From ab56290421bc00284fe8192602fc706d3186cd3f Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 16:00:25 +0100 Subject: [PATCH 01/37] Add SwiftRuntimeLibrary project The SwiftRuntimeLibrary includes C# implementation of Swift types used for marshalling. This commit adds initial layout of the project. --- src/SwiftRuntimeLibrary/Exceptions.cs | 24 +++++++++++++++++++ src/SwiftRuntimeLibrary/ISwiftObject.cs | 12 ++++++++++ .../SwiftRuntimeLibrary.csproj | 9 +++++++ 3 files changed, 45 insertions(+) create mode 100644 src/SwiftRuntimeLibrary/Exceptions.cs create mode 100644 src/SwiftRuntimeLibrary/ISwiftObject.cs create mode 100644 src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj diff --git a/src/SwiftRuntimeLibrary/Exceptions.cs b/src/SwiftRuntimeLibrary/Exceptions.cs new file mode 100644 index 000000000000..6a1bdb68351d --- /dev/null +++ b/src/SwiftRuntimeLibrary/Exceptions.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SwiftRuntimeLibrary { + public static class Exceptions { + public static T ThrowOnNull(T o, string name, string message = null) where T : class + { + if (o == null) + ThrowArgumentNull(name, message); + return o!; + } + + static void ThrowArgumentNull(string name, string message = null) + { + name = name ?? "::no name supplied::"; + if (message == null) + throw new ArgumentNullException(name); + else + throw new ArgumentNullException(name, message); + } + } +} diff --git a/src/SwiftRuntimeLibrary/ISwiftObject.cs b/src/SwiftRuntimeLibrary/ISwiftObject.cs new file mode 100644 index 000000000000..0538401dee23 --- /dev/null +++ b/src/SwiftRuntimeLibrary/ISwiftObject.cs @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +namespace SwiftRuntimeLibrary { + public unsafe interface ISwiftObject : IDisposable { + void* SwiftObject { get; } + } +} + diff --git a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj new file mode 100644 index 000000000000..a71289817ef0 --- /dev/null +++ b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj @@ -0,0 +1,9 @@ + + + Library + net7.0 + enable + disable + true + + From 49bd30d507584f377a910ebee16024f5590de6fc Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 16:05:49 +0100 Subject: [PATCH 02/37] Add SyntaxDynamo project The SyntaxDynamo is a code generator for C# source code generation. Also, it contains Swift syntax and is used as a parser for API aggregation. --- src/SyntaxDynamo/CodeElementCollection.cs | 60 +++ src/SyntaxDynamo/CodeWriter.cs | 149 +++++++ .../CommaListElementCollection.cs | 84 ++++ .../DecoratedCodeElementCollection.cs | 79 ++++ .../DelegatedCommaListElementCollection.cs | 59 +++ src/SyntaxDynamo/DelegatedSimpleElement.cs | 53 +++ src/SyntaxDynamo/Exceptions.cs | 21 + src/SyntaxDynamo/Extensions.cs | 68 +++ src/SyntaxDynamo/ICodeElement.cs | 24 ++ src/SyntaxDynamo/ICodeElementSet.cs | 11 + src/SyntaxDynamo/ICodeWriter.cs | 18 + .../LabeledCodeElementCollection.cs | 64 +++ src/SyntaxDynamo/LineCodeElementCollection.cs | 53 +++ src/SyntaxDynamo/SimpleElement.cs | 59 +++ src/SyntaxDynamo/SimpleLineElement.cs | 64 +++ .../SyntaxDynamo.CSLang/CSArgument.cs | 35 ++ .../SyntaxDynamo.CSLang/CSArray1D.cs | 115 ++++++ .../SyntaxDynamo.CSLang/CSAssignment.cs | 79 ++++ .../SyntaxDynamo.CSLang/CSAttribute.cs | 89 ++++ .../SyntaxDynamo.CSLang/CSBaseExpression.cs | 97 +++++ .../SyntaxDynamo.CSLang/CSBinaryExpression.cs | 80 ++++ .../SyntaxDynamo.CSLang/CSBinding.cs | 79 ++++ .../SyntaxDynamo.CSLang/CSClass.cs | 205 +++++++++ .../SyntaxDynamo.CSLang/CSCodeBlock.cs | 52 +++ .../SyntaxDynamo.CSLang/CSComment.cs | 56 +++ .../CSConditionalCompilation.cs | 37 ++ .../SyntaxDynamo.CSLang/CSConstant.cs | 72 ++++ .../SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs | 41 ++ .../SyntaxDynamo.CSLang/CSEnum.cs | 101 +++++ .../SyntaxDynamo.CSLang/CSFieldDeclaration.cs | 106 +++++ .../SyntaxDynamo.CSLang/CSFile.cs | 71 ++++ .../SyntaxDynamo.CSLang/CSFileBasic.cs | 65 +++ .../SyntaxDynamo.CSLang/CSFixed.cs | 35 ++ .../SyntaxDynamo.CSLang/CSForEach.cs | 60 +++ .../SyntaxDynamo.CSLang/CSFunctionCall.cs | 132 ++++++ .../CSGenericConstraint.cs | 81 ++++ .../CSGenericTypeDeclaration.cs | 71 ++++ .../SyntaxDynamo.CSLang/CSIdentifier.cs | 39 ++ .../SyntaxDynamo.CSLang/CSIfElse.cs | 58 +++ .../SyntaxDynamo.CSLang/CSIndexExpression.cs | 43 ++ .../SyntaxDynamo.CSLang/CSInheritance.cs | 29 ++ .../SyntaxDynamo.CSLang/CSInitializer.cs | 46 +++ .../SyntaxDynamo.CSLang/CSInject.cs | 19 + .../SyntaxDynamo.CSLang/CSInterface.cs | 119 ++++++ .../SyntaxDynamo.CSLang/CSLambda.cs | 72 ++++ .../SyntaxDynamo.CSLang/CSLine.cs | 30 ++ .../SyntaxDynamo.CSLang/CSMethod.cs | 231 +++++++++++ .../SyntaxDynamo.CSLang/CSNamespace.cs | 51 +++ .../SyntaxDynamo.CSLang/CSParameter.cs | 109 +++++ .../CSParenthesisExpression.cs | 47 +++ .../SyntaxDynamo.CSLang/CSProperty.cs | 190 +++++++++ .../SyntaxDynamo.CSLang/CSReturn.cs | 26 ++ .../SyntaxDynamo.CSLang/CSShortCircuit.cs | 32 ++ .../SyntaxDynamo.CSLang/CSTernary.cs | 40 ++ .../SyntaxDynamo.CSLang/CSThrow.cs | 46 +++ .../SyntaxDynamo.CSLang/CSTryCatch.cs | 78 ++++ .../SyntaxDynamo.CSLang/CSType.cs | 256 ++++++++++++ .../SyntaxDynamo.CSLang/CSUnaryExpression.cs | 110 +++++ .../SyntaxDynamo.CSLang/CSUsing.cs | 60 +++ src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs | 93 +++++ .../SyntaxDynamo.CSLang/ICSExpression.cs | 14 + .../SyntaxDynamo.CSLang/ICSLineable.cs | 10 + .../SyntaxDynamo.CSLang/ICSStatement.cs | 10 + .../ICSTopLevelDeclaration.cs | 18 + .../SyntaxDynamo.SwiftLang/Enums.cs | 89 ++++ .../SyntaxDynamo.SwiftLang/ISLExpr.cs | 11 + .../SyntaxDynamo.SwiftLang/ISLLineable.cs | 8 + .../SyntaxDynamo.SwiftLang/ISLStatement.cs | 8 + .../SyntaxDynamo.SwiftLang/SLAddressOf.cs | 29 ++ .../SyntaxDynamo.SwiftLang/SLArgument.cs | 35 ++ .../SyntaxDynamo.SwiftLang/SLAsExpr.cs | 19 + .../SyntaxDynamo.SwiftLang/SLAttribute.cs | 81 ++++ .../SyntaxDynamo.SwiftLang/SLBaseExpr.cs | 82 ++++ .../SyntaxDynamo.SwiftLang/SLBinaryExpr.cs | 93 +++++ .../SyntaxDynamo.SwiftLang/SLBinding.cs | 54 +++ .../SyntaxDynamo.SwiftLang/SLClass.cs | 163 ++++++++ .../SyntaxDynamo.SwiftLang/SLClosure.cs | 39 ++ .../SyntaxDynamo.SwiftLang/SLClosureCall.cs | 26 ++ .../SyntaxDynamo.SwiftLang/SLCodeBlock.cs | 35 ++ .../SyntaxDynamo.SwiftLang/SLCommaListExpr.cs | 30 ++ .../SyntaxDynamo.SwiftLang/SLComment.cs | 42 ++ .../SLConditionalCompilation.cs | 48 +++ .../SyntaxDynamo.SwiftLang/SLConstant.cs | 69 ++++ .../SyntaxDynamo.SwiftLang/SLDeclaration.cs | 63 +++ .../SyntaxDynamo.SwiftLang/SLDoCatch.cs | 63 +++ .../SyntaxDynamo.SwiftLang/SLFile.cs | 75 ++++ .../SyntaxDynamo.SwiftLang/SLFunc.cs | 162 ++++++++ .../SyntaxDynamo.SwiftLang/SLFunctionCall.cs | 68 +++ .../SLGenericConstraint.cs | 26 ++ .../SLGenericTypeDeclaration.cs | 111 +++++ .../SyntaxDynamo.SwiftLang/SLIdentifier.cs | 29 ++ .../SyntaxDynamo.SwiftLang/SLIfElse.cs | 61 +++ .../SyntaxDynamo.SwiftLang/SLImport.cs | 83 ++++ .../SyntaxDynamo.SwiftLang/SLInheritance.cs | 21 + .../SyntaxDynamo.SwiftLang/SLInject.cs | 19 + .../SyntaxDynamo.SwiftLang/SLLetMatch.cs | 30 ++ .../SyntaxDynamo.SwiftLang/SLLine.cs | 29 ++ .../SLLineableOperator.cs | 24 ++ .../SyntaxDynamo.SwiftLang/SLNameTypePair.cs | 66 +++ .../SLNamedClosureCall.cs | 26 ++ .../SyntaxDynamo.SwiftLang/SLParameter.cs | 73 ++++ .../SyntaxDynamo.SwiftLang/SLParameterList.cs | 40 ++ .../SLParenthesisExpression.cs | 21 + .../SyntaxDynamo.SwiftLang/SLPostBang.cs | 32 ++ .../SyntaxDynamo.SwiftLang/SLProperty.cs | 63 +++ .../SyntaxDynamo.SwiftLang/SLReturn.cs | 26 ++ .../SyntaxDynamo.SwiftLang/SLSubscript.cs | 73 ++++ .../SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs | 37 ++ .../SyntaxDynamo.SwiftLang/SLSwitch.cs | 107 +++++ .../SyntaxDynamo.SwiftLang/SLThrow.cs | 25 ++ .../SyntaxDynamo.SwiftLang/SLTryBang.cs | 30 ++ .../SyntaxDynamo.SwiftLang/SLTupleExpr.cs | 29 ++ .../SyntaxDynamo.SwiftLang/SLType.cs | 389 ++++++++++++++++++ .../SyntaxDynamo.SwiftLang/SLUnaryExpr.cs | 36 ++ .../SyntaxDynamo.SwiftLang/SLVariadicExpr.cs | 28 ++ src/SyntaxDynamo/SyntaxDynamo.csproj | 12 + src/SyntaxDynamo/WriteEventArgs.cs | 18 + 117 files changed, 7457 insertions(+) create mode 100644 src/SyntaxDynamo/CodeElementCollection.cs create mode 100644 src/SyntaxDynamo/CodeWriter.cs create mode 100644 src/SyntaxDynamo/CommaListElementCollection.cs create mode 100644 src/SyntaxDynamo/DecoratedCodeElementCollection.cs create mode 100644 src/SyntaxDynamo/DelegatedCommaListElementCollection.cs create mode 100644 src/SyntaxDynamo/DelegatedSimpleElement.cs create mode 100644 src/SyntaxDynamo/Exceptions.cs create mode 100644 src/SyntaxDynamo/Extensions.cs create mode 100644 src/SyntaxDynamo/ICodeElement.cs create mode 100644 src/SyntaxDynamo/ICodeElementSet.cs create mode 100644 src/SyntaxDynamo/ICodeWriter.cs create mode 100644 src/SyntaxDynamo/LabeledCodeElementCollection.cs create mode 100644 src/SyntaxDynamo/LineCodeElementCollection.cs create mode 100644 src/SyntaxDynamo/SimpleElement.cs create mode 100644 src/SyntaxDynamo/SimpleLineElement.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs create mode 100644 src/SyntaxDynamo/SyntaxDynamo.csproj create mode 100644 src/SyntaxDynamo/WriteEventArgs.cs diff --git a/src/SyntaxDynamo/CodeElementCollection.cs b/src/SyntaxDynamo/CodeElementCollection.cs new file mode 100644 index 000000000000..251a0e5e5256 --- /dev/null +++ b/src/SyntaxDynamo/CodeElementCollection.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo { + public class CodeElementCollection : List, ICodeElementSet where T : ICodeElement { + public CodeElementCollection () : base () + { + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + + #endregion + + #region ICodeElemSet implementation + + public System.Collections.Generic.IEnumerable Elements { + get { + return this.Cast (); + } + } + + #endregion + + } +} + diff --git a/src/SyntaxDynamo/CodeWriter.cs b/src/SyntaxDynamo/CodeWriter.cs new file mode 100644 index 000000000000..8789ccc2fd71 --- /dev/null +++ b/src/SyntaxDynamo/CodeWriter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using System.IO; + +namespace SyntaxDynamo { + public class CodeWriter : ICodeWriter { + int charsWrittenThisLine; + bool indentedThisLine; + + const int kSpacesPerIndent = 4; + const int kWrapPoint = 60; + + public CodeWriter (Stream stm) + : this (new StreamWriter (Exceptions.ThrowOnNull (stm, "stm"))) + { + } + + public CodeWriter (TextWriter tw) + { + TextWriter = Exceptions.ThrowOnNull (tw, "tw"); + charsWrittenThisLine = 0; + IndentLevel = 0; + IsAtLineStart = true; + } + + public static void WriteToFile (string fileName, ICodeElement element) + { + using (var stm = new FileStream (fileName, FileMode.Create)) { + CodeWriter writer = new CodeWriter (stm); + element.WriteAll (writer); + writer.TextWriter.Flush (); + } + } + + public static Stream WriteToStream (ICodeElement element) + { + var stm = new MemoryStream (); + var codeWriter = new CodeWriter (stm); + element.WriteAll (codeWriter); + codeWriter.TextWriter.Flush (); + stm.Flush (); + stm.Seek (0, SeekOrigin.Begin); + return stm; + } + + public static string WriteToString (ICodeElement element) + { + using (var reader = new StreamReader (WriteToStream (element))) + return reader.ReadToEnd (); + } + + public TextWriter TextWriter { get; private set; } + + #region ICodeWriter implementation + + public void BeginNewLine (bool prependIndents) + { + Write (Environment.NewLine, false); + if (prependIndents) + WriteIndents (); + IsAtLineStart = true; + } + + public void EndLine () + { + charsWrittenThisLine = 0; + if (indentedThisLine) { + indentedThisLine = false; + // strictly speaking, this test shouldn't be necessary + if (IndentLevel > 0) + Exdent (); + } + } + + public bool IsAtLineStart { get; private set; } + + public void Write (string code, bool allowSplit) + { + var characterEnum = StringInfo.GetTextElementEnumerator (code); + while (characterEnum.MoveNext ()) { + string c = characterEnum.GetTextElement (); + WriteUnicode (c, allowSplit); + } + } + + public void Write (char c, bool allowSplit) + { + Write (c.ToString (), allowSplit); + } + + void WriteUnicode (string c, bool allowSplit) + { + var info = new StringInfo (c); + if (info.LengthInTextElements > 1) + throw new ArgumentOutOfRangeException (nameof (c), $"Expected a single unicode value but got '{c}'"); + WriteNoBookKeeping (c); + IsAtLineStart = false; + charsWrittenThisLine++; + if (allowSplit && charsWrittenThisLine > kWrapPoint && IsWhiteSpace (c)) { + if (!indentedThisLine) { + Indent (); + indentedThisLine = true; + } + WriteNoBookKeeping (Environment.NewLine); + charsWrittenThisLine = 0; + WriteIndents (); + IsAtLineStart = true; + } + } + + bool IsWhiteSpace (string c) { + return c.Length == 1 && Char.IsWhiteSpace (c[0]); + + } + + void WriteNoBookKeeping (string s) + { + TextWriter.Write (s); + } + + void WriteIndents () + { + int totalSpaces = IndentLevel * kSpacesPerIndent; + // know what's embarrassing? When your indents cause breaks which generates more indents. + for (int i = 0; i < totalSpaces; i++) + Write (" ", false); + } + + public void Indent () + { + IndentLevel++; + } + + public void Exdent () + { + if (IndentLevel == 0) + throw new Exception ("IndentLevel is at 0."); + IndentLevel--; + } + + public int IndentLevel { get; private set; } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/CommaListElementCollection.cs b/src/SyntaxDynamo/CommaListElementCollection.cs new file mode 100644 index 000000000000..a314d203e28c --- /dev/null +++ b/src/SyntaxDynamo/CommaListElementCollection.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo { + public class CommaListElementCollection : List, ICodeElement where T : ICodeElement { + public CommaListElementCollection () + : this ("", "") + { + } + + + public CommaListElementCollection (IEnumerable objs) + : this ("", "", objs) + { + } + + public CommaListElementCollection (string prefix, string suffix) + : base () + { + Prefix = Exceptions.ThrowOnNull (prefix, nameof (prefix)); + Suffix = Exceptions.ThrowOnNull (suffix, nameof (suffix)); + } + + public CommaListElementCollection (string prefix, string suffix, IEnumerable objs, bool newlineAfterEach = false) + : this (prefix, suffix) + { + AddRange (Exceptions.ThrowOnNull (objs, nameof (objs))); + NewlineAfterEach = newlineAfterEach; + } + + + public string Prefix { get; private set; } + public string Suffix { get; private set; } + public bool NewlineAfterEach { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + writer.Write (Prefix, true); + for (int i = 0; i < Count; i++) { + this [i].WriteAll (writer); + if (i < Count - 1) + writer.Write (", ", true); + if (NewlineAfterEach && !writer.IsAtLineStart) { + writer.BeginNewLine (true); + } + } + writer.Write (Suffix, true); + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/DecoratedCodeElementCollection.cs b/src/SyntaxDynamo/DecoratedCodeElementCollection.cs new file mode 100644 index 000000000000..3b3f4f19d9fe --- /dev/null +++ b/src/SyntaxDynamo/DecoratedCodeElementCollection.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace SyntaxDynamo { + public class DecoratedCodeElementCollection : CodeElementCollection where T : ICodeElement { + bool startOnOwnLine, endOnOwnLine, indent; + + public DecoratedCodeElementCollection (string startDecoration, string endDecoration, + bool startOnOwnLine, bool endOnOwnLine, bool indent, + IEnumerable elems) + : base () + { + StartDecoration = startDecoration; + EndDecoration = endDecoration; + this.startOnOwnLine = startOnOwnLine; + this.endOnOwnLine = endOnOwnLine; + this.indent = indent; + if (elems != null) + AddRange (elems); + } + + public DecoratedCodeElementCollection (string startDecoration, string endDecoration, + bool startOnOwnLine, bool endOnOwnLine, bool indent) + : this (startDecoration, endDecoration, startOnOwnLine, endOnOwnLine, indent, null) + { + } + + public string StartDecoration { get; private set; } + public string EndDecoration { get; private set; } + + public override void Write (ICodeWriter writer, object o) + { + if (StartDecoration != null) { + if (startOnOwnLine) + writer.BeginNewLine (true); + writer.Write (StartDecoration, true); + if (startOnOwnLine) + writer.EndLine (); + } + if (indent) + writer.Indent (); + } + + public override void EndWrite (ICodeWriter writer, object o) + { + if (indent) + writer.Exdent (); + if (EndDecoration != null) { + if (endOnOwnLine) + writer.BeginNewLine (true); + writer.Write (EndDecoration, true); + if (endOnOwnLine) + writer.EndLine (); + } + + base.EndWrite (writer, o); + } + + public override string ToString () + { + return string.Format ("{0}{1}{2}", + StartDecoration ?? "", + StartDecoration != null && EndDecoration != null ? "..." : "", + EndDecoration ?? ""); + } + + + public static DecoratedCodeElementCollection CBlock (IEnumerable elems) + { + var col = new DecoratedCodeElementCollection ("{", "}", true, true, true); + if (elems != null) + col.AddRange (elems); + return col; + } + } +} + diff --git a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs new file mode 100644 index 000000000000..9e4c9d6e25bc --- /dev/null +++ b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo { + public class DelegatedCommaListElemCollection : List, ICodeElement where T : ICodeElement { + Action elementWriter; + public DelegatedCommaListElemCollection (Action elementWriter) + : base () + { + this.elementWriter = Exceptions.ThrowOnNull (elementWriter, nameof(elementWriter)); + } + + public DelegatedCommaListElemCollection (Action elementWriter, IEnumerable objs) + : base () + { + this.elementWriter = Exceptions.ThrowOnNull (elementWriter, nameof (elementWriter)); + AddRange (Exceptions.ThrowOnNull (objs, nameof(objs))); + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + for (int i = 0; i < Count; i++) { + elementWriter (writer, i, this [i]); + if (i < Count - 1) + writer.Write (", ", true); + } + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + } +} + diff --git a/src/SyntaxDynamo/DelegatedSimpleElement.cs b/src/SyntaxDynamo/DelegatedSimpleElement.cs new file mode 100644 index 000000000000..e9b9ca177a93 --- /dev/null +++ b/src/SyntaxDynamo/DelegatedSimpleElement.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public abstract class DelegatedSimpleElement : ICodeElement { + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + LLWrite (writer, o); + } + + protected abstract void LLWrite (ICodeWriter writer, object o); + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + } + + public class LineBreak : DelegatedSimpleElement { + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.EndLine (); + writer.BeginNewLine (true); + } + } +} + diff --git a/src/SyntaxDynamo/Exceptions.cs b/src/SyntaxDynamo/Exceptions.cs new file mode 100644 index 000000000000..5d6aa86c3599 --- /dev/null +++ b/src/SyntaxDynamo/Exceptions.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public class Exceptions { + public static T ThrowOnNull (T o, string name, string message = null) where T : class + { + name = name ?? "::no name supplied::"; + if (o == null) { + if (message == null) + throw new ArgumentNullException (name); + else + throw new ArgumentNullException (name, message); + } + return o; + } + } +} + diff --git a/src/SyntaxDynamo/Extensions.cs b/src/SyntaxDynamo/Extensions.cs new file mode 100644 index 000000000000..fb1471437098 --- /dev/null +++ b/src/SyntaxDynamo/Extensions.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo { + public static class Extensions { + public static void WriteAll (this ICodeElement elem, ICodeWriter writer) + { + object memento = elem.BeginWrite (writer); + elem.Write (writer, memento); + ICodeElementSet set = elem as ICodeElementSet; + if (set != null) { + foreach (ICodeElement sub in set.Elements) { + sub.WriteAll (writer); + } + } + elem.EndWrite (writer, memento); + } + + public static void FireInReverse (this EventHandler handler, object sender, EventArgs args) where T : EventArgs + { + var dels = handler.GetInvocationList (); + for (int i = dels.Length - 1; i >= 0; i--) { + dels [i].DynamicInvoke (new object [] { sender, args }); + } + } + + public static IEnumerable Interleave (this IEnumerable contents, T separator, bool includeSeparatorFirst = false) + { + bool first = true; + foreach (T t in contents) { + if (!first || includeSeparatorFirst) + yield return separator; + first = false; + yield return t; + } + } + + public static IEnumerable BracketInterleave (this IEnumerable contents, T start, T end, T separator, bool includeSeparatorFirst = false) + { + yield return start; + foreach (T t in contents.Interleave (separator, includeSeparatorFirst)) + yield return t; + yield return end; + } + + public static T AttachBefore (this T attacher, ICodeElement attachTo) where T : ICodeElement + { + Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); + attachTo.Begin += (s, eventArgs) => { + attacher.WriteAll (eventArgs.Writer); + }; + return attacher; + } + + public static T AttachAfter (this T attacher, ICodeElement attachTo) where T : ICodeElement + { + Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); + attachTo.End += (s, eventArgs) => { + attacher.WriteAll (eventArgs.Writer); + }; + return attacher; + } + } +} + diff --git a/src/SyntaxDynamo/ICodeElement.cs b/src/SyntaxDynamo/ICodeElement.cs new file mode 100644 index 000000000000..855364f31605 --- /dev/null +++ b/src/SyntaxDynamo/ICodeElement.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public interface ICodeElement { + // these three methods represent the memento pattern. The object returned is only ever used by + // the ICodeElem. + object BeginWrite (ICodeWriter writer); + void Write (ICodeWriter writer, object o); + void EndWrite (ICodeWriter writer, object o); + + // These events seem redundant, but they are intended for use for non-structural code elements + // such as block comments or #region or #if/#else/#endif + + // Begin should be fired by BeginWrite BEFORE anything is written + event EventHandler Begin; + // Note, when you implement End, it should use GetInvocationList and fire in reverse order. + // End should be fired by EndWrite AFTER anything is written + event EventHandler End; + } +} + diff --git a/src/SyntaxDynamo/ICodeElementSet.cs b/src/SyntaxDynamo/ICodeElementSet.cs new file mode 100644 index 000000000000..63c13176bb0f --- /dev/null +++ b/src/SyntaxDynamo/ICodeElementSet.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace SyntaxDynamo { + public interface ICodeElementSet : ICodeElement { + IEnumerable Elements { get; } + } +} + diff --git a/src/SyntaxDynamo/ICodeWriter.cs b/src/SyntaxDynamo/ICodeWriter.cs new file mode 100644 index 000000000000..0871e20fac6e --- /dev/null +++ b/src/SyntaxDynamo/ICodeWriter.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public interface ICodeWriter { + void BeginNewLine (bool prependIndents); + void EndLine (); + void Write (char c, bool allowSplit); + void Write (string code, bool allowSplit); + void Indent (); + void Exdent (); + int IndentLevel { get; } + bool IsAtLineStart { get; } + } +} + diff --git a/src/SyntaxDynamo/LabeledCodeElementCollection.cs b/src/SyntaxDynamo/LabeledCodeElementCollection.cs new file mode 100644 index 000000000000..c4ec14215dd2 --- /dev/null +++ b/src/SyntaxDynamo/LabeledCodeElementCollection.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo { + public class LabeledCodeElementCollection : ICodeElementSet where T : ICodeElement { + public LabeledCodeElementCollection (SimpleLineElement label, CodeElementCollection block) + { + Label = Exceptions.ThrowOnNull (label, nameof(label)); + Block = Exceptions.ThrowOnNull (block, nameof(block)); + } + + public SimpleLineElement Label { get; private set; } + public CodeElementCollection Block { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + yield return Label; + yield return Block; + } + } + + #endregion + + } +} + diff --git a/src/SyntaxDynamo/LineCodeElementCollection.cs b/src/SyntaxDynamo/LineCodeElementCollection.cs new file mode 100644 index 000000000000..5b750cd86243 --- /dev/null +++ b/src/SyntaxDynamo/LineCodeElementCollection.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace SyntaxDynamo { + public class LineCodeElementCollection : CodeElementCollection where T : ICodeElement { + bool indent, prependIndents, isSingleLine; + public LineCodeElementCollection (IEnumerable elems, bool indent, bool prependIndents) + : this (elems, true, indent, prependIndents) + { + } + + public LineCodeElementCollection (bool isSingleLine, bool indent, bool prependIndents) + : this (null, isSingleLine, indent, prependIndents) + { + } + + public LineCodeElementCollection (IEnumerable elems, bool isSingleLine, bool indent, bool prependIndents) + { + this.isSingleLine = isSingleLine; + this.indent = indent; + this.prependIndents = prependIndents; + if (elems != null) + AddRange (elems); + } + + + public override void Write (ICodeWriter writer, object o) + { + if (isSingleLine) { + if (indent) + writer.Indent (); + writer.BeginNewLine (prependIndents); + } + } + + protected override void OnEndWrite (WriteEventArgs args) + { + if (isSingleLine) + args.Writer.EndLine (); + base.OnEndWrite (args); + } + + public LineCodeElementCollection And (T elem) + { + Add (elem); + return this; + } + + } +} + diff --git a/src/SyntaxDynamo/SimpleElement.cs b/src/SyntaxDynamo/SimpleElement.cs new file mode 100644 index 000000000000..46ccad436d5d --- /dev/null +++ b/src/SyntaxDynamo/SimpleElement.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public class SimpleElement : ICodeElement { + bool allowSplit; + public SimpleElement (string label, bool allowSplit = false) + { + Label = label; + this.allowSplit = allowSplit; + } + + public string Label { get; private set; } + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + writer.Write (Label, allowSplit); + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + public override string ToString () + { + return Label; + } + + static SimpleElement spacer = new SimpleElement (" ", true); + public static SimpleElement Spacer { get { return spacer; } } + } +} + diff --git a/src/SyntaxDynamo/SimpleLineElement.cs b/src/SyntaxDynamo/SimpleLineElement.cs new file mode 100644 index 000000000000..63e70582604d --- /dev/null +++ b/src/SyntaxDynamo/SimpleLineElement.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public class SimpleLineElement : ICodeElement { + bool indent, prependIndents, allowSplit; + + public SimpleLineElement (string contents, bool indent, bool prependIdents, bool allowSplit) + { + Contents = contents ?? ""; + this.indent = indent; + this.prependIndents = prependIdents; + this.allowSplit = allowSplit; + } + + public string Contents { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + if (indent) + writer.Indent (); + writer.BeginNewLine (prependIndents); + writer.Write (Contents, allowSplit); + writer.EndLine (); + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + public override string ToString () + { + return Contents; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs new file mode 100644 index 000000000000..11c5acda9d99 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.CSLang { + public class CSArgument : DelegatedSimpleElement { + public CSArgument (ICSExpression expr) + { + Value = Exceptions.ThrowOnNull (expr, nameof(expr)); + } + + public ICSExpression Value { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Value.WriteAll (writer); + } + } + + public class CSArgumentList : CommaListElementCollection { + + public void Add (ICSExpression expr) + { + Add (new CSArgument (expr)); + } + + public static CSArgumentList FromExpressions (params ICSExpression [] exprs) + { + var al = new CSArgumentList (); + foreach (var ex in exprs) + al.Add (new CSArgument (ex)); + return al; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs new file mode 100644 index 000000000000..01bca40d5272 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang +{ + public class CSArray1D : CSBaseExpression + { + public CSArray1D (CSIdentifier name, CommaListElementCollection paramList) + { + Name = Exceptions.ThrowOnNull (name, "name"); + Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); + } + + public CSArray1D(string name, params CSBaseExpression[] parameters) + : this(new CSIdentifier(name), new CommaListElementCollection(parameters)) + { + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Name.WriteAll (writer); + writer.Write ("[", false); + Parameters.WriteAll (writer); + writer.Write ("]", false); + } + + public CSIdentifier Name { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + public static CSArray1D New(CSSimpleType type, bool isStackAlloc, params CSBaseExpression[] parameters) + { + string ID = (isStackAlloc ? "stackalloc " : "new ") + type.Name; + return new CSArray1D (ID, parameters); + } + } + + public class CSArray1DInitialized : CSBaseExpression { + public CSArray1DInitialized(CSType type, CommaListElementCollection initializers) + { + Type = Exceptions.ThrowOnNull (type, "type"); + Parameters = Exceptions.ThrowOnNull (initializers, "initializers"); + } + + public CSArray1DInitialized(CSType type, params CSBaseExpression[] parameters) + : this(type, new CommaListElementCollection(parameters)) + { + } + + public CSArray1DInitialized(string typeName, params CSBaseExpression[] parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSArray1DInitialized(string typeName, IEnumerable parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("new ", true); + Type.WriteAll (writer); + writer.Write ("[", false); + writer.Write ("] ", true); + writer.Write ("{ ", true); + Parameters.WriteAll (writer); + writer.Write ("}", false); + } + + } + + public class CSListInitialized : CSBaseExpression { + public CSListInitialized (CSType type, CommaListElementCollection initializers) + { + Type = Exceptions.ThrowOnNull (type, "type"); + Parameters = Exceptions.ThrowOnNull (initializers, "initializers"); + } + + public CSListInitialized (CSType type, params CSBaseExpression [] parameters) + : this (type, new CommaListElementCollection (parameters)) + { + } + + public CSListInitialized (string typeName, params CSBaseExpression [] parameters) + : this (new CSSimpleType (typeName), new CommaListElementCollection (parameters)) + { + } + + public CSListInitialized (string typeName, IEnumerable parameters) + : this (new CSSimpleType (typeName), new CommaListElementCollection (parameters)) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("new List<", true); + Type.WriteAll (writer); + writer.Write (">", true); + writer.Write ("(", false); + writer.Write (") ", true); + writer.Write ("{ ", true); + Parameters.WriteAll (writer); + writer.Write ("}", false); + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs new file mode 100644 index 000000000000..db23c117c330 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSAssignment : CSBaseExpression, ICSLineable { + public CSAssignment (CSBaseExpression lhs, CSAssignmentOperator op, CSBaseExpression rhs) + { + Target = Exceptions.ThrowOnNull (lhs, "lhs"); + Value = Exceptions.ThrowOnNull (rhs, "rhs"); + Operation = op; + } + + public CSAssignment(string lhs, CSAssignmentOperator op, CSBaseExpression rhs) + : this(new CSIdentifier(Exceptions.ThrowOnNull(lhs, "lhs")), op, rhs) + { + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Target.WriteAll (writer); + writer.Write (string.Format (" {0} ", ToAssignmentOpString (Operation)), true); + Value.WriteAll (writer); + } + + public CSBaseExpression Target { get; private set; } + public CSBaseExpression Value { get; private set; } + public CSAssignmentOperator Operation { get; private set; } + + static string ToAssignmentOpString(CSAssignmentOperator op) + { + switch (op) { + case CSAssignmentOperator.Assign: + return "="; + case CSAssignmentOperator.AddAssign: + return "+="; + case CSAssignmentOperator.SubAssign: + return "-="; + case CSAssignmentOperator.MulAssign: + return "*="; + case CSAssignmentOperator.DivAssign: + return "/="; + case CSAssignmentOperator.ModAssign: + return "%="; + case CSAssignmentOperator.AndAssign: + return "&="; + case CSAssignmentOperator.OrAssign: + return "|="; + case CSAssignmentOperator.XorAssign: + return "^="; + default: + throw new ArgumentOutOfRangeException ("op"); + } + } + + public static CSLine Assign(string name, CSAssignmentOperator op, CSBaseExpression value) + { + return new CSLine (new CSAssignment (name, op, value)); + } + + public static CSLine Assign(string name, CSBaseExpression value) + { + return Assign (name, CSAssignmentOperator.Assign, value); + } + + public static CSLine Assign(CSBaseExpression name, CSBaseExpression value) + { + return Assign (name, CSAssignmentOperator.Assign, value); + } + + public static CSLine Assign(CSBaseExpression name, CSAssignmentOperator op, CSBaseExpression value) + { + return new CSLine (new CSAssignment (name, op, value)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs new file mode 100644 index 000000000000..56504c47c3ae --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +namespace SyntaxDynamo.CSLang { + public class CSAttribute : LineCodeElementCollection { + public CSAttribute (CSIdentifier name, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) + : base (isSingleLine, false, isSingleLine) + { + Add (new SimpleElement ("[")); + if (isReturn) + Add (new SimpleElement ("return:")); + Add (Exceptions.ThrowOnNull (name, nameof(name))); + if (args != null) { + Add (new SimpleElement ("(")); + Add (args); + Add (new SimpleElement (")")); + } + Add (new SimpleElement ("]")); + } + + public CSAttribute (string name, CSArgumentList args) + : this (new CSIdentifier (name), args) + { + } + + public CSAttribute (string name, params ICSExpression [] exprs) + : this (new CSIdentifier(name), CSArgumentList.FromExpressions (exprs)) + { + } + + // DllImport("msvcrt.dll", EntryPoint="puts") + public static CSAttribute DllImport (string dllName, string entryPoint = null) + { + CSArgumentList args = new CSArgumentList (); + args.Add (CSConstant.Val (dllName)); + if (entryPoint != null) + args.Add (new CSAssignment ("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val (entryPoint))); + return new CSAttribute (new CSIdentifier ("DllImport"), args, true); + } + + public static CSAttribute DllImport (CSBaseExpression dllName, string entryPoint = null) + { + CSArgumentList args = new CSArgumentList (); + args.Add (dllName); + if (entryPoint != null) + args.Add (new CSAssignment ("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val (entryPoint))); + return new CSAttribute (new CSIdentifier ("DllImport"), args, true); + } + + static CSAttribute returnMarshalAsI1 = new CSAttribute ("return: MarshalAs", new CSIdentifier ("UnmanagedType.I1")); + + public static CSAttribute ReturnMarshalAsI1 => returnMarshalAsI1; + + public static CSAttribute FieldOffset (int offset) + { + CSArgumentList args = new CSArgumentList (); + args.Add (CSConstant.Val (offset)); + return new CSAttribute (new CSIdentifier ("FieldOffset"), args, true); + } + + public static CSAttribute LayoutKind (LayoutKind layout) + { + CSArgumentList args = new CSArgumentList (); + args.Add (new CSIdentifier (String.Format ("LayoutKind.{0}", layout))); + return new CSAttribute (new CSIdentifier ("StructLayout"), args, true); + } + + public static CSAttribute FromAttr (Type attribute, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) + { + Exceptions.ThrowOnNull (attribute, nameof(attribute)); + if (!attribute.IsSubclassOf (typeof (Attribute))) + throw new ArgumentException (String.Format ("Type {0} is not an Attribute type.", attribute.Name), nameof(attribute)); + var name = attribute.Name.EndsWith ("Attribute") ? + attribute.Name.Substring (0, attribute.Name.Length - "Attribute".Length) : attribute.Name; + return new CSAttribute (new CSIdentifier (name), args, isSingleLine, isReturn); + } + + public static CSAttribute MarshalAsFunctionPointer () + { + CSArgumentList list = new CSArgumentList (); + list.Add (new CSArgument (new CSIdentifier ("UnmanagedType.FunctionPtr"))); + return FromAttr (typeof (MarshalAsAttribute), list, false); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs new file mode 100644 index 000000000000..92a71f61eaa0 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public abstract class CSBaseExpression : DelegatedSimpleElement, ICSExpression { + public CSBaseExpression Dot (CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Dot, this, rhs); + } + public static CSBaseExpression operator + (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Add, lhs, rhs); + } + public static CSBaseExpression operator - (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Sub, lhs, rhs); + } + public static CSBaseExpression operator * (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Mul, lhs, rhs); + } + public static CSBaseExpression operator / (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Div, lhs, rhs); + } + public static CSBaseExpression operator % (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Mod, lhs, rhs); + } + public static CSBaseExpression operator < (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Less, lhs, rhs); + } + public static CSBaseExpression operator > (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Greater, lhs, rhs); + } + public static CSBaseExpression operator == (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.Equal, lhs, rhs); + } + public static CSBaseExpression operator != (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.NotEqual, lhs, rhs); + } + public static CSBaseExpression operator <= (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.LessEqual, lhs, rhs); + } + public static CSBaseExpression operator >= (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.GreaterEqual, lhs, rhs); + } + public static CSBaseExpression operator & (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.BitAnd, lhs, rhs); + } + public static CSBaseExpression operator | (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.BitOr, lhs, rhs); + } + public static CSBaseExpression operator ^ (CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression (CSBinaryOperator.BitXor, lhs, rhs); + } + public static CSBaseExpression operator << (CSBaseExpression lhs, int bits) + { + return new CSBinaryExpression (CSBinaryOperator.LeftShift, lhs, CSConstant.Val (bits)); + } + public static CSBaseExpression operator >> (CSBaseExpression lhs, int bits) + { + return new CSBinaryExpression (CSBinaryOperator.RightShift, lhs, CSConstant.Val (bits)); + } + public override bool Equals(object obj) + { + if (obj == null || GetType() != obj.GetType()) + { + return false; + } + + // Add your custom equality logic here + + return base.Equals(obj); + } + + public override int GetHashCode() + { + // Add your custom hash code logic here + + return base.GetHashCode(); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs new file mode 100644 index 000000000000..7fdb393d736f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + + +namespace SyntaxDynamo.CSLang { + public class CSBinaryExpression : CSBaseExpression { + public CSBinaryExpression (CSBinaryOperator op, ICSExpression lhs, ICSExpression rhs) + { + Operation = op; + Left = Exceptions.ThrowOnNull (lhs, "lhs"); + Right = Exceptions.ThrowOnNull (rhs, "rhs"); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Left.WriteAll (writer); + writer.Write (string.Format (Operation == CSBinaryOperator.Dot ? "{0}" : " {0} ", OpToString (Operation)), true); + Right.WriteAll (writer); + } + + public CSBinaryOperator Operation { get; private set; } + public ICSExpression Left { get; private set; } + public ICSExpression Right { get; private set; } + + static string OpToString (CSBinaryOperator op) + { + switch (op) { + case CSBinaryOperator.Add: + return "+"; + case CSBinaryOperator.Sub: + return "-"; + case CSBinaryOperator.Mul: + return "*"; + case CSBinaryOperator.Div: + return "/"; + case CSBinaryOperator.Mod: + return "%"; + case CSBinaryOperator.And: + return "&&"; + case CSBinaryOperator.Or: + return "||"; + case CSBinaryOperator.Less: + return "<"; + case CSBinaryOperator.Greater: + return ">"; + case CSBinaryOperator.Equal: + return "=="; + case CSBinaryOperator.NotEqual: + return "!="; + case CSBinaryOperator.LessEqual: + return "<="; + case CSBinaryOperator.GreaterEqual: + return ">="; + case CSBinaryOperator.BitAnd: + return "&"; + case CSBinaryOperator.BitOr: + return "|"; + case CSBinaryOperator.BitXor: + return "^"; + case CSBinaryOperator.LeftShift: + return ">>"; + case CSBinaryOperator.RightShift: + return "<<"; + case CSBinaryOperator.Dot: + return "."; + case CSBinaryOperator.Is: + return "is"; + case CSBinaryOperator.As: + return "as"; + case CSBinaryOperator.NullCoalesce: + return "??"; + default: + throw new ArgumentOutOfRangeException ("op"); + } + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs new file mode 100644 index 000000000000..6b8a6ab5f0fe --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSBinding : ICodeElementSet { + public CSBinding (CSIdentifier name, ICSExpression val = null, bool onOwnLine = false) + { + Name = name; + Value = val; + OnOwnLine = onOwnLine; + } + + public CSBinding (string name, ICSExpression val = null, bool onOwnLine = false) + : this (new CSIdentifier (name), val, onOwnLine) + { + } + + public CSIdentifier Name { get; private set; } + public ICSExpression Value { get; private set; } + public bool OnOwnLine { get; private set; } + + public override string ToString () + { + return string.Format ("{0}{1}{2}", + Name.Name, Value == null ? "" : " = ", Value == null ? "" : Value.ToString ()); + } + + + #region ICodeElem implementation + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + if (OnOwnLine) + args.Writer.BeginNewLine (true); + } + + public void Write (ICodeWriter writer, object o) + { + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + #endregion + + #region ICodeElemSet implementation + public IEnumerable Elements { + get { + yield return Name; + if (Value != null) { + yield return new SimpleElement (" = ", true); + yield return Value; + } + } + } + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs new file mode 100644 index 000000000000..764737769203 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSClass : ICodeElementSet, ICSTopLevelDeclaration { + public CSClass (CSVisibility vis, CSIdentifier name, IEnumerable methods = null, + bool isStatic = false, bool isSealed = false) + { + Visibility = vis; + IsStatic = isStatic; + IsSealed = isSealed; + Name = Exceptions.ThrowOnNull (name, "name"); + Inheritance = new CSInheritance (); + Delegates = new List (); + Fields = new List (); + Constructors = new List (); + Methods = new List (); + Properties = new List (); + InnerClasses = new CSClasses (); + InnerEnums = new List (); + StaticConstructor = new CSCodeBlock (); + GenericParams = new CSGenericTypeDeclarationCollection (); + GenericConstraints = new CSGenericConstraintCollection (); + + if (methods != null) + Methods.AddRange (methods); + } + + public CSClass (CSVisibility vis, string name, + IEnumerable members = null, bool isStatic = false, bool isSealed = false) + : this (vis, new CSIdentifier (name), members, isStatic, isSealed) + { + } + + protected virtual string EntityLabel { get { return "class"; } } + + public CSVisibility Visibility { get; private set; } + public bool IsStatic { get; private set; } + public bool IsSealed { get; private set; } + public CSIdentifier Name { get; private set; } + public CSInheritance Inheritance { get; private set; } + public List Delegates { get; private set; } + public List Fields { get; private set; } + public List Constructors { get; private set; } + public List Methods { get; private set; } + public List Properties { get; private set; } + public CSClasses InnerClasses { get; private set; } + public List InnerEnums { get; private set; } + public CSCodeBlock StaticConstructor { get; private set; } + public CSGenericTypeDeclarationCollection GenericParams { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + + public CSType ToCSType (IEnumerable genericReplacements) + { + List replacements = genericReplacements.ToList (); + if (replacements.Count < GenericParams.Count) { + replacements.AddRange (GenericParams.Skip (replacements.Count).Select (gen => new CSSimpleType (gen.Name.Name))); + } + CSSimpleType t = new CSSimpleType (Name.Name, false, replacements.ToArray ()); + return t; + } + + public CSType ToCSType () + { + return ToCSType (GenericParams.Select (gen => new CSSimpleType (gen.Name.Name))); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + var decl = new LineCodeElementCollection (true, false, true); + if (Visibility != CSVisibility.None) + decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); + if (IsStatic) + decl.Add (new SimpleElement ("static ", true)); + if (IsSealed) + decl.Add (new SimpleElement ("sealed ", true)); + decl.Add (new CSIdentifier (EntityLabel + " ")); + decl.Add (Name); + decl.Add (GenericParams); + if (Inheritance.Count > 0) { + decl.Add (new SimpleElement (" : ", true)); + decl.Add (Inheritance); + } + if (GenericConstraints.Count > 0) { + decl.Add (SimpleElement.Spacer); + decl.Add (GenericConstraints); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection ("{", "}", + true, true, true); + + contents.AddRange (Delegates); + contents.AddRange (Fields); + + if (StaticConstructor.Count > 0) { + var m = new CSMethod (CSVisibility.None, CSMethodKind.Static, + null, Name, new CSParameterList (), StaticConstructor); + contents.Add (m); + } + contents.AddRange (Constructors); + contents.AddRange (Methods); + contents.AddRange (Properties); + contents.Add (InnerClasses); + contents.AddRange (InnerEnums); + + yield return contents; + + } + } + + #endregion + } + + public class CSClasses : CodeElementCollection { + public CSClasses (IEnumerable classes = null) + : base () + { + if (classes != null) + AddRange (classes); + } + + public CSClasses And (CSClass use) + { + Add (use); + return this; + } + } + + public class CSStruct : CSClass { + public CSStruct (CSVisibility vis, CSIdentifier name, IEnumerable methods = null, + bool isStatic = false, bool isSealed = false) + : base (vis, name, methods, isStatic, isSealed) + { + } + + public CSStruct (CSVisibility vis, string name, + IEnumerable members = null, bool isStatic = false, bool isSealed = false) + : this (vis, new CSIdentifier (name), members, isStatic, isSealed) + { + } + + protected override string EntityLabel { + get { + return "struct"; + } + } + } + + public class CSStructs : CodeElementCollection { + public CSStructs (IEnumerable structs = null) + : base () + { + if (structs != null) + AddRange (structs); + } + + public CSStructs And (CSStruct st) + { + Add (st); + return this; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs new file mode 100644 index 000000000000..4d39f5e2c6f4 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSCodeBlock : DecoratedCodeElementCollection, ICSStatement { + public CSCodeBlock () + : this (null) + { + + } + + public CSCodeBlock (IEnumerable statements) + : this ("{", "}", statements) + { + } + + public static CSCodeBlock Create (params ICodeElement [] statements) + { + return new CSCodeBlock (statements); + } + + public CSCodeBlock (string start, string end, IEnumerable statements) + : base (Exceptions.ThrowOnNull (start, "start"), Exceptions.ThrowOnNull (end, "end"), true, true, true) + { + if (statements != null) { + foreach (ICodeElement elem in statements) { + And (elem); + } + } + } + + public CSCodeBlock And (ICodeElement elem) + { + if (!(elem is ICSStatement)) + throw new ArgumentException ($"contents must each be an IStatement, got {elem.GetType ()}"); + Add (elem); + return this; + } + } + + public class CSUnsafeCodeBlock : CSCodeBlock { + public CSUnsafeCodeBlock (IEnumerable statements) + : base ("unsafe {", "}", statements) + { + } + } + +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs new file mode 100644 index 000000000000..825a5880b260 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSComment : SimpleLineElement { + public CSComment (string text) + : base (Commentize (text), false, true, false) + { + } + + static string Commentize (string text) + { + text = text ?? ""; + if (text.Contains ("\n")) + throw new ArgumentException ("Comment text must not contain new line characters.", "text"); + return "// " + text; + } + } + + public class CSCommentBlock : CodeElementCollection { + public CSCommentBlock (params CSComment [] comments) + { + AddRange (comments); + } + + public CSCommentBlock (params string [] text) + { + AddRange (Sanitize (Exceptions.ThrowOnNull (text, "text"))); + } + + static IEnumerable Sanitize (string [] text) + { + foreach (string s in text) { + string [] lines = s.Split ('\n'); + foreach (string line in lines) + yield return new CSComment (line); + } + } + + public CSCommentBlock And (string text) + { + AddRange (Sanitize (new string [] { text })); + return this; + } + + public CSCommentBlock And (CSComment comment) + { + Add (Exceptions.ThrowOnNull (comment, "comment")); + return this; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs new file mode 100644 index 000000000000..36b574185965 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSConditionalCompilation : LineCodeElementCollection { + CSConditionalCompilation (CSIdentifier tag, CSIdentifier condition) + : base (true, false, false) + { + Add (tag); + if ((object)condition != null) { + Add (SimpleElement.Spacer); + Add (condition); + } + } + + + static CSConditionalCompilation _else = new CSConditionalCompilation (new CSIdentifier ("#else"), null); + public static CSConditionalCompilation Else { get { return _else; } } + static CSConditionalCompilation _endif = new CSConditionalCompilation (new CSIdentifier ("#endif"), null); + public static CSConditionalCompilation Endif { get { return _endif; } } + + public static CSConditionalCompilation If (CSIdentifier condition) + { + return new CSConditionalCompilation (new CSIdentifier ("#if"), Exceptions.ThrowOnNull (condition, nameof (condition))); + } + + public static void ProtectWithIfEndif (CSIdentifier condition, ICodeElement elem) + { + var @if = If (condition); + @if.AttachBefore (elem); + Endif.AttachAfter (elem); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs new file mode 100644 index 000000000000..5e791b123223 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; +using System.IO; +using System.CodeDom.Compiler; +using System.CodeDom; + +namespace SyntaxDynamo.CSLang { + public class CSConstant : CSBaseExpression { + public CSConstant (string val) + { + Value = Exceptions.ThrowOnNull (val, "val"); + } + + public static explicit operator CSConstant (string val) + { + return new CSConstant (val); + } + + public string Value { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Value, false); + } + + public static CSConstant Val (byte b) { return new CSConstant (b.ToString ()); } + public static CSConstant Val (sbyte sb) { return new CSConstant (sb.ToString ()); } + public static CSConstant Val (ushort us) { return new CSConstant (us.ToString ()); } + public static CSConstant Val (short s) { return new CSConstant (s.ToString ()); } + public static CSConstant Val (uint ui) { return new CSConstant (ui.ToString ()); } + public static CSConstant Val (int i) { return new CSConstant (i.ToString ()); } + public static CSConstant Val (ulong ul) { return new CSConstant (ul.ToString ()); } + public static CSConstant Val (long l) { return new CSConstant (l.ToString ()); } + public static CSConstant Val (float f) + { + return new CSConstant (f.ToString () + "f"); + } + public static CSConstant Val (double d) { return new CSConstant (d.ToString ()); } + public static CSConstant Val (bool b) { return new CSConstant (b ? "true" : "false"); } + public static CSConstant Val (char c) { return new CSConstant (ToCharLiteral (c)); } + public static CSConstant Val (string s) { return new CSConstant (ToStringLiteral (s)); } + static CSConstant cNull = new CSConstant ("null"); + public static CSConstant Null { get { return cNull; } } + static CSConstant cIntPtrZero = new CSConstant ("IntPtr.Zero"); + public static CSConstant IntPtrZero { get { return cIntPtrZero; } } + public static CSBaseExpression ValNFloat (double d) { return new CSCastExpression (CSSimpleType.NFloat, Val (d)); } + + static string ToCharLiteral (char c) + { + using (var writer = new StringWriter ()) { + using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { + provider.GenerateCodeFromExpression (new CodePrimitiveExpression (c), writer, null); + return writer.ToString (); + } + } + } + + static string ToStringLiteral (string s) + { + using (var writer = new StringWriter ()) { + using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { + provider.GenerateCodeFromExpression (new CodePrimitiveExpression (s), writer, null); + return writer.ToString (); + } + } + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs new file mode 100644 index 000000000000..1c26bfdcea5e --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSDelegateTypeDecl : DelegatedSimpleElement, ICSStatement { + public CSDelegateTypeDecl (CSVisibility vis, CSType type, CSIdentifier name, CSParameterList parms, bool isUnsafe = false) + { + Visibility = vis; + Type = type != null ? type : CSSimpleType.Void; + Name = Exceptions.ThrowOnNull (name, "name"); + Parameters = parms; + IsUnsafe = isUnsafe; + } + + public CSVisibility Visibility { get; private set; } + public CSType Type { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList Parameters { get; private set; } + public bool IsUnsafe { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write (CSMethod.VisibilityToString (Visibility), false); + if (IsUnsafe) + writer.Write (" unsafe", true); + writer.Write (" delegate ", true); + Type.WriteAll (writer); + writer.Write (' ', true); + Name.WriteAll (writer); + writer.Write ('(', true); + Parameters.WriteAll (writer); + writer.Write (')', true); + writer.Write (';', false); + writer.EndLine (); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs new file mode 100644 index 000000000000..92d798ed1ad8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.CSLang { + public class CSEnum : ICodeElementSet, ICSTopLevelDeclaration { + public CSEnum (CSVisibility vis, CSIdentifier name, CSType optionalType) + { + Values = new List (); + Name = Exceptions.ThrowOnNull (name, "name"); + OptionalType = optionalType; + Visibility = vis; + } + + public CSEnum (CSVisibility vis, string name, CSType optionalType) + : this (vis, new CSIdentifier (name), optionalType) + { + } + + public List Values { get; private set; } + public CSVisibility Visibility { get; private set; } + public CSType OptionalType { get; private set; } + public CSIdentifier Name { get; private set; } + + public CSType ToCSType () + { + return new CSSimpleType (Name.Name); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + var decl = new LineCodeElementCollection (true, false, true); + if (Visibility != CSVisibility.None) + decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); + decl.Add (new CSIdentifier ("enum" + " ")); + decl.Add (Name); + + if (OptionalType != null) { + decl.Add (new SimpleElement (" : ", true)); + decl.Add (OptionalType); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection ("{", "}", + true, true, true); + + var bindings = new CommaListElementCollection (); + bindings.AddRange (Values); + if (bindings.Count > 0 && !bindings [0].OnOwnLine) { + bindings [0] = new CSBinding (bindings [0].Name, bindings [0].Value, true); + } + contents.Add (bindings); + + yield return contents; + + } + } + + #endregion + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs new file mode 100644 index 000000000000..7e729c90e904 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSVariableDeclaration : LineCodeElementCollection, ICSExpression, ICSLineable { + public CSVariableDeclaration (CSType type, IEnumerable bindings) + : base (null, false, true) + { + Type = Exceptions.ThrowOnNull (type, "type"); + And (Type).And (SimpleElement.Spacer); + Bindings = new CommaListElementCollection (Exceptions.ThrowOnNull (bindings, "bindings")); + Add (Bindings); + } + + public CSVariableDeclaration (CSType type, string name, ICSExpression value = null) + : this (type, new CSIdentifier (name), value) + { + } + + public CSVariableDeclaration (CSType type, CSIdentifier name, ICSExpression value = null) + : this (type, new CSBinding [] { new CSBinding (name, value) }) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Bindings { get; private set; } + + + public static CSLine VarLine (CSType type, CSIdentifier name, ICSExpression value = null) + { + return new CSLine (new CSVariableDeclaration (type, name, value)); + } + + public static CSLine VarLine (CSType type, string name, ICSExpression value = null) + { + return new CSLine (new CSVariableDeclaration (type, name, value)); + } + + public static CSLine VarLine (string name, ICSExpression value) + { + return new CSLine (new CSVariableDeclaration (CSSimpleType.Var, name, value)); + } + + public static CSLine VarLine (CSIdentifier name, ICSExpression value) + { + return new CSLine (new CSVariableDeclaration (CSSimpleType.Var, name, value)); + } + } + + public class CSFieldDeclaration : CSVariableDeclaration { + public CSFieldDeclaration (CSType type, IEnumerable bindings, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) + : base (type, bindings) + { + Visibilty = vis; + IsStatic = isStatic; + IsUnsafe = isUnsafe; + if (isReadonly) { + this.Insert (0, new SimpleElement ("readonly")); + this.Insert (1, SimpleElement.Spacer); + } + if (IsUnsafe) { + this.Insert (0, new SimpleElement ("unsafe")); + this.Insert (1, SimpleElement.Spacer); + } + if (isStatic) { + this.Insert (0, new SimpleElement ("static")); + this.Insert (1, SimpleElement.Spacer); + } + if (vis != CSVisibility.None) { + this.Insert (0, new SimpleElement (CSMethod.VisibilityToString (vis))); + this.Insert (1, SimpleElement.Spacer); + } + } + + public CSFieldDeclaration (CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) + : this (type, new CSIdentifier (name), value, vis, isStatic, isReadonly, isUnsafe) + { + } + + public CSFieldDeclaration (CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadOnly = false, bool isUnsafe = false) + : this (type, new CSBinding [] { new CSBinding (name, value) }, vis, isStatic, isReadOnly, isUnsafe) + { + } + + + public CSVisibility Visibilty { get; private set; } + public bool IsStatic { get; private set; } + public bool IsUnsafe { get; private set; } + + public static CSLine FieldLine (CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) + { + return new CSLine (new CSFieldDeclaration (type, name, value, vis, isStatic)); + } + + public static CSLine FieldLine (CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) + { + return new CSLine (new CSFieldDeclaration (type, name, value, vis, isStatic)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs new file mode 100644 index 000000000000..ac78e03b69b2 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSFile : ICodeElementSet { + public CSFile (CSUsingPackages use, IEnumerable ns) + { + Using = use ?? new CSUsingPackages (); + ns = ns ?? new CSNamespace [0]; + Namespaces = new CSNamespaceBlock (ns); + } + + public static CSFile Create (CSUsingPackages use, params CSNamespace [] ns) + { + return new CSFile (use, ns); + } + + public CSUsingPackages Using { get; private set; } + public CSNamespaceBlock Namespaces { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public System.Collections.Generic.IEnumerable Elements { + get { + yield return Using; + yield return Namespaces; + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs new file mode 100644 index 000000000000..30416874f59e --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSFileBasic : ICodeElementSet { + string nameSpace; + + public CSFileBasic (string nameSpace) + { + this.nameSpace = Exceptions.ThrowOnNull (nameSpace, "nameSpace"); + Using = new CSUsingPackages (); + Classes = new CSClasses (); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public CSClasses Classes { get; private set; } + public CSUsingPackages Using { get; private set; } + + public object BeginWrite (ICodeWriter writer) + { + return null; + } + + public void Write (ICodeWriter writer, object o) + { + } + + public void EndWrite (ICodeWriter writer, object o) + { + } + + protected virtual void OnBegin (WriteEventArgs e) + { + Begin (this, e); + } + + protected virtual void OnEnd (WriteEventArgs e) + { + End (this, e); + } + + #endregion + + #region ICodeElemSet implementation + + public System.Collections.Generic.IEnumerable Elements { + get { + yield return Using; + CSNamespace ns = new CSNamespace (nameSpace); + ns.Block.AddRange (Classes); + yield return ns; + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs new file mode 100644 index 000000000000..21847bd9a111 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSFixedCodeBlock : CSCodeBlock, ICSStatement { + public CSFixedCodeBlock (CSType type, CSIdentifier ident, CSBaseExpression expr, IEnumerable body) + : base (body) + { + Type = Exceptions.ThrowOnNull (type, "type"); + Identifier = Exceptions.ThrowOnNull (ident, "ident"); + Expr = Exceptions.ThrowOnNull (expr, "expr"); + } + + public override void Write (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write ("fixed (", true); + Type.Write (writer, o); + writer.Write (' ', false); + Identifier.Write (writer, o); + writer.Write (" = ", true); + Expr.Write (writer, o); + writer.Write (") ", true); + base.Write (writer, o); + } + + public CSType Type { get; private set; } + public CSIdentifier Identifier { get; private set; } + public CSBaseExpression Expr { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs new file mode 100644 index 000000000000..fe9cfd004c77 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.CSLang { + public class CSForEach : CodeElementCollection, ICSStatement { + + class ForElement : DelegatedSimpleElement, ICSStatement { + public ForElement (CSType type, CSIdentifier ident, CSBaseExpression expr) + : base () + { + Type = type; + Ident = ident; + Expr = expr; + } + + public CSType Type { get; private set; } + public CSIdentifier Ident { get; private set; } + public CSBaseExpression Expr { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write ("foreach (", false); + if (Type != null) { + Type.WriteAll (writer); + } else { + writer.Write ("var", false); + } + SimpleElement.Spacer.WriteAll (writer); + Ident.WriteAll (writer); + writer.Write (" in ", true); + Expr.WriteAll (writer); + writer.Write (")", false); + writer.EndLine (); + } + } + + + public CSForEach (CSType type, CSIdentifier ident, CSBaseExpression expr, CSCodeBlock body) + { + Type = type; + Ident = Exceptions.ThrowOnNull (ident, nameof (ident)); + Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); + Body = body ?? new CSCodeBlock (); + Add (new ForElement (type, ident, expr)); + Add (Body); + } + + public CSForEach (CSType type, string ident, CSBaseExpression expr, CSCodeBlock body) + : this (type, new CSIdentifier (ident), expr, body) + { + } + + public CSType Type { get; private set; } + public CSIdentifier Ident { get; private set; } + public CSBaseExpression Expr { get; private set; } + public CSCodeBlock Body { get; private set; } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs new file mode 100644 index 000000000000..ac6473589aa1 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSFunctionCall : CSBaseExpression, ICSLineable { + public CSFunctionCall (CSIdentifier ident, CommaListElementCollection paramList, bool isConstructor = false) + { + Name = Exceptions.ThrowOnNull (ident, "ident"); + Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); + IsConstructor = isConstructor; + } + + public CSFunctionCall (string identifier, bool isConstructor, params CSBaseExpression [] parameters) + : this (new CSIdentifier (identifier), new CommaListElementCollection (parameters), isConstructor) + { + } + + public static CSFunctionCall Function (string identifier, params CSBaseExpression [] parameters) + { + return new CSFunctionCall (identifier, false, parameters); + } + public static CSLine FunctionLine (string identifier, params CSBaseExpression [] parameters) => new CSLine (Function (identifier, parameters)); + + public static CSFunctionCall Ctor (string identifier, params CSBaseExpression [] parameters) + { + return new CSFunctionCall (identifier, true, parameters); + } + public static CSLine CtorLine (string identifier, params CSBaseExpression [] parameters) => new CSLine (Ctor (identifier, parameters)); + + public static CSLine ConsoleWriteLine (params CSBaseExpression [] parameters) => FunctionLine ("Console.WriteLine", parameters); + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (IsConstructor) + writer.Write ("new ", false); + Name.WriteAll (writer); + writer.Write ("(", false); + Parameters.WriteAll (writer); + writer.Write (")", false); + } + + public bool IsConstructor { get; private set; } + public CSIdentifier Name { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + public static CSLine FunctionCallLine (CSIdentifier identifier, params CSBaseExpression [] parameters) + { + return FunctionCallLine (identifier, false, parameters); + } + + public static CSLine FunctionCallLine (CSIdentifier identifier, bool isConstructor, params CSBaseExpression [] parameters) + { + return new CSLine (new CSFunctionCall (identifier, + new CommaListElementCollection (parameters), isConstructor)); + } + + public static CSLine FunctionCallLine (string identifier, params CSBaseExpression [] parameters) + { + return FunctionCallLine (identifier, false, parameters); + } + + public static CSLine FunctionCallLine (string identifier, bool isConstructor, params CSBaseExpression [] parameters) + { + return new CSLine (new CSFunctionCall (new CSIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), + new CommaListElementCollection (parameters), isConstructor)); + } + + static CSIdentifier iNameOf = new CSIdentifier ("nameof"); + + public static CSFunctionCall Nameof (CSIdentifier id) + { + return FooOf (iNameOf, id); + } + + public static CSFunctionCall Nameof (string name) + { + return Nameof (new CSIdentifier (name)); + } + + static CSIdentifier iTypeof = new CSIdentifier ("typeof"); + + public static CSFunctionCall Typeof (Type t) + { + return Typeof (t.Name); + } + + public static CSFunctionCall Typeof (string t) + { + return FooOf (iTypeof, new CSIdentifier (t)); + } + + public static CSFunctionCall Typeof (CSSimpleType t) + { + return Typeof (t.Name); + } + + static CSIdentifier iSizeof = new CSIdentifier ("sizeof"); + + public static CSFunctionCall Sizeof (CSBaseExpression expr) + { + return FooOf (iSizeof, expr); + } + + static CSIdentifier iDefault = new CSIdentifier ("default"); + + public static CSFunctionCall Default (Type t) + { + return Default (t.Name); + } + + public static CSFunctionCall Default (string t) + { + return FooOf (iDefault, new CSIdentifier (t)); + } + + public static CSFunctionCall Default (CSSimpleType t) + { + return Default (t.Name); + } + + static CSFunctionCall FooOf (CSIdentifier foo, CSBaseExpression parameter) + { + CommaListElementCollection parms = new CommaListElementCollection (); + parms.Add (parameter); + return new CSFunctionCall (foo, parms, false); + } + } + +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs new file mode 100644 index 000000000000..ee0f318d7211 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSGenericConstraint : DelegatedSimpleElement { + public CSGenericConstraint (CSIdentifier name, CSIdentifier isA) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + IsA = new CommaListElementCollection (); + IsA.Add (Exceptions.ThrowOnNull (isA, nameof (isA))); + } + + public CSGenericConstraint (CSIdentifier name, IEnumerable multiIs) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + IsA = new CommaListElementCollection (); + if (multiIs != null) + IsA.AddRange (multiIs); + } + + public CSIdentifier Name { get; private set; } + public CommaListElementCollection IsA { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("where ", true); + Name.Write (writer, o); + writer.Write (" : ", true); + IsA.WriteAll (writer); + } + } + + public class CSGenericConstraintCollection : List, ICodeElementSet { + public IEnumerable Elements { + get { + bool first = true; + foreach (CSGenericConstraint tc in this) { + if (!first) { + yield return new LineBreak (); + } + first = false; + yield return tc; + } + } + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + } + +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs new file mode 100644 index 000000000000..2ef843588c8d --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSGenericTypeDeclaration { + public CSGenericTypeDeclaration (CSIdentifier name) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + } + + public CSIdentifier Name { get; private set; } + } + + public class CSGenericTypeDeclarationCollection : List, ICodeElementSet { + public CSGenericTypeDeclarationCollection () + : base () + { + } + + public IEnumerable Elements { + get { + if (this.Count > 0) { + yield return new SimpleElement ("<"); + bool first = true; + foreach (CSGenericTypeDeclaration decl in this) { + if (!first) { + yield return new SimpleElement (",", true); + yield return SimpleElement.Spacer; + } else { + first = false; + } + yield return decl.Name; + } + yield return new SimpleElement (">"); + } + } + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs new file mode 100644 index 000000000000..6df2a664bd27 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSIdentifier : CSBaseExpression { + public CSIdentifier (string name) + { + Name = Exceptions.ThrowOnNull (name, "name"); + } + + public static explicit operator CSIdentifier (string name) + { + return new CSIdentifier (name); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Name, false); + } + + public string Name { get; private set; } + + public override string ToString () + { + return Name; + } + + public static CSIdentifier Create (string name) => new CSIdentifier (name); + + static CSIdentifier thisID = new CSIdentifier ("this"); + public static CSIdentifier This { get { return thisID; } } + static CSIdentifier baseID = new CSIdentifier ("base"); + public static CSIdentifier Base { get { return baseID; } } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs new file mode 100644 index 000000000000..02b906f7104e --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSIfElse : CodeElementCollection, ICSStatement { + class CSIfElement : DelegatedSimpleElement, ICSStatement { + public CSIfElement (CSBaseExpression condition) + : base () + { + Condition = condition; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write ("if (", false); + Condition.WriteAll (writer); + writer.Write (")", false); + writer.EndLine (); + } + + public CSBaseExpression Condition { get; private set; } + } + + public CSIfElse (CSBaseExpression condition, CSCodeBlock ifClause, CSCodeBlock elseClause = null) + : base () + { + Condition = new CSIfElement (Exceptions.ThrowOnNull (condition, "condition")); + IfClause = Exceptions.ThrowOnNull (ifClause, "ifClause"); + ElseClause = elseClause; + + Add (Condition); + Add (IfClause); + if (ElseClause != null && ElseClause.Count > 0) { + Add (new SimpleLineElement ("else", false, true, false)); + Add (ElseClause); + } + } + + public CSIfElse (CSBaseExpression expr, IEnumerable ifClause, IEnumerable elseClause) + : this (expr, new CSCodeBlock (ifClause), + elseClause != null ? new CSCodeBlock (elseClause) : null) + + { + + } + + public DelegatedSimpleElement Condition { get; private set; } + public CSCodeBlock IfClause { get; private set; } + public CSCodeBlock ElseClause { get; private set; } + + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs new file mode 100644 index 000000000000..dd9d3606feb0 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSIndexExpression : CSBaseExpression { + public CSIndexExpression (CSBaseExpression aggregate, CommaListElementCollection paramList, bool addParensAroundAggregate) + { + AddParensAroundAggregate = addParensAroundAggregate; + Aggregate = Exceptions.ThrowOnNull (aggregate, "aggregate"); + Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); + } + + public CSIndexExpression (string identifier, bool addParensAroundAggregate, params CSBaseExpression [] parameters) + : this (new CSIdentifier (identifier), new CommaListElementCollection (parameters), addParensAroundAggregate) + { + } + + public CSIndexExpression (CSBaseExpression aggregate, bool addParensAroundAggregate, params CSBaseExpression [] parameters) + : this (aggregate, new CommaListElementCollection (parameters), addParensAroundAggregate) + { + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (AddParensAroundAggregate) + writer.Write ('(', false); + Aggregate.WriteAll (writer); + if (AddParensAroundAggregate) + writer.Write (')', false); + writer.Write ("[", false); + Parameters.WriteAll (writer); + writer.Write ("]", false); + } + + public bool AddParensAroundAggregate { get; private set; } + public CSBaseExpression Aggregate { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs new file mode 100644 index 000000000000..bbdb8263a575 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; + +namespace SyntaxDynamo.CSLang { + public class CSInheritance : CommaListElementCollection { + public CSInheritance (IEnumerable identifiers) + { + if (identifiers != null) + AddRange (identifiers); + } + + public CSInheritance (params string [] identifiers) + : this (identifiers.Select (str => new CSIdentifier (str))) + { + } + + public void Add (Type t) + { + Exceptions.ThrowOnNull (t, "t"); + Add (new CSIdentifier (t.Name)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs new file mode 100644 index 000000000000..06916ae0214c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSInitializer : CSBaseExpression { + public CSInitializer (IEnumerable parameters, bool appendNewlineAfterEach) + { + Parameters = new CommaListElementCollection ("", "", parameters, appendNewlineAfterEach); + } + + public CommaListElementCollection Parameters { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("{ ", false); + Parameters.WriteAll (writer); + writer.Write (" }", false); + } + } + + public class CSInitializedType : CSBaseExpression { + public CSInitializedType (CSFunctionCall call, CSInitializer initializer) + { + Call = Exceptions.ThrowOnNull (call, nameof (call)); + Initializer = Exceptions.ThrowOnNull (initializer, nameof (initializer)); + } + + public CSInitializedType (CSFunctionCall call, IEnumerable parameters, bool appendNewlineAfterEach) + : this (call, new CSInitializer (parameters, appendNewlineAfterEach)) + { + } + + public CSFunctionCall Call { get; private set; } + public CSInitializer Initializer { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Call.WriteAll (writer); + SimpleElement.Spacer.WriteAll (writer); + Initializer.WriteAll (writer); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs new file mode 100644 index 000000000000..368a1b6bcb13 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.CSLang { + // CSInject is a way to more formalize the notion of code that is just plain easier to + // inject as raw text. It's not strictly necessary, but when you see a CSInject, it will make + // it clear that you're doing something not quite on the up and up. + public class CSInject : CSIdentifier { + public CSInject (string name) + : base (name) + { + } + + public static explicit operator CSInject (string name) + { + return new CSInject (name); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs new file mode 100644 index 000000000000..10f918ed1d19 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.CSLang { + public class CSInterface : ICodeElementSet, ICSTopLevelDeclaration { + public CSInterface (CSVisibility vis, CSIdentifier name, + IEnumerable methods = null) + { + Visibility = vis; + Name = Exceptions.ThrowOnNull (name, "name"); + Inheritance = new CSInheritance (); + Methods = new List (); + Properties = new List (); + GenericParams = new CSGenericTypeDeclarationCollection (); + GenericConstraints = new CSGenericConstraintCollection (); + if (methods != null) + Methods.AddRange (methods); + } + + public CSInterface (CSVisibility vis, string name, IEnumerable methods = null) + : this (vis, new CSIdentifier (name), methods) + { + } + + + public CSType ToCSType (IEnumerable genericReplacements) + { + var replacements = genericReplacements.ToList (); + if (replacements.Count < GenericParams.Count) { + replacements.AddRange (GenericParams.Skip (replacements.Count).Select (gen => new CSSimpleType (gen.Name.Name))); + } + return new CSSimpleType (Name.Name, false, replacements.ToArray ()); + } + + public CSType ToCSType () + { + return ToCSType (GenericParams.Select (gen => new CSSimpleType (gen.Name.Name))); + } + + public CSVisibility Visibility { get; private set; } + public CSIdentifier Name { get; private set; } + public CSInheritance Inheritance { get; private set; } + public List Methods { get; private set; } + public List Properties { get; private set; } + public CSGenericTypeDeclarationCollection GenericParams { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + + #region ICodeElem implementation + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + var decl = new LineCodeElementCollection (true, false, true); + if (Visibility != CSVisibility.None) + decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); + decl.Add (new CSIdentifier ("interface ")); + decl.Add (Name); + + decl.Add (GenericParams); + if (Inheritance.Count > 0) { + decl.Add (new SimpleElement (" : ", true)); + decl.Add (Inheritance); + } + if (GenericConstraints.Count > 0) { + decl.Add (SimpleElement.Spacer); + decl.Add (GenericConstraints); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection ("{", "}", + true, true, true); + + contents.AddRange (Methods); + contents.AddRange (Properties); + + yield return contents; + + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs new file mode 100644 index 000000000000..c33cca59169d --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSLambda : CSBaseExpression { + public CSLambda (CSParameterList parameters, ICSExpression value) + { + Parameters = parameters ?? new CSParameterList (); + Value = Exceptions.ThrowOnNull (value, "value"); + Body = null; + } + + public CSLambda (CSParameterList parameters, CSCodeBlock body) + { + body = body ?? new CSCodeBlock (); + Parameters = parameters ?? new CSParameterList (); + Value = null; + Body = body; + } + + public CSLambda (ICSExpression value, params string [] parameters) + : this (new CSParameterList (parameters.Select (p => new CSParameter (CSSimpleType.Void, new CSIdentifier (p)))), value) + { + } + + public CSLambda (CSCodeBlock body, params string [] parameters) + : this (new CSParameterList (parameters.Select (p => new CSParameter (CSSimpleType.Void, new CSIdentifier (p)))), body) + { + } + + + public CSParameterList Parameters { get; private set; } + public ICSExpression Value { get; private set; } + public CSCodeBlock Body { get; private set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + // hack - Parameters really want types. If you set them to void, we'll consider them to be + // typeless. + bool allVoid = Parameters.All (p => p.CSType == CSSimpleType.Void); + + writer.Write ('(', true); + if (allVoid) { + bool didFirst = false; + foreach (CSParameter p in Parameters) { + if (didFirst) { + writer.Write (", ", true); + } + p.Name.WriteAll (writer); + didFirst = true; + } + } else { + Parameters.WriteAll (writer); + } + writer.Write (") => ", true); + if (Value != null) { + Value.WriteAll (writer); + } else { + Body.WriteAll (writer); + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs new file mode 100644 index 000000000000..64cc40603a4d --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSLine : DelegatedSimpleElement, ICSStatement { + public CSLine (ICodeElement contents, bool addSemicolon = true) + { + Contents = Exceptions.ThrowOnNull (contents, nameof(contents)); + if (!(contents is ICSLineable) && addSemicolon) + throw new ArgumentException ("contents must be ILineable", nameof (contents)); + AddSemicolon = addSemicolon; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + Contents.WriteAll (writer); + if (AddSemicolon) + writer.Write (';', false); + writer.EndLine (); + } + + public ICodeElement Contents { get; private set; } + public bool AddSemicolon { get; set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs new file mode 100644 index 000000000000..ef23cc88a1e3 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSMethod : CodeElementCollection { + public CSMethod (CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, CSParameterList parms, CSCodeBlock body) + : this (vis, kind, type, name, parms, null, false, body) + { + + } + public CSMethod (CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, + CSParameterList parms, CSBaseExpression [] baseOrThisCallParms, bool callsBase, CSCodeBlock body, bool isSealed = false, + bool isAsync = false) + { + GenericParameters = new CSGenericTypeDeclarationCollection (); + GenericConstraints = new CSGenericConstraintCollection (); + Visibility = vis; + Kind = kind; + Type = type; // no throw on null - could be constructor + Name = Exceptions.ThrowOnNull (name, nameof (name)); + Parameters = Exceptions.ThrowOnNull (parms, nameof (parms)); + CallsBase = callsBase; + BaseOrThisCallParameters = baseOrThisCallParms; + + Body = body; // can be null + IsSealed = isSealed; + IsAsync = isAsync; + + LineCodeElementCollection lc = new LineCodeElementCollection (new ICodeElement [0], false, true); + if (vis != CSVisibility.None) { + lc.And (new SimpleElement (VisibilityToString (vis))).And (SimpleElement.Spacer); + } + + if (isSealed) { + lc.And (new SimpleElement ("sealed")).And (SimpleElement.Spacer); + } + + if (isAsync) { + lc.And (new SimpleElement ("async")).And (SimpleElement.Spacer); + } + + lc.And (new SimpleElement (MethodKindToString (kind))).And (SimpleElement.Spacer); + + if (type != null) { + lc.And (type).And (SimpleElement.Spacer); + } + + lc.And (name).And (GenericParameters).And (new SimpleElement ("(")).And (parms).And (new SimpleElement (")")).And (GenericConstraints); + if (body == null) { + if (!(kind == CSMethodKind.StaticExtern || kind == CSMethodKind.Interface)) + throw new ArgumentException ("Method body is only optional when method kind kind is either StaticExtern or Interface", + nameof (body)); + lc.Add (new SimpleElement (";")); + } + Add (lc); + if (BaseOrThisCallParameters != null) { + Add (new CSFunctionCall (CallsBase ? ": base" : ": this", false, BaseOrThisCallParameters)); + } + if (body != null) + Add (body); + } + + public CSVisibility Visibility { get; private set; } + public CSMethodKind Kind { get; private set; } + public CSType Type { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList Parameters { get; private set; } + public bool CallsBase { get; private set; } + public CSBaseExpression [] BaseOrThisCallParameters { get; private set; } + public CSCodeBlock Body { get; private set; } + public CSGenericTypeDeclarationCollection GenericParameters { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + public bool IsSealed { get; private set; } + public bool IsAsync { get; private set; } + + public CSMethod AsSealed () + { + var sealedMethod = new CSMethod (Visibility, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, true); + return CopyGenerics (this, sealedMethod); + } + + public CSMethod AsOverride () + { + var overrideMethod = new CSMethod (Visibility, CSMethodKind.Override, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); + return CopyGenerics (this, overrideMethod); + } + + public CSMethod AsPrivate () + { + var privateMethod = new CSMethod (CSVisibility.None, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); + return CopyGenerics (this, privateMethod); + } + + public static CSMethod CopyGenerics (CSMethod from, CSMethod to) + { + to.GenericParameters.AddRange (from.GenericParameters); + to.GenericConstraints.AddRange (from.GenericConstraints); + return to; + } + + public static CSMethod RemoveGenerics (CSMethod from) + { + var newMethod = new CSMethod (from.Visibility, from.Kind, from.Type, from.Name, from.Parameters, from.Body); + return newMethod; + } + + public static string VisibilityToString (CSVisibility visibility) + { + switch (visibility) { + case CSVisibility.None: + return ""; + case CSVisibility.Internal: + return "internal"; + case CSVisibility.Private: + return "private"; + case CSVisibility.Public: + return "public"; + case CSVisibility.Protected: + return "protected"; + default: + throw new ArgumentOutOfRangeException ("vis"); + } + } + + public static string MethodKindToString (CSMethodKind kind) + { + switch (kind) { + case CSMethodKind.None: + case CSMethodKind.Interface: + return ""; + case CSMethodKind.Extern: + return "extern"; + case CSMethodKind.New: + return "new"; + case CSMethodKind.Override: + return "override"; + case CSMethodKind.Static: + return "static"; + case CSMethodKind.StaticExtern: + return "static extern"; + case CSMethodKind.StaticNew: + return "static new"; + case CSMethodKind.Virtual: + return "virtual"; + case CSMethodKind.Abstract: + return "abstract"; + case CSMethodKind.Unsafe: + return "unsafe"; + case CSMethodKind.StaticUnsafe: + return "static unsafe"; + default: + throw new ArgumentOutOfRangeException (nameof (kind)); + } + } + + public static CSMethod PublicMethod (CSType type, string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod (CSVisibility.Public, CSMethodKind.None, type, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PublicMethod (CSMethodKind kind, CSType type, string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod (CSVisibility.Public, kind, type, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PublicConstructor (string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod (CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PublicConstructor (string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression [] baseParams) + { + return new CSMethod (CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier (name), parms, + baseParams, true, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PrivateConstructor (string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod (CSVisibility.None, CSMethodKind.None, null, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PrivateConstructor (string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression [] baseParams) + { + return new CSMethod (CSVisibility.None, CSMethodKind.None, null, new CSIdentifier (name), parms, + baseParams, true, Exceptions.ThrowOnNull (body, "body")); + } + + public static CSMethod PInvoke (CSVisibility vis, CSType type, string name, string dllName, string externName, CSParameterList parms) + { + CSMethod method = new CSMethod (vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull (type, "type"), + new CSIdentifier (name), parms, null); + + CSAttribute.DllImport (dllName, externName).AttachBefore (method); + + return method; + } + + public static CSMethod PInvoke (CSVisibility vis, CSType type, string name, CSBaseExpression dllName, string externName, CSParameterList parms) + { + CSMethod method = new CSMethod (vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull (type, "type"), + new CSIdentifier (name), parms, null); + + CSAttribute.DllImport (dllName, externName).AttachBefore (method); + + return method; + } + + public static CSMethod PublicPInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke (CSVisibility.Public, type, name, dllName, externName, parms); + } + + public static CSMethod PrivatePInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke (CSVisibility.None, type, name, dllName, externName, parms); + } + + public static CSMethod InternalPInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke (CSVisibility.Internal, type, name, dllName, externName, parms); + } + + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs new file mode 100644 index 000000000000..6e5620c60844 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; +using System.Linq; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public class CSNamespace : LabeledCodeElementCollection { + public CSNamespace () + : base (new SimpleLineElement (string.Empty, false, false, false), + new DecoratedCodeElementCollection (string.Empty, string.Empty, false, false, false)) + { + } + + public CSNamespace (string nameSpace) + : base (new SimpleLineElement (string.Format ("namespace {0}", Exceptions.ThrowOnNull (nameSpace, nameof (nameSpace))), + false, true, false), + new DecoratedCodeElementCollection ("{", "}", true, true, true)) + { + } + + } + + public class CSNamespaceBlock : CodeElementCollection { + public CSNamespaceBlock (params string [] nameSpaces) + : base () + { + this.AddRange (nameSpaces.Select (s => new CSNamespace (s))); + } + + public CSNamespaceBlock (IEnumerable nameSpaces) + : base () + { + this.AddRange (nameSpaces); + } + + public CSNamespaceBlock And (string s) + { + return And (new CSNamespace (s)); + } + + public CSNamespaceBlock And (CSNamespace ns) + { + Add (Exceptions.ThrowOnNull (ns, "ns")); + return this; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs new file mode 100644 index 000000000000..4d56a09f621c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + + +namespace SyntaxDynamo.CSLang { + public class CSParameter : DelegatedSimpleElement { + public CSParameter (CSType type, CSIdentifier name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + { + CSType = Exceptions.ThrowOnNull (type, nameof(type)); + Name = Exceptions.ThrowOnNull (name, nameof(name)); + ParameterKind = parameterKind; + DefaultValue = defaultValue; + } + + public CSParameter (CSType type, string name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + : this (type, new CSIdentifier (name), parameterKind, defaultValue) + { + } + + public CSParameter (string type, string name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + : this (new CSSimpleType (type), new CSIdentifier (name), parameterKind, defaultValue) + { + } + + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (this.ParameterKind != CSParameterKind.None) { + writer.Write (ToParameterKindString (this.ParameterKind), false); + writer.Write (' ', false); + } + this.CSType.WriteAll (writer); + writer.Write (' ', true); + Name.WriteAll (writer); + if ((Object)DefaultValue != null) { + writer.Write (" = ", true); + DefaultValue.WriteAll (writer); + } + } + + static string ToParameterKindString (CSParameterKind parameterKind) + { + switch (parameterKind) { + case CSParameterKind.None: + return ""; + case CSParameterKind.Out: + return "out"; + case CSParameterKind.Ref: + return "ref"; + case CSParameterKind.This: + return "this"; + case CSParameterKind.Params: + return "params"; + default: + throw new ArgumentOutOfRangeException (nameof(parameterKind), "unexpected parameter kind " + parameterKind.ToString ()); + } + } + + public CSType CSType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSConstant DefaultValue { get; private set; } + public CSParameterKind ParameterKind { get; private set; } + } + + public class CSParameterList : CommaListElementCollection { + public CSParameterList (IEnumerable parameters) + : base () + { + if (parameters != null) + AddRange (parameters); + } + public CSParameterList (params CSParameter[] parameters) + : base () + { + if (parameters != null) + AddRange (parameters); + } + + public CSParameterList () : this ((IEnumerable)null) { } + + public CSParameterList (CSParameter parameter) : this (new CSParameter [] { parameter }) { } + + public CSParameterList And (CSParameter parameter) + { + Add (Exceptions.ThrowOnNull (parameter, nameof(parameter))); + return this; + } + + public CSParameterList And (string type, string identifier, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + { + return And (new CSParameter (new CSSimpleType (Exceptions.ThrowOnNull (type, nameof(type))), + new CSIdentifier (Exceptions.ThrowOnNull (identifier, nameof(identifier))), parameterKind, defaultValue)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs new file mode 100644 index 000000000000..d9caf746e3df --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSParenthesisExpression : CSBaseExpression { + public CSParenthesisExpression (ICSExpression within) + { + Within = Exceptions.ThrowOnNull (within, "within"); + } + + public ICSExpression Within { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('(', true); + Within.WriteAll (writer); + writer.Write (')', true); + } + } + + public class CSCastExpression : CSBaseExpression, ICSLineable { + public CSCastExpression (string type, ICSExpression toCast) + : this (new CSSimpleType (type), toCast) + { + } + + public CSCastExpression (CSType type, ICSExpression toCast) + { + Type = Exceptions.ThrowOnNull (type, "type"); + ToCast = Exceptions.ThrowOnNull (toCast, "toCast"); + } + + public CSType Type { get; private set; } + public ICSExpression ToCast { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("(", true); + Type.WriteAll (writer); + writer.Write (')', true); + ToCast.WriteAll (writer); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs new file mode 100644 index 000000000000..c1d9e0fd5539 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Text; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSProperty : CodeElementCollection { + public CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, IEnumerable getter, + CSVisibility setVis, IEnumerable setter) + : this (type, kind, name, + getVis, getter != null ? new CSCodeBlock (getter) : null, + setVis, setter != null ? new CSCodeBlock (setter) : null) + { + } + + + public CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter) + : this (type, kind, name, getVis, getter, setVis, setter, null) + { + } + + public CSProperty (CSType type, CSMethodKind kind, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) + : this (type, kind, new CSIdentifier ("this"), getVis, getter, setVis, setter, + Exceptions.ThrowOnNull (parms, nameof (parms))) + { + } + + CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) + { + bool unifiedVis = getVis == setVis; + IndexerParameters = parms; + + LineCodeElementCollection decl = new LineCodeElementCollection (null, false, true); + + GetterVisibility = getVis; + SetterVisibility = setVis; + CSVisibility bestVis = (CSVisibility)Math.Min ((int)getVis, (int)setVis); + decl.And (new SimpleElement (CSMethod.VisibilityToString (bestVis))).And (SimpleElement.Spacer); + if (kind != CSMethodKind.None) + decl.And (new SimpleElement (CSMethod.MethodKindToString (kind))).And (SimpleElement.Spacer); + + PropType = type; + Name = name; + + decl.And (Exceptions.ThrowOnNull (type, "type")).And (SimpleElement.Spacer) + .And (Exceptions.ThrowOnNull (name, nameof (name))); + if (parms != null) { + decl.And (new SimpleElement ("[", true)).And (parms).And (new SimpleElement ("]")); + } + Add (decl); + + + CSCodeBlock cb = new CSCodeBlock (null); + + if (getter != null) { + Getter = getter; + LineCodeElementCollection getLine = MakeEtter (getVis, "get", unifiedVis, getVis > setVis); + cb.Add (getLine); + if (getter.Count () == 0) { + getLine.Add (new SimpleElement (";")); + } else { + cb.Add (getter); + } + } + if (setter != null) { + Setter = setter; + LineCodeElementCollection setLine = MakeEtter (setVis, "set", unifiedVis, setVis > getVis); + cb.Add (setLine); + if (setter.Count () == 0) { + setLine.Add (new SimpleElement (";")); + } else { + cb.Add (setter); + } + } + + Add (cb); + } + public CSType PropType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList IndexerParameters { get; private set; } + public CSVisibility GetterVisibility { get; private set; } + public CSVisibility SetterVisibility { get; private set; } + + public CSCodeBlock Getter { get; private set; } + + public CSCodeBlock Setter { get; private set; } + + static LineCodeElementCollection MakeEtter (CSVisibility vis, string getset, + bool unifiedVis, bool moreRestrictiveVis) + { + LineCodeElementCollection getLine = new LineCodeElementCollection (null, false, true); + if (!unifiedVis && vis != CSVisibility.None && moreRestrictiveVis) + getLine.And (new SimpleElement (CSMethod.VisibilityToString (vis))).And (SimpleElement.Spacer); + return getLine.And (new SimpleElement (getset, false)); + } + + public static CSProperty PublicGetSet (CSType type, string name) + { + return new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), + CSVisibility.Public, new CSCodeBlock (), CSVisibility.Public, new CSCodeBlock ()); + } + + public static CSProperty PublicGetPrivateSet (CSType type, string name) + { + return new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), + CSVisibility.Public, new CSCodeBlock (), CSVisibility.Private, new CSCodeBlock ()); + } + + static CSProperty PublicGetPubPrivSetBacking (CSType type, string name, bool declareField, bool setIsPublic, string backingFieldName = null) + { + if (!declareField && backingFieldName == null) + throw new ArgumentException ("declareField must be true if there is no supplied field name", nameof (declareField)); + backingFieldName = backingFieldName ?? MassageName (Exceptions.ThrowOnNull (name, nameof (name))); + + + CSIdentifier backingIdent = new CSIdentifier (backingFieldName); + LineCodeElementCollection getCode = + new LineCodeElementCollection (new ICodeElement [] { CSReturn.ReturnLine (backingIdent) }, false, true); + LineCodeElementCollection setCode = + new LineCodeElementCollection ( + new ICodeElement [] { + CSAssignment.Assign (backingFieldName, new CSIdentifier ("value")) + }, false, true); + CSProperty prop = new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), CSVisibility.Public, + new CSCodeBlock (getCode), + (setIsPublic ? CSVisibility.Public : CSVisibility.Private), new CSCodeBlock (setCode)); + if (declareField) + prop.Insert (0, CSFieldDeclaration.FieldLine (type, backingFieldName)); + return prop; + } + + + public static CSProperty PublicGetSetBacking (CSType type, string name, bool declareField, string backingFieldName = null) + { + return PublicGetPubPrivSetBacking (type, name, true, declareField, backingFieldName); + } + + public static CSProperty PublicGetPrivateSetBacking (CSType type, string name, bool declareField, string backingFieldName = null) + { + return PublicGetPubPrivSetBacking (type, name, false, declareField, backingFieldName); + } + + public static CSProperty PublicGetBacking (CSType type, CSIdentifier name, CSIdentifier backingFieldName, + bool includeBackingFieldDeclaration = false, CSMethodKind methodKind = CSMethodKind.None) + { + LineCodeElementCollection getCode = + new LineCodeElementCollection ( + new ICodeElement [] { + CSReturn.ReturnLine (Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))) + }, false, true); + CSProperty prop = new CSProperty (type, methodKind, Exceptions.ThrowOnNull (name, nameof (name)), + CSVisibility.Public, new CSCodeBlock (getCode), + CSVisibility.Public, null); + if (includeBackingFieldDeclaration) + prop.Insert (0, CSFieldDeclaration.FieldLine (type, backingFieldName)); + return prop; + } + + + public static CSProperty PublicGetBacking (CSType type, string name, string backingFieldName, bool includeBackingFieldDeclaration = false) + { + return PublicGetBacking (type, + new CSIdentifier (Exceptions.ThrowOnNull (name, nameof (name))), + new CSIdentifier (Exceptions.ThrowOnNull (backingFieldName, nameof (backingFieldName))), + includeBackingFieldDeclaration); + } + + static string MassageName (string name) + { + StringBuilder sb = new StringBuilder (); + sb.Append ("_"); + sb.Append (Char.ToLowerInvariant (name [0])); + if (name.Length > 0) + sb.Append (name.Substring (1)); + return sb.ToString (); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs new file mode 100644 index 000000000000..514546f580da --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.CSLang { + public class CSReturn : DelegatedSimpleElement, ICSExpression, ICSLineable { + public CSReturn (ICSExpression expr) + { + Value = expr; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("return ", true); + if (Value != null) + Value.WriteAll (writer); + } + + public ICSExpression Value { get; private set; } + + public static CSLine ReturnLine (ICSExpression expr) + { + return new CSLine (new CSReturn (expr)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs new file mode 100644 index 000000000000..ee756b4e8401 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs @@ -0,0 +1,32 @@ +using System; +namespace SyntaxDynamo.CSLang { + public class CSShortCircuit : DelegatedSimpleElement, ICSLineable { + public CSShortCircuit (CSShortCircuitKind kind) + { + Kind = kind; + } + + public CSShortCircuitKind Kind { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + var keyword = Kind == CSShortCircuitKind.Break ? "break" : "continue"; + writer.Write (keyword, false); + } + + public static CSLine ShortCircuit (CSShortCircuitKind kind) + { + return new CSLine (new CSShortCircuit (kind)); + } + + public static CSLine Continue () + { + return ShortCircuit (CSShortCircuitKind.Continue); + } + + public static CSLine Break () + { + return ShortCircuit (CSShortCircuitKind.Break); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs new file mode 100644 index 000000000000..67f3a406b9c6 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSTernary : CSBaseExpression { + public CSTernary (CSBaseExpression predicate, CSBaseExpression onTrue, CSBaseExpression onFalse, bool addParentheses) + { + Predicate = Exceptions.ThrowOnNull (predicate, "predicate"); + OnTrue = Exceptions.ThrowOnNull (onTrue, "onTrue"); + OnFalse = Exceptions.ThrowOnNull (onFalse, "onFalse"); + AddParentheses = addParentheses; + } + public CSBaseExpression Predicate { get; private set; } + public CSBaseExpression OnTrue { get; private set; } + public CSBaseExpression OnFalse { get; private set; } + public bool AddParentheses { get; set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (AddParentheses) { + writer.Write ('(', true); + } + Predicate.WriteAll (writer); + writer.Write (" ? ", true); + OnTrue.WriteAll (writer); + writer.Write (" : ", true); + OnFalse.WriteAll (writer); + if (AddParentheses) { + writer.Write (')', true); + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs new file mode 100644 index 000000000000..0021aa15d4a9 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSThrow : CSBaseExpression, ICSStatement, ICSLineable { + public CSThrow (CSBaseExpression expr) + { + Expr = Exceptions.ThrowOnNull (expr, "expr"); + } + + public CSBaseExpression Expr { get; private set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("throw ", true); + Expr.WriteAll (writer); + } + + #endregion + + public static CSLine ThrowLine (T exType, CommaListElementCollection args) where T : Exception + { + return new CSLine (new CSThrow (new CSFunctionCall (new CSIdentifier (exType.GetType ().Name), args, true))); + } + + public static CSLine ThrowLine (T exType, string message) where T : Exception + { + CommaListElementCollection args = new CommaListElementCollection (); + if (message != null) + args.Add (CSConstant.Val (message)); + return ThrowLine (exType, args); + } + + public static CSLine ThrowLine(T exType, CSBaseExpression expr) where T : Exception + { + CommaListElementCollection args = new CommaListElementCollection (); + args.Add (Exceptions.ThrowOnNull (expr, nameof (expr))); + return ThrowLine (exType, args); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs new file mode 100644 index 000000000000..dae057dbc005 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.CSLang { + public class CSCatch : DelegatedSimpleElement, ICSStatement { + public CSCatch (CSType catchType, CSIdentifier name, CSCodeBlock body) + { + CatchType = catchType; + Name = name; + Body = body ?? new CSCodeBlock (); + } + + public CSCatch (string catchType, string name, CSCodeBlock body) + : this (new CSSimpleType (catchType), name != null ? new CSIdentifier (name) : null, body) + { + } + + public CSCatch (Type catchType, string name, CSCodeBlock body) + : this (new CSSimpleType (catchType), name != null ? new CSIdentifier (name) : null, body) + { + } + + public CSCatch (CSCodeBlock body) + : this ((CSType)null, null, body) + { + } + + public CSType CatchType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSCodeBlock Body { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + + writer.BeginNewLine (true); + writer.Write ("catch ", false); + if ((object)CatchType != null) { + writer.Write ("(", false); + CatchType.WriteAll (writer); + if ((object)Name != null) { + SimpleElement.Spacer.WriteAll (writer); + Name.WriteAll (writer); + } + writer.Write (")", false); + } + writer.EndLine (); + Body.WriteAll (writer); + writer.EndLine (); + } + } + + public class CSTryCatch : CodeElementCollection, ICSStatement { + public CSTryCatch (CSCodeBlock tryBlock, params CSCatch [] catchBlocks) + { + TryBlock = tryBlock ?? new CSCodeBlock (); + CatchBlocks = new CodeElementCollection (); + CatchBlocks.AddRange (catchBlocks); + + Add (new SimpleElement ("try ", true)); + Add (TryBlock); + Add (CatchBlocks); + } + + public CSTryCatch (CSCodeBlock tryBlock, Type catchType, string name, CSCodeBlock catchBlock) + : this (tryBlock, new CSCatch (catchType, name, catchBlock)) + { + } + + public override void Write (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + base.Write (writer, o); + } + + public CSCodeBlock TryBlock { get; private set; } + public CodeElementCollection CatchBlocks { get; private set; } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs new file mode 100644 index 000000000000..5708dbce1a13 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; +using System.IO; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +namespace SyntaxDynamo.CSLang { + public abstract class CSType : DelegatedSimpleElement { + public override string ToString () => CodeWriter.WriteToString (this); + + public abstract CSFunctionCall Typeof (); + public abstract CSFunctionCall Default (); + public abstract CSFunctionCall Ctor (); + + public static CSType Copy (CSType csType) + { + if (csType is CSSimpleType csSimpleType) { + return new CSSimpleType (csSimpleType); + } + if (csType is CSGenericReferenceType csGen) { + return new CSGenericReferenceType (csGen); + } + throw new NotImplementedException ($"Type {csType.GetType ().Name} needs a copy constructor"); + } + } + + public class CSSimpleType : CSType { + public CSSimpleType (Type t) + : this (t.Name) + { + } + public CSSimpleType (string name) + : this (name, false) + { + } + + public CSSimpleType (CSSimpleType csSimpleType) + : this (csSimpleType.Name, csSimpleType.IsArray) + { + if (csSimpleType.GenericTypes != null) { + GenericTypes = new CSType [csSimpleType.GenericTypes.Length]; + for (int i = 0; i < GenericTypes.Length; i++) { + GenericTypes [i] = CSType.Copy (csSimpleType.GenericTypes [i]); + } + } + } + + public CSSimpleType (string name, bool isArray) + { + hiddenName = Exceptions.ThrowOnNull (name, "name") + (isArray ? "[]" : ""); + } + + public static explicit operator CSSimpleType (string name) + { + return new CSSimpleType (name); + } + + public static CSSimpleType CreateArray (string name) + { + return new CSSimpleType (name, true); + } + + public CSSimpleType (string name, bool isArray, params CSType [] genericSpecialization) + { + IsGeneric = genericSpecialization != null && genericSpecialization.Length > 0; + GenericTypes = genericSpecialization; + GenericTypeName = Exceptions.ThrowOnNull (name, nameof (name)); + IsArray = isArray; + } + + public CSSimpleType (string name, bool isArray, params string [] genericSpecialization) + : this (name, isArray, genericSpecialization.Select (s => new CSSimpleType (s)).ToArray ()) + { + } + + string hiddenName; + public string Name { + get { + return hiddenName ?? GenerateName (); + } + } + public bool IsGeneric { get; private set; } + public string GenericTypeName { get; private set; } + public CSType [] GenericTypes { get; private set; } + public bool IsArray { get; private set; } + public bool IsPointer { get; private set; } + + string GenerateName () + { + StringBuilder sb = new StringBuilder (); + sb.Append (GenericTypeName); + if (GenericTypes != null && GenericTypes.Length > 0) { + sb.Append ("<"); + int i = 0; + foreach (CSType type in GenericTypes) { + if (i > 0) + sb.Append (", "); + sb.Append (type.ToString ()); + i++; + } + sb.Append (">"); + } + if (IsArray) + sb.Append ("[]"); + return sb.ToString (); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Name, false); + } + + public override CSFunctionCall Typeof () + { + return new CSFunctionCall ("typeof", false, new CSIdentifier (Name)); + } + + public override CSFunctionCall Default () + { + return new CSFunctionCall ("default", false, new CSIdentifier (Name)); + } + + public override CSFunctionCall Ctor () + { + return new CSFunctionCall (Name, true); + } + + static CSSimpleType + tBool = new CSSimpleType ("bool"), + tChar = new CSSimpleType ("char"), + tSbyte = new CSSimpleType ("sbyte"), + tShort = new CSSimpleType ("short"), + tInt = new CSSimpleType ("int"), + tLong = new CSSimpleType ("long"), + tFloat = new CSSimpleType ("float"), + tByte = new CSSimpleType ("byte"), + tUshort = new CSSimpleType ("ushort"), + tUint = new CSSimpleType ("uint"), + tUlong = new CSSimpleType ("ulong"), + tDouble = new CSSimpleType ("double"), + tString = new CSSimpleType ("string"), + tObject = new CSSimpleType ("object"), + tIntPtr = new CSSimpleType ("IntPtr"), + tVoid = new CSSimpleType ("void"), + tByteStar = new CSSimpleType ("byte").Star, + tType = new CSSimpleType ("Type"), + tVar = new CSSimpleType ("var"), + tNfloat = new CSSimpleType ("nfloat"), + tNint = new CSSimpleType ("nint"), + tNUint = new CSSimpleType ("nuint") + ; + + public CSSimpleType Star { + get { + if (Name.EndsWith ("[]")) { + throw new NotImplementedException ("Blindly making an array a pointer doesn't do what you think."); + } else { + var ptrType = new CSSimpleType (Name + " *", false); + ptrType.IsPointer = true; + return ptrType; + } + } + } + + public static CSSimpleType Bool { get { return tBool; } } + public static CSSimpleType Char { get { return tChar; } } + public static CSSimpleType SByte { get { return tSbyte; } } + public static CSSimpleType Short { get { return tShort; } } + public static CSSimpleType Int { get { return tInt; } } + public static CSSimpleType Long { get { return tLong; } } + public static CSSimpleType Float { get { return tFloat; } } + public static CSSimpleType Byte { get { return tByte; } } + public static CSSimpleType UShort { get { return tUshort; } } + public static CSSimpleType UInt { get { return tUint; } } + public static CSSimpleType ULong { get { return tUlong; } } + public static CSSimpleType Double { get { return tDouble; } } + public static CSSimpleType String { get { return tString; } } + public static CSSimpleType Object { get { return tObject; } } + public static CSSimpleType IntPtr { get { return tIntPtr; } } + public static CSSimpleType Void { get { return tVoid; } } + public static CSSimpleType ByteStar { get { return tByteStar; } } + public static CSSimpleType Type { get { return tType; } } + public static CSSimpleType Var { get { return tVar; } } + public static CSSimpleType NFloat { get { return tNfloat; } } + public static CSSimpleType NInt => tNint; + public static CSSimpleType NUInt => tNUint; + } + + public class CSGenericReferenceType : CSType { + public CSGenericReferenceType (int depth, int index) + { + Depth = depth; + Index = index; + InterfaceConstraints = new List (); + } + + public CSGenericReferenceType (CSGenericReferenceType csGeneric) + : this (csGeneric.Depth, csGeneric.Index) + { + foreach (var elem in csGeneric.InterfaceConstraints) { + InterfaceConstraints.Add (CSType.Copy (elem)); + } + ReferenceNamer = csGeneric.ReferenceNamer; + } + + // this doesn't really belong here, but I'm going to need it. + public List InterfaceConstraints { get; private set; } + + public int Depth { get; private set; } + public int Index { get; private set; } + public Func ReferenceNamer { get; set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Name, true); + } + + public string Name { + get { + Func namer = ReferenceNamer ?? DefaultNamer; + return namer (Depth, Index); + } + } + + const string kNames = "TUVWABCDEFGHIJKLMN"; + + public static string DefaultNamer (int depth, int index) + { + if (depth < 0 || depth >= kNames.Length) + throw new ArgumentOutOfRangeException (nameof (depth)); + if (index < 0) + throw new ArgumentOutOfRangeException (nameof (index)); + return String.Format ("{0}{1}", kNames [depth], index); + } + + public override CSFunctionCall Typeof () + { + return new CSFunctionCall ("typeof", false, new CSIdentifier (Name)); + } + + public override CSFunctionCall Default () + { + return new CSFunctionCall ("default", false, new CSIdentifier (Name)); + } + + public override CSFunctionCall Ctor () + { + return new CSFunctionCall (Name, true); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs new file mode 100644 index 000000000000..70305c76a982 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public class CSUnaryExpression : CSBaseExpression { + public CSUnaryExpression (CSUnaryOperator op, ICSExpression expr) + { + Operation = op; + Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); + } + protected override void LLWrite (ICodeWriter writer, object o) + { + if (IsPostfix (Operation)) { + Expr.WriteAll (writer); + writer.Write (OperatorToString (Operation), true); + } else { + writer.Write (OperatorToString (Operation), true); + Expr.WriteAll (writer); + } + } + + public CSUnaryOperator Operation { get; private set; } + public ICSExpression Expr { get; private set; } + + static string OperatorToString (CSUnaryOperator op) + { + switch (op) { + case CSUnaryOperator.At: + return "@"; + case CSUnaryOperator.BitNot: + return "~"; + case CSUnaryOperator.Neg: + return "-"; + case CSUnaryOperator.Not: + return "!"; + case CSUnaryOperator.Out: + return "out "; + case CSUnaryOperator.Pos: + return "+"; + case CSUnaryOperator.Ref: + return "ref "; + case CSUnaryOperator.AddressOf: + return "&"; + case CSUnaryOperator.Indirection: + return "*"; + case CSUnaryOperator.Await: + return "await "; + case CSUnaryOperator.PostBang: + return "!"; + case CSUnaryOperator.Question: + return "?"; + default: + throw new ArgumentOutOfRangeException (nameof(op)); + } + } + + static bool IsPostfix (CSUnaryOperator op) + { + return op == CSUnaryOperator.PostBang || op == CSUnaryOperator.Question; + } + + public static CSUnaryExpression AddressOf (ICSExpression expr) + { + return new CSUnaryExpression (CSUnaryOperator.AddressOf, expr); + } + + public static CSUnaryExpression Star (ICSExpression expr) + { + return new CSUnaryExpression (CSUnaryOperator.Indirection, expr); + } + + public static CSUnaryExpression Out (CSIdentifier id) + { + return new CSUnaryExpression (CSUnaryOperator.Out, id); + } + + public static CSUnaryExpression Out (string id) + { + return Out (new CSIdentifier (id)); + } + + public static CSUnaryExpression Ref (CSIdentifier id) + { + return new CSUnaryExpression (CSUnaryOperator.Ref, id); + } + + public static CSUnaryExpression Ref (string id) + { + return Ref (new CSIdentifier (id)); + } + + public static CSUnaryExpression Await (ICSExpression expr) + { + return new CSUnaryExpression (CSUnaryOperator.Await, expr); + } + + public static CSUnaryExpression PostBang (ICSExpression expr) + { + return new CSUnaryExpression (CSUnaryOperator.PostBang, expr); + } + + public static CSUnaryExpression Question (ICSExpression expr) + { + return new CSUnaryExpression (CSUnaryOperator.Question, expr); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs new file mode 100644 index 000000000000..ebe9966ad8dd --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public class CSUsing : SimpleLineElement { + public CSUsing (string package) + : base (string.Format ("using {0};", Exceptions.ThrowOnNull (package, nameof(package))), false, false, false) + { + Package = package; + } + + public string Package { get; private set; } + } + + public class CSUsingPackages : CodeElementCollection { + public CSUsingPackages () : base () { } + public CSUsingPackages (params CSUsing [] use) + : this () + { + AddRange (use); + } + public CSUsingPackages (params string [] use) + : this () + { + AddRange (use.Select (s => new CSUsing (s))); + } + + public CSUsingPackages And (CSUsing use) + { + Add (use); + return this; + } + + public CSUsingPackages And (string package) { return And (new CSUsing (package)); } + + public void AddIfNotPresent (string package, CSIdentifier protectedBy = null) + { + if (String.IsNullOrEmpty (package)) + return; + CSUsing target = new CSUsing (package); + if (!this.Exists (use => use.Contents == target.Contents)) { + if ((object)protectedBy != null) { + CSConditionalCompilation.ProtectWithIfEndif (protectedBy, target); + } + Add (target); + } + } + + public void AddIfNotPresent (Type t, CSIdentifier protectedBy = null) + { + AddIfNotPresent (t.Namespace, protectedBy); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs new file mode 100644 index 000000000000..8b993f4e2ad8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.CSLang { + public enum CSVisibility { + None = 0, + Public, + Internal, + Protected, + Private, + } + + public enum CSMethodKind { + None = 0, + Static, + StaticExtern, + StaticNew, + Virtual, + Override, + Extern, + New, + Abstract, + Interface, + Unsafe, + StaticUnsafe, + } + + public enum CSBinaryOperator { + Add = 0, + Sub, + Mul, + Div, + Mod, + And, + Or, + Less, + Greater, + Equal, + NotEqual, + LessEqual, + GreaterEqual, + BitAnd, + BitOr, + BitXor, + LeftShift, + RightShift, + Dot, + Is, + As, + NullCoalesce, + } + + public enum CSUnaryOperator { + Neg = 0, + Pos, + At, + Not, + BitNot, + Ref, + Out, + AddressOf, + Indirection, + Await, + PostBang, + Question, + } + + public enum CSAssignmentOperator { + Assign, + AddAssign, + SubAssign, + MulAssign, + DivAssign, + ModAssign, + AndAssign, + OrAssign, + XorAssign + } + + public enum CSParameterKind { + None, + Ref, + Out, + Params, + This + } + + public enum CSShortCircuitKind { + Break, + Continue, + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs new file mode 100644 index 000000000000..a6c2d21ff57f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; + +namespace SyntaxDynamo.CSLang { + public interface ICSExpression : ICodeElement { + } + + public interface ICSExpressionList : ICodeElementSet { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs new file mode 100644 index 000000000000..82f3eabaa15c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public interface ICSLineable { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs new file mode 100644 index 000000000000..d876d1ed14f8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.CSLang { + public interface ICSStatement { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs new file mode 100644 index 000000000000..a3fcc27e140d --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.CSLang { + public interface ICSTopLevelDeclaration : ICodeElement { + } + + public class CSTopLevelDeclations : CodeElementCollection { + public CSTopLevelDeclations (params ICSTopLevelDeclaration [] decls) + : base () + { + AddRange (Exceptions.ThrowOnNull (decls, "decls")); + } + + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs new file mode 100644 index 000000000000..ef2b642d8f27 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public enum ImportKind { + None, + TypeAlias, + Struct, + Class, + Enum, + Protocol, + Var, + Func, + } + + public enum SLParameterKind { + None, + Var, + InOut, + } + + public enum BinaryOp { + None = -1, + Add, + Sub, + Mul, + Div, + Mod, + And, + Or, + Less, + Greater, + Equal, + NotEqual, + LessEqual, + GreaterEqual, + BitAnd, + BitOr, + BitXor, + LeftShift, + RightShift, + Dot, + AndAdd, + AndSub, + AndMul, + Assign, + } + + public enum UnaryOp { + Neg = 0, + Pos, + At, + Not, + BitNot, + } + + public enum Visibility { + None, + Public, + Private, + Internal, + Open, + FilePrivate, + } + + [Flags] + public enum FunctionKind { + None = 0, + Override = 1 << 0, + Final = 1 << 1, + Static = 1 << 2, + Throws = 1 << 3, + Constructor = 1 << 4, + Class = 1 << 5, + Rethrows = 1 << 6, + Required = 1 << 7, + Async = 1 << 8, + } + + public enum NamedType { + Class = 0, + Struct, + Extension, + Actor, + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs new file mode 100644 index 000000000000..fb0dde1b419f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public interface ISLExpr : ICodeElement { + } + + public interface ISLExprList : ICodeElementSet { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs new file mode 100644 index 000000000000..700f123f833e --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public interface ISLLineable { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs new file mode 100644 index 000000000000..d6f4232d69ae --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public interface ISLStatement { + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs new file mode 100644 index 000000000000..3ae091834905 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLAddressOf : SLBaseExpr { + public SLAddressOf (SLBaseExpr expr, bool addParens) + { + Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); + AddParens = addParens; + } + + public SLBaseExpr Expr { get; private set; } + public bool AddParens { get; set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('&', false); + if (AddParens) + writer.Write ('(', false); + Expr.WriteAll (writer); + if (AddParens) + writer.Write (')', false); + } + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs new file mode 100644 index 000000000000..5912db882fce --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLArgument : DelegatedSimpleElement { + public SLArgument (SLIdentifier ident, SLBaseExpr expr, bool identifierIsRequired = false) + { + Identifier = identifierIsRequired ? Exceptions.ThrowOnNull (ident, nameof(ident)) : ident; + Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); + IdentifierIsRequired = identifierIsRequired; + } + + public SLArgument (string ident, SLBaseExpr expr, bool identifierIsRequired = false) + : this (!String.IsNullOrEmpty (ident) ? new SLIdentifier (ident) : null, expr, identifierIsRequired) + { + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (Identifier != null && IdentifierIsRequired) { + Identifier.WriteAll (writer); + writer.Write (": ", true); + } + Expr.WriteAll (writer); + } + + + + public SLIdentifier Identifier { get; private set; } + public SLBaseExpr Expr { get; private set; } + public bool IdentifierIsRequired { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs new file mode 100644 index 000000000000..de6b021abd52 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLAsExpr : SLBaseExpr { + public SLAsExpr (SLType asType) + { + AsType = Exceptions.ThrowOnNull (asType, nameof (asType)); + } + + public SLType AsType { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("as ", true); + AsType.WriteAll (writer); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs new file mode 100644 index 000000000000..c405fc340d49 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Reflection; +using System.Text; + +namespace SyntaxDynamo.SwiftLang { + public class SLAttribute : LineCodeElementCollection { + public SLAttribute (SLIdentifier name, CommaListElementCollection args, bool isSingleLine = false) + : base (isSingleLine, false, isSingleLine) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + Add (new SimpleElement ("@")); + var stringRep = new StringBuilder (Name.Name); + Add (Name); + if (args != null) { + Add (new SimpleElement ("(")); + Add (args); + Add (new SimpleElement (")")); + stringRep.Append ("("); + foreach (var arg in args) { + if (arg is SLIdentifier argId) { + stringRep.Append (argId.Name); + } + } + stringRep.Append (")"); + } + StringRep = stringRep.ToString (); + } + + public SLAttribute (string name, CommaListElementCollection args = null) + : this (new SLIdentifier (name), args) + { + } + + public SLAttribute (string name, bool isSingleLine, params SLBaseExpr [] args) + : this (new SLIdentifier (name), new CommaListElementCollection (args), isSingleLine) + { + } + + public SLIdentifier Name { get; private set; } + + public string StringRep { get; private set; } + + static SLAttribute objc; + + public static SLAttribute ObjC () + { + if (objc == null) { + objc = new SLAttribute ("objc"); + } + return objc; + } + + static SLAttribute convc; + + public static SLAttribute ConventionC () + { + if (convc == null) { + convc = new SLAttribute ("convention", new CommaListElementCollection () { new SLIdentifier ("c") }); + } + return convc; + } + + static SLAttribute escaping; + + public static SLAttribute Escaping () + { + if (escaping == null) { + escaping = new SLAttribute ("escaping"); + } + return escaping; + } + + void SLAttributeWriteAll (object sender, WriteEventArgs eventArgs) + { + this.WriteAll (eventArgs.Writer); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs new file mode 100644 index 000000000000..aac2bea949ce --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public abstract class SLBaseExpr : DelegatedSimpleElement, ISLExpr { + public static SLBaseExpr operator + (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Add, lhs, rhs); + } + + public static SLBaseExpr operator - (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Sub, lhs, rhs); + } + + public static SLBaseExpr operator * (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Mul, lhs, rhs); + } + + public static SLBaseExpr operator / (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Div, lhs, rhs); + } + + public static SLBaseExpr operator % (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Mod, lhs, rhs); + } + + public static SLBaseExpr operator < (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Less, lhs, rhs); + } + + public static SLBaseExpr operator > (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.Greater, lhs, rhs); + } + + public static SLBaseExpr operator <= (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.LessEqual, lhs, rhs); + } + + public static SLBaseExpr operator >= (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.GreaterEqual, lhs, rhs); + } + + public static SLBaseExpr operator & (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.BitAnd, lhs, rhs); + } + + public static SLBaseExpr operator | (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.BitOr, lhs, rhs); + } + + public static SLBaseExpr operator ^ (SLBaseExpr lhs, SLBaseExpr rhs) + { + return new SLBinaryExpr (BinaryOp.BitXor, lhs, rhs); + } + + public static SLBaseExpr operator << (SLBaseExpr lhs, int bits) + { + return new SLBinaryExpr (BinaryOp.LeftShift, lhs, SLConstant.Val (bits)); + } + + public static SLBaseExpr operator >> (SLBaseExpr lhs, int bits) + { + return new SLBinaryExpr (BinaryOp.RightShift, lhs, SLConstant.Val (bits)); + } + + public SLBaseExpr Dot (SLBaseExpr other) + { + return new SLBinaryExpr (BinaryOp.Dot, this, other); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs new file mode 100644 index 000000000000..16bdbc6c695c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLBinaryExpr : SLBaseExpr { + public SLBinaryExpr (BinaryOp op, ISLExpr lhs, ISLExpr rhs) + { + Operation = op; + CustomOperation = null; + Left = Exceptions.ThrowOnNull (lhs, nameof(lhs)); + Right = Exceptions.ThrowOnNull (rhs, nameof(rhs)); + } + + public SLBinaryExpr (string op, ISLExpr lhs, ISLExpr rhs) + { + CustomOperation = Exceptions.ThrowOnNull (op, nameof (op)); + Operation = BinaryOp.None; + Left = Exceptions.ThrowOnNull (lhs, nameof (lhs)); + Right = Exceptions.ThrowOnNull (rhs, nameof (rhs)); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Left.WriteAll (writer); + var operation = CustomOperation ?? OpToString (Operation); + operation = Operation == BinaryOp.Dot ? $"{operation}" : $" {operation} "; + writer.Write (operation, true); + Right.WriteAll (writer); + } + + public string CustomOperation { get; private set; } + public BinaryOp Operation { get; private set; } + public ISLExpr Left { get; private set; } + public ISLExpr Right { get; private set; } + + static string OpToString (BinaryOp op) + { + switch (op) { + case BinaryOp.Add: + return "+"; + case BinaryOp.AndAdd: + return "&+"; + case BinaryOp.Sub: + return "-"; + case BinaryOp.AndSub: + return "&-"; + case BinaryOp.Mul: + return "*"; + case BinaryOp.AndMul: + return "&*"; + case BinaryOp.Div: + return "/"; + case BinaryOp.Mod: + return "%"; + case BinaryOp.And: + return "&&"; + case BinaryOp.Or: + return "||"; + case BinaryOp.Less: + return "<"; + case BinaryOp.Greater: + return ">"; + case BinaryOp.Equal: + return "=="; + case BinaryOp.NotEqual: + return "!="; + case BinaryOp.LessEqual: + return "<="; + case BinaryOp.GreaterEqual: + return ">="; + case BinaryOp.BitAnd: + return "&"; + case BinaryOp.BitOr: + return "|"; + case BinaryOp.BitXor: + return "^"; + case BinaryOp.LeftShift: + return ">>"; + case BinaryOp.RightShift: + return "<<"; + case BinaryOp.Dot: + return "."; + case BinaryOp.Assign: + return "="; + default: + throw new ArgumentOutOfRangeException (nameof(op)); + } + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs new file mode 100644 index 000000000000..edcb7184bf65 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLBinding : SLBaseExpr, ISLLineable { + public SLBinding (SLIdentifier id, ISLExpr value, SLType typeAnnotation = null) + { + Name = Exceptions.ThrowOnNull (id, nameof(id)); + Value = value; + TypeAnnotation = typeAnnotation; + } + + public SLBinding (string id, ISLExpr value, SLType typeAnnotation = null) + : this (new SLIdentifier (id), value, typeAnnotation) + { + } + + public SLBinding (SLSubscriptExpr sub, ISLExpr value) + { + Name = null; + Subscript = Exceptions.ThrowOnNull (sub, nameof(sub)); + Value = value; + TypeAnnotation = null; + } + + public SLIdentifier Name { get; private set; } + public SLSubscriptExpr Subscript { get; private set; } + public SLType TypeAnnotation { get; private set; } + public ISLExpr Value { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + if (Name != null) + Name.WriteAll (writer); + else + Subscript.WriteAll (writer); + + if (TypeAnnotation != null) { + writer.Write (": ", true); + TypeAnnotation.WriteAll (writer); + } + + if (Value != null) { + writer.Write (" = ", true); + Value.WriteAll (writer); + } + writer.EndLine (); + } + + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs new file mode 100644 index 000000000000..d3a2bd82c826 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLClass : ICodeElementSet { + public SLClass (Visibility vis, SLIdentifier name, IEnumerable methods = null, + bool isStatic = false, bool isSealed = false, NamedType namedType = NamedType.Class, + bool isFinal = false) + { + // swift hates when you put public on an extension on a public type + Visibility = vis == Visibility.Public && namedType == NamedType.Extension ? Visibility.None : vis; + IsStatic = isStatic; + IsSealed = isSealed; + IsFinal = isFinal; + NamedType = namedType; + Name = Exceptions.ThrowOnNull (name, "name"); + Inheritance = new SLInheritance (); + Fields = new List (); + Constructors = new List (); + Methods = new List (); + Properties = new List (); + InnerClasses = new SLClasses (); + Subscripts = new List (); + Generics = new SLGenericTypeDeclarationCollection (); + + if (methods != null) + Methods.AddRange (methods); + } + + public SLClass (Visibility vis, string name, + IEnumerable members = null, bool isStatic = false, bool isSealed = false, NamedType namedType = NamedType.Class, + bool isFinal = false) + : this (vis, new SLIdentifier (name), members, isStatic, isSealed, namedType, isFinal) + { + } + + public Visibility Visibility { get; private set; } + public bool IsStatic { get; private set; } + public bool IsSealed { get; private set; } + public bool IsFinal { get; private set; } + public NamedType NamedType { get; private set; } + public SLIdentifier Name { get; private set; } + public SLInheritance Inheritance { get; private set; } + public List Fields { get; private set; } + public List Constructors { get; private set; } + public List Methods { get; private set; } + public List Properties { get; private set; } + public SLClasses InnerClasses { get; private set; } + public List Subscripts { get; private set; } + public SLGenericTypeDeclarationCollection Generics { get; private set; } + + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + #endregion + + static SLIdentifier IdentifierForNamedType (NamedType nt) + { + switch (nt) { + case NamedType.Class: return new SLIdentifier ("class"); + case NamedType.Struct: return new SLIdentifier ("struct"); + case NamedType.Extension: return new SLIdentifier ("extension"); + case NamedType.Actor: return new SLIdentifier ("actor"); + default: + throw new ArgumentOutOfRangeException ($"Unknown named type {nt}", nameof (nt)); + } + } + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + var decl = new LineCodeElementCollection (true, false, true); + if (Visibility != Visibility.None) + decl.Add (new SimpleElement (SLFunc.ToVisibilityString (Visibility) + " ")); + if (IsStatic) + decl.Add (new SimpleElement ("static ", true)); + if (IsSealed) + decl.Add (new SimpleElement ("sealed ", true)); + if (IsFinal) + decl.Add (new SimpleElement ("final ", true)); + decl.Add (IdentifierForNamedType (NamedType)); + decl.Add (SimpleElement.Spacer); + decl.Add (Name); + if (Generics.Count > 0) { + decl.Add (Generics); + } + if (Inheritance.Count > 0) { + decl.Add (new SimpleElement (" : ", true)); + decl.Add (Inheritance); + } + yield return decl; + + foreach (var constraint in Generics.ConstraintElements) { + yield return constraint; + } + + var contents = new DecoratedCodeElementCollection ("{", "}", + true, true, true); + + contents.AddRange (Fields); + contents.AddRange (Constructors); + contents.AddRange (Methods); + contents.AddRange (Properties); + contents.AddRange (Subscripts); + contents.Add (InnerClasses); + + yield return contents; + } + } + + #endregion + } + + public class SLClasses : CodeElementCollection { + public SLClasses (IEnumerable classes = null) + : base () + { + if (classes != null) + AddRange (classes); + } + + public SLClasses And (SLClass use) + { + Add (use); + return this; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs new file mode 100644 index 000000000000..3f7673f32f57 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLClosure : SLBaseExpr { + public SLClosure (SLType type, SLTupleType parms, CodeElementCollection body, bool throws) + { + OuterBlock = new SLCodeBlock (null); + Parameters = parms; + if (parms != null) { + OuterBlock.Add (parms); + OuterBlock.Add (SimpleElement.Spacer); + if (throws) { + OuterBlock.Add (new SimpleElement ("throws ")); + } + if (type != null) { + Type = type; + OuterBlock.Add (new SimpleElement ("-> ")); + OuterBlock.Add (Type); + OuterBlock.Add (SimpleElement.Spacer); + } + OuterBlock.Add (new SimpleElement ("in ")); + OuterBlock.Add (body); + } + } + + public SLTupleType Parameters { get; private set; } + public SLCodeBlock OuterBlock { get; private set; } + public CodeElementCollection Body { get; private set; } + public SLType Type { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + OuterBlock.WriteAll (writer); + } + } + +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs new file mode 100644 index 000000000000..cf170627aeb8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLClosureCall : SLBaseExpr, ISLLineable { + + public SLClosureCall (SLClosure closure, DelegatedCommaListElemCollection paramList) + { + Closure = Exceptions.ThrowOnNull (closure, "closure"); + Parameters = paramList ?? new DelegatedCommaListElemCollection (SLFunctionCall.WriteElement); + } + + public SLClosure Closure { get; private set; } + public DelegatedCommaListElemCollection Parameters { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Closure.WriteAll (writer); + writer.Write ("(", false); + Parameters.WriteAll (writer); + writer.Write (")", false); + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs new file mode 100644 index 000000000000..08ebf0361efd --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLCodeBlock : DecoratedCodeElementCollection, ISLStatement { + public SLCodeBlock (IEnumerable statements) + : this ("{", "}", statements) + { + } + + public SLCodeBlock (string start, string end, IEnumerable statements) + : base (Exceptions.ThrowOnNull (start, nameof(start)), + Exceptions.ThrowOnNull (end, nameof(end)), + true, true, true) + { + if (statements != null) { + foreach (ICodeElement elem in statements) { + And (elem); + } + } + } + + public SLCodeBlock And (ICodeElement elem) + { + if (!((elem is ISLStatement) || (elem is ISLLineable))) + throw new ArgumentException ("contents must each be an ISLStatement or ISLLineable"); + Add (elem); + return this; + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs new file mode 100644 index 000000000000..15f59adf1e6b --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLCommaListExpr : SLBaseExpr { + public SLCommaListExpr (params SLBaseExpr [] exprs) + { + Exprs = new List (); + if (exprs != null) + Exprs.AddRange (exprs); + } + + public List Exprs { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + bool isFirst = true; + foreach (SLBaseExpr expr in Exprs) { + if (!isFirst) + writer.Write (", ", true); + isFirst = false; + expr.WriteAll (writer); + } + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs new file mode 100644 index 000000000000..1c0342c30c16 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.SwiftLang { + public class SLComment : DelegatedSimpleElement { + public SLComment (string contents, bool onOwnLine) + { + Contents = contents; + OnOwnLine = onOwnLine; + } + + public bool OnOwnLine { get; set; } + public string Contents { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (OnOwnLine) { + writer.BeginNewLine (true); + } else { + SimpleElement.Spacer.Write (writer, o); + } + writer.Write ("// ", false); + writer.Write (Contents, false); + writer.EndLine (); + } + + public void AttachBefore (ICodeElement item) + { + item.Begin += (s, writeEventArgs) => { + this.WriteAll (writeEventArgs.Writer); + }; + } + + public void AttachAfter (ICodeElement item) + { + item.End += (s, writeEventArgs) => { + this.WriteAll (writeEventArgs.Writer); + }; + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs new file mode 100644 index 000000000000..fe2045f0b50a --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLConditionalCompilation : LineCodeElementCollection { + SLConditionalCompilation (SLIdentifier tag, SLIdentifier condition) + : base (true, false, false) + { + Add (tag); + if (condition != null) { + Add (SimpleElement.Spacer); + Add (condition); + } + } + + public SLConditionalCompilation AttachBefore (ICodeElement thing) + { + Exceptions.ThrowOnNull (thing, nameof (thing)); + thing.Begin += (s, eventArgs) => { + this.WriteAll (eventArgs.Writer); + }; + return this; + } + + public SLConditionalCompilation AttachAfter (ICodeElement thing) + { + Exceptions.ThrowOnNull (thing, nameof (thing)); + thing.End += (s, eventArgs) => { + this.WriteAll (eventArgs.Writer); + }; + return this; + } + + + + static SLConditionalCompilation _else = new SLConditionalCompilation (new SLIdentifier ("#else"), null); + public static SLConditionalCompilation Else { get { return _else; } } + static SLConditionalCompilation _endif = new SLConditionalCompilation (new SLIdentifier ("#endif"), null); + public static SLConditionalCompilation Endif { get { return _endif; } } + + public static SLConditionalCompilation If (SLIdentifier condition) + { + return new SLConditionalCompilation (new SLIdentifier ("#if"), Exceptions.ThrowOnNull (condition, nameof (condition))); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs new file mode 100644 index 000000000000..6bf543ae99ff --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.CodeDom.Compiler; +using System.CodeDom; + +namespace SyntaxDynamo.SwiftLang { + public class SLConstant : SLBaseExpr { + public SLConstant (string val) + { + Value = Exceptions.ThrowOnNull (val, nameof(val)); + } + + public string Value { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Value, false); + } + + public static SLConstant Val (byte b) { return new SLConstant (b.ToString ()); } + public static SLConstant Val (sbyte sb) { return new SLConstant (sb.ToString ()); } + public static SLConstant Val (ushort us) { return new SLConstant (us.ToString ()); } + public static SLConstant Val (short s) { return new SLConstant (s.ToString ()); } + public static SLConstant Val (uint ui) { return new SLConstant (ui.ToString ()); } + public static SLConstant Val (int i) { return new SLConstant (i.ToString ()); } + public static SLConstant Val (ulong ul) { return new SLConstant (ul.ToString ()); } + public static SLConstant Val (long l) { return new SLConstant (l.ToString ()); } + public static SLConstant Val (float f) + { + return new SLConstant (f.ToString ()); // AFAIK, there is no explicit way to distinguish between a float or double + // constant in swift + } + public static SLConstant Val (double d) { return new SLConstant (d.ToString ()); } + public static SLConstant Val (bool b) { return new SLConstant (b ? "true" : "false"); } + public static SLConstant Val (char c) { return new SLConstant (ToCharLiteral (c)); } + public static SLConstant Val (string s) { return new SLConstant (ToStringLiteral (s)); } + + static SLConstant any = new SLConstant ("_"); + public static SLConstant Any { get { return any; } } + + static SLConstant kNil = new SLConstant ("nil"); + public static SLConstant Nil { get { return kNil; } } + + static string ToCharLiteral (char c) // uses C# semantics. Eh. + { + using (var writer = new StringWriter ()) { + using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { + provider.GenerateCodeFromExpression (new CodePrimitiveExpression (c), writer, null); + return writer.ToString (); + } + } + } + + static string ToStringLiteral (string s) + { + using (var writer = new StringWriter ()) { + using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { + provider.GenerateCodeFromExpression (new CodePrimitiveExpression (s), writer, null); + return writer.ToString (); + } + } + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs new file mode 100644 index 000000000000..832581fd4902 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLDeclaration : LineCodeElementCollection, ISLExpr, ISLLineable { + public SLDeclaration (bool isLet, SLBinding binding, Visibility vis = Visibility.Private, bool isStatic = false) + : base (null, false, true) + { + IsLet = isLet; + IsStatic = isStatic; + And (new SimpleElement (SLFunc.ToVisibilityString (vis))).And (SimpleElement.Spacer); + if (IsStatic) + Add (new SimpleElement ("static ", true)); + And (new SimpleElement (isLet ? "let" : "var")).And (SimpleElement.Spacer); + Binding = binding; + Add (Binding); + } + + public SLDeclaration (bool isLet, string name, SLType typeAnnotation = null, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + : this (isLet, new SLIdentifier (Exceptions.ThrowOnNull (name, nameof(name))), typeAnnotation, value, vis, isStatic) + { + } + + public SLDeclaration (bool isLet, SLIdentifier name, SLType typeAnnotation = null, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + : this (isLet, new SLBinding (name, value, typeAnnotation), vis, isStatic) + { + } + + public bool IsLet { get; private set; } + public Visibility Visibilty { get; private set; } + public SLBinding Binding { get; private set; } + public bool IsStatic { get; private set; } + + + public static SLLine LetLine (SLIdentifier name, SLType typeAnnotation, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + { + return new SLLine (new SLDeclaration (true, name, typeAnnotation, value, vis, isStatic)); + } + + public static SLLine LetLine (string name, SLType typeAnnotation, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + { + return new SLLine (new SLDeclaration (true, name, typeAnnotation, value, vis, isStatic)); + } + + public static SLLine VarLine (SLIdentifier name, SLType typeAnnotation, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + { + return new SLLine (new SLDeclaration (false, name, typeAnnotation, value, vis, isStatic)); + } + + public static SLLine VarLine (string name, SLType typeAnnotation, ISLExpr value = null, + Visibility vis = Visibility.Private, bool isStatic = false) + { + return new SLLine (new SLDeclaration (false, name, typeAnnotation, value, vis, isStatic)); + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs new file mode 100644 index 000000000000..ca67c0572766 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLCatch : DelegatedSimpleElement, ISLStatement { + public SLCatch (ICodeElement catchExpr, SLCodeBlock body) + { + CatchExpr = catchExpr; + Body = body ?? new SLCodeBlock (null); + } + + public SLCatch () + : this ((ICodeElement)null, null) + { + } + + public SLCatch (string name, SLType typeMatch) + : this (SLLetMatch.LetAs (name, typeMatch), null) + { + } + + public ICodeElement CatchExpr { get; private set; } + public SLCodeBlock Body { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write ("catch ", false); + if (CatchExpr != null) { + CatchExpr.WriteAll (writer); + } + writer.EndLine (); + Body.WriteAll (writer); + writer.EndLine (); + } + } + + public class SLDo : CodeElementCollection, ISLStatement { + public SLDo (SLCodeBlock doBlock, params SLCatch [] catchBlocks) + { + DoBlock = doBlock ?? new SLCodeBlock (null); + CatchBlocks = new CodeElementCollection (); + CatchBlocks.AddRange (catchBlocks); + + Add (new SimpleElement ("do ", true)); + Add (DoBlock); + Add (CatchBlocks); + } + + public SLDo (SLCodeBlock doBlock, string name, SLType catchType) + : this (doBlock, new SLCatch (name, catchType)) + { + } + + public SLCodeBlock DoBlock { get; private set; } + public CodeElementCollection CatchBlocks { get; private set; } + + public override void Write (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + base.Write (writer, o); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs new file mode 100644 index 000000000000..3975ddd09fa0 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLFile : ICodeElementSet { + public SLFile (SLImportModules import) + { + Imports = import ?? new SLImportModules (); + Declarations = new List (); + Classes = new SLClasses (); + Functions = new List (); + Trailer = new List (); + } + + public SLImportModules Imports { get; private set; } + public List Declarations { get; private set; } + public SLClasses Classes { get; private set; } + public List Functions { get; private set; } + public List Trailer { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite (ICodeWriter writer) + { + OnBegin (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBegin (WriteEventArgs args) + { + Begin (this, args); + } + + public void Write (ICodeWriter writer, object o) + { + } + + public void EndWrite (ICodeWriter writer, object o) + { + OnEnd (new WriteEventArgs (writer)); + } + + protected virtual void OnEnd (WriteEventArgs args) + { + End (this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + yield return Imports; + foreach (var decl in Declarations) + yield return decl; + yield return Classes; + foreach (var func in Functions) + yield return func; + foreach (var trailerElem in Trailer) + yield return trailerElem; + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs new file mode 100644 index 000000000000..0c48271a0cc9 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLFunc : ICodeElementSet { + public SLFunc (Visibility vis, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body) + : this (vis, type, name, parms, body, false) + { + } + + public SLFunc (Visibility vis, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body, bool throws) + : this (vis, (throws ? FunctionKind.Throws : FunctionKind.None), type, name, parms, body) + { + } + + public SLFunc (Visibility vis, FunctionKind funcKind, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body, bool isOptional = false) + { + GenericParams = new SLGenericTypeDeclarationCollection (); + Visibility = vis; + ReturnType = type; + bool isConstructor = (funcKind & FunctionKind.Constructor) != 0; + Name = isConstructor ? new SLIdentifier (isOptional ? "init?" : "init") : Exceptions.ThrowOnNull (name, nameof (name)); + Parameters = parms ?? new SLParameterList (); + Body = Exceptions.ThrowOnNull (body, nameof (body)); + FuncKind = funcKind; + IsConstructor = isConstructor; + IsOptional = isOptional; + } + + public bool IsConstructor { get; private set; } + public FunctionKind FuncKind { get; private set; } + public Visibility Visibility { get; private set; } + public SLType ReturnType { get; private set; } + public SLIdentifier Name { get; private set; } + public SLParameterList Parameters { get; private set; } + public SLCodeBlock Body { get; private set; } + public SLGenericTypeDeclarationCollection GenericParams { get; private set; } + public bool IsOptional { get; private set; } + + + public static string ToVisibilityString (Visibility vis) + { + switch (vis) { + case Visibility.Private: + return "private"; + case Visibility.Public: + return "public"; + case Visibility.None: + return ""; + case Visibility.Internal: + return "internal"; + case Visibility.Open: + return "open"; + case Visibility.FilePrivate: + return "fileprivate"; + default: + throw new ArgumentOutOfRangeException (nameof (vis)); + } + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + public IEnumerable Elements { + get { + if (Visibility != Visibility.None) { + yield return new SimpleElement (ToVisibilityString (Visibility), false); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Final) != 0) { + yield return new SimpleElement ("final"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Override) != 0) { + yield return new SimpleElement ("override"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Required) != 0) { + yield return new SimpleElement ("required"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Static) != 0) { + yield return new SimpleElement ("static"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Class) != 0) { + yield return new SimpleElement ("class"); + yield return SimpleElement.Spacer; + } + + if (!IsConstructor) { + yield return new SimpleElement ("func"); + yield return SimpleElement.Spacer; + } + + + yield return Name; + yield return GenericParams; + yield return Parameters; + + if ((FuncKind & FunctionKind.Async) != 0) { + yield return SimpleElement.Spacer; + yield return new SimpleElement ("async"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Throws) != 0) { + yield return SimpleElement.Spacer; + yield return new SimpleElement ("throws"); + yield return SimpleElement.Spacer; + } + if ((FuncKind & FunctionKind.Rethrows) != 0) { + yield return SimpleElement.Spacer; + yield return new SimpleElement ("rethrows"); + yield return SimpleElement.Spacer; + } + if (!IsConstructor && ReturnType != null) { + yield return SimpleElement.Spacer; + yield return new SimpleElement ("->"); + yield return SimpleElement.Spacer; + yield return ReturnType; + } + foreach (ICodeElement constr in GenericParams.ConstraintElements) { + yield return constr; + } + + yield return Body; + } + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs new file mode 100644 index 000000000000..b225a8dd8cc8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLFunctionCall : SLBaseExpr, ISLLineable { + public SLFunctionCall (SLIdentifier ident, DelegatedCommaListElemCollection paramList) + { + Name = ident; + Parameters = paramList ?? new DelegatedCommaListElemCollection (WriteElement); + } + + public SLFunctionCall (string identifier, bool isConstructor, params SLArgument [] parameters) + : this (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), + isConstructor ? new DelegatedCommaListElemCollection (WriteAllElements, parameters) : + new DelegatedCommaListElemCollection (WriteElement, parameters)) + { + } + + public SLFunctionCall (string identifier, bool isConstructor, bool writeAllParameterParts, params SLArgument [] parameters) + : this (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), + writeAllParameterParts ? new DelegatedCommaListElemCollection (WriteAllElements, parameters) : + new DelegatedCommaListElemCollection (WriteElement, parameters)) + { + } + + + protected override void LLWrite (ICodeWriter writer, object o) + { + Name.WriteAll (writer); + writer.Write ("(", false); + Parameters.WriteAll (writer); + writer.Write (")", false); + } + + public SLIdentifier Name { get; private set; } + public DelegatedCommaListElemCollection Parameters { get; private set; } + public bool IncludeFirstParameterLabel { get; set; } + + public static void WriteElement (ICodeWriter writer, int i, SLArgument arg) + { + if (i == 0 && !arg.IdentifierIsRequired) { + arg.Expr.WriteAll (writer); + } else { + arg.WriteAll (writer); + } + } + + public static void WriteAllElements (ICodeWriter writer, int i, SLArgument arg) + { + arg.WriteAll (writer); + } + + + public static SLLine FunctionCallLine (SLIdentifier identifier, params SLArgument [] parameters) + { + return new SLLine (new SLFunctionCall (identifier, + new DelegatedCommaListElemCollection (WriteElement, parameters))); + } + + public static SLLine FunctionCallLine (string identifier, params SLArgument [] parameters) + { + return new SLLine (new SLFunctionCall (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), + new DelegatedCommaListElemCollection (WriteElement, parameters))); + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs new file mode 100644 index 000000000000..dd427f69b2af --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLGenericConstraint : DelegatedSimpleElement { + public SLGenericConstraint (bool isInheritance, SLType firstType, SLType secondType) + { + IsInheritance = isInheritance; + FirstType = Exceptions.ThrowOnNull (firstType, nameof (firstType)); + SecondType = Exceptions.ThrowOnNull (secondType, nameof (secondType)); + } + + public bool IsInheritance { get; private set; } + public SLType FirstType { get; private set; } + public SLType SecondType { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + FirstType.Write (writer, o); + writer.Write (String.Format (" {0} ", IsInheritance ? ":" : "=="), true); + SecondType.Write (writer, o); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs new file mode 100644 index 000000000000..fb2145ff2d16 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang +{ + public class SLGenericTypeDeclaration + { + public SLGenericTypeDeclaration(SLIdentifier name) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + Constraints = new List(); + } + + public SLIdentifier Name { get; private set; } + public List Constraints { get; private set; } + } + + public class SLGenericTypeDeclarationCollection : List, ICodeElementSet + { + public SLGenericTypeDeclarationCollection() + : base() + { + } + + public IEnumerable ConstraintElements + { + get + { + List constrained = this.Where(decl => decl.Constraints.Count > 0).ToList(); + if (constrained.Count == 0) + yield break; + yield return new SimpleElement(" where ", true); + bool first = true; + foreach (SLGenericTypeDeclaration decl in constrained) + { + foreach (SLGenericConstraint constraint in decl.Constraints) + { + if (!first) + { + yield return new SimpleElement(",", true); + yield return SimpleElement.Spacer; + } + else + { + first = false; + } + yield return constraint; + } + } + } + } + + public IEnumerable Elements + { + get + { + if (this.Count > 0) + { + yield return new SimpleElement("<"); + bool first = true; + foreach (SLGenericTypeDeclaration decl in this) + { + if (!first) + { + yield return new SimpleElement(",", true); + yield return SimpleElement.Spacer; + } + else { + first = false; + } + yield return decl.Name; + } + yield return new SimpleElement(">"); + } + } + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } + + public virtual void Write(ICodeWriter writer, object o) + { + } + + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } + + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs new file mode 100644 index 000000000000..fe0455f0dc5f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLIdentifier : SLBaseExpr { + public SLIdentifier (string name) + { + Name = Exceptions.ThrowOnNull (name, nameof(name)); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Name, false); + } + + public string Name { get; private set; } + + public override string ToString () + { + return Name; + } + + static SLIdentifier anonymousIdentifier = new SLIdentifier ("_"); + public static SLIdentifier Anonymous { get { return anonymousIdentifier; } } + static SLIdentifier superIdentifier = new SLIdentifier ("super"); + public static SLIdentifier Super { get { return superIdentifier; } } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs new file mode 100644 index 000000000000..52dc88e706d6 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLIfElse : CodeElementCollection, ISLStatement { + class IfElem : DelegatedSimpleElement, ISLStatement { + public IfElem (SLBaseExpr condition, bool isCase) + : base () + { + Condition = condition; + IsCase = isCase; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + writer.Write ("if ", false); + if (IsCase) + writer.Write ("case ", true); + Condition.WriteAll (writer); + writer.EndLine (); + } + + public bool IsCase { get; private set; } + public SLBaseExpr Condition { get; private set; } + } + + public SLIfElse (SLBaseExpr condition, SLCodeBlock ifClause, SLCodeBlock elseClause = null, bool isCase = false) + : base () + { + Condition = new IfElem (Exceptions.ThrowOnNull (condition, nameof(condition)), isCase); + IfClause = Exceptions.ThrowOnNull (ifClause, nameof(ifClause)); + ElseClause = elseClause; + + Add (Condition); + Add (IfClause); + if (ElseClause != null && ElseClause.Count > 0) { + Add (new SimpleLineElement ("else", false, true, false)); + Add (ElseClause); + } + } + + public SLIfElse (SLBaseExpr expr, IEnumerable ifClause, IEnumerable elseClause, bool isCase) + : this (expr, new SLCodeBlock (ifClause), + elseClause != null ? new SLCodeBlock (elseClause) : null, isCase) + + { + + } + + public DelegatedSimpleElement Condition { get; private set; } + public SLCodeBlock IfClause { get; private set; } + public SLCodeBlock ElseClause { get; private set; } + + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs new file mode 100644 index 000000000000..9ecf7337e8e8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLImport : SimpleLineElement { + public SLImport (string module, ImportKind kind = ImportKind.None) + : base (string.Format ("import {0}{1}", ToImportKindString (kind), + Exceptions.ThrowOnNull (module, nameof(module))), + false, false, false) + { + Module = module; + } + + public string Module { get; private set; } + + static string ToImportKindString (ImportKind kind) + { + switch (kind) { + case ImportKind.None: + return ""; + case ImportKind.Class: + return "class "; + case ImportKind.Enum: + return "enum "; + case ImportKind.Func: + return "func "; + case ImportKind.Protocol: + return "protocol "; + case ImportKind.Struct: + return "struct "; + case ImportKind.TypeAlias: + return "typealias "; + case ImportKind.Var: + return "var "; + default: + throw new ArgumentOutOfRangeException (nameof(kind)); + } + } + } + + public class SLImportModules : CodeElementCollection { + public SLImportModules () : base () { } + public SLImportModules (params SLImport [] imp) + : this () + { + AddRange (imp); + } + public SLImportModules (params string [] imp) + : this () + { + AddRange (imp.Select (s => new SLImport (s))); + } + + public SLImportModules And (SLImport use) + { + if (OwningModule != null && use.Module == OwningModule) + return this; + if (use.Module == "Self") + return this; + Add (use); + return this; + } + + public SLImportModules And (string package) { return And (new SLImport (package)); } + + public void AddIfNotPresent (string package) + { + SLImport target = new SLImport (package); + if (package == "Self") + return; + + if (package != OwningModule && !this.Exists (imp => imp.Contents == target.Contents)) + Add (target); + } + + public string OwningModule { get; set; } + } + +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs new file mode 100644 index 000000000000..3d9c423a43fc --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLInheritance : CommaListElementCollection { + public SLInheritance (IEnumerable identifiers) + { + if (identifiers != null) + AddRange (identifiers); + } + + public SLInheritance (params string [] identifiers) + : this (identifiers.Select (str => new SLIdentifier (str))) + { + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs new file mode 100644 index 000000000000..21b321d2944c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLInject : SLIdentifier { + // SLInject is a way to more formalize the notion of code that is just plain easier to + // inject as raw text. It's not strictly necessary, but when you see a CSInject, it will make + // it clear that you're doing something not quite on the up and up. + public SLInject (string name) + : base (name) + { + } + + public static explicit operator SLInject (string name) + { + return new SLInject (name); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs new file mode 100644 index 000000000000..4b732c3d6b6b --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLLetMatch : SLBaseExpr, ISLLineable { + public SLLetMatch (SLIdentifier name, ISLExpr expr) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + Expr = expr; + } + + public SLIdentifier Name { get; private set; } + public ISLExpr Expr { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("let ", true); + Name.WriteAll (writer); + if (Expr != null) { + SimpleElement.Spacer.WriteAll (writer); + Expr.WriteAll (writer); + } + } + + public static SLLetMatch LetAs (string name, SLType asType) + { + return new SLLetMatch (new SLIdentifier (name), asType != null ? new SLAsExpr (asType) : null); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs new file mode 100644 index 000000000000..9e9aaf63b33c --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLLine : DelegatedSimpleElement, ISLStatement { + public SLLine (ISLExpr contents, bool addSemicolon = true) + { + Contents = Exceptions.ThrowOnNull (contents, nameof(contents)); + if (!(contents is ISLLineable) && addSemicolon) + throw new ArgumentException ("contents must be ISLineable and require a semicolon", nameof (contents)); + AddSemicolon = addSemicolon; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + Contents.WriteAll (writer); + if (AddSemicolon) + writer.Write (';', false); + writer.EndLine (); + } + + public ISLExpr Contents { get; private set; } + public bool AddSemicolon { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs new file mode 100644 index 000000000000..77dc690b045f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.SwiftLang { + public class SLLineableOperator : SLBaseExpr, ISLLineable { + public SLLineableOperator (SLUnaryExpr unaryExpr) + { + OperatorExpr = Exceptions.ThrowOnNull (unaryExpr, nameof (unaryExpr)); + } + + public SLLineableOperator (SLBinaryExpr binaryExpr) + { + OperatorExpr = Exceptions.ThrowOnNull (binaryExpr, nameof (binaryExpr)); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + OperatorExpr.WriteAll (writer); + } + + public SLBaseExpr OperatorExpr { get; private set; } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs new file mode 100644 index 000000000000..6ad4f802d160 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLNameTypePair : DelegatedSimpleElement { + public SLNameTypePair (SLParameterKind kind, SLIdentifier id, SLType type) + : base () + { + ParameterKind = kind; + Name = id; + TypeAnnotation = type; + } + + public SLNameTypePair (SLIdentifier id, SLType type) + : this (SLParameterKind.None, id, type) + { + } + + public SLNameTypePair(SLParameterKind kind, string id, SLType type) + : this (kind, id != null ? new SLIdentifier(id) : null, type) + { + } + + public SLNameTypePair(string id, SLType type) + : this (SLParameterKind.None, id, type) + { + } + + public SLIdentifier Name { get; private set; } + public SLType TypeAnnotation { get; private set; } + public SLParameterKind ParameterKind { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (Name != null) { + Name.WriteAll (writer); + } + if (TypeAnnotation != null) { + if (Name != null) + writer.Write (": ", true); + if (ParameterKind != SLParameterKind.None) { + writer.Write (ToParameterKindString (ParameterKind), false); + writer.Write (' ', false); + } + TypeAnnotation.WriteAll (writer); + } + } + + internal static string ToParameterKindString (SLParameterKind kind) + { + switch (kind) { + case SLParameterKind.None: + return ""; + case SLParameterKind.Var: + return "var"; + case SLParameterKind.InOut: + return "inout"; + default: + throw new ArgumentOutOfRangeException (nameof(kind), "unexpected value " + kind.ToString ()); + } + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs new file mode 100644 index 000000000000..afb678456892 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLNamedClosureCall : SLBaseExpr, ISLLineable { + + public SLNamedClosureCall (SLBaseExpr closureExpr, CommaListElementCollection paramList) + { + Closure = Exceptions.ThrowOnNull (closureExpr, "closure"); + Parameters = paramList ?? new CommaListElementCollection (); + } + + public SLBaseExpr Closure { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Closure.WriteAll (writer); + writer.Write ("(", false); + Parameters.WriteAll (writer); + writer.Write (")", false); + } + + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs new file mode 100644 index 000000000000..4e4ad7f5fabb --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.SwiftLang { + + public class SLUnnamedParameter : DelegatedSimpleElement { + public SLUnnamedParameter (SLType type, SLParameterKind kind = SLParameterKind.None) + { + ParameterKind = kind; + TypeAnnotation = Exceptions.ThrowOnNull (type, nameof (type)); + } + public SLParameterKind ParameterKind { get; private set; } + public SLType TypeAnnotation { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (ParameterKind != SLParameterKind.None) { + writer.Write (SLNameTypePair.ToParameterKindString (ParameterKind), false); + writer.Write (' ', false); + } + TypeAnnotation.WriteAll (writer); + } + } + + + public class SLParameter : SLUnnamedParameter { + public SLParameter (SLIdentifier publicName, SLIdentifier privateName, SLType type, SLParameterKind kind = SLParameterKind.None) + : base (type, kind) + { + PublicName = publicName; + PrivateName = Exceptions.ThrowOnNull (privateName, nameof (privateName)); + } + + public SLParameter (string publicName, string privateName, SLType type, SLParameterKind kind = SLParameterKind.None) + : this (publicName != null ? new SLIdentifier (publicName) : null, new SLIdentifier (privateName), type, kind) + { + } + + public SLParameter (SLIdentifier name, SLType type, SLParameterKind kind = SLParameterKind.None) + : this (name, name, type, kind) + { + + } + + public SLParameter (string name, SLType type, SLParameterKind kind = SLParameterKind.None) + : this (name, name, type, kind) + { + + } + + public SLIdentifier PublicName { get; private set; } + public SLIdentifier PrivateName { get; private set; } + public bool PublicNameIsOptional { get { return PublicName == null || String.IsNullOrEmpty (PublicName.Name); } } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (PublicNameIsOptional) { + writer.Write ("_ ", true); + PrivateName.WriteAll (writer); + } else if (PublicName.Name == PrivateName.Name) { + PrivateName.WriteAll (writer); + } else { + PublicName.WriteAll (writer); + writer.Write (" ", true); + PrivateName.WriteAll (writer); + } + writer.Write (": ", true); + base.LLWrite (writer, o); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs new file mode 100644 index 000000000000..d0d0494892e9 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLParameterList : DelegatedSimpleElement { + public SLParameterList () + { + Parameters = new List (); + } + + public SLParameterList (IEnumerable parameters) + : this () + { + Parameters.AddRange (parameters); + } + + public SLParameterList (params SLParameter[] parameters) + : this () + { + Parameters.AddRange (parameters); + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('(', true); + for (int i = 0; i < Parameters.Count; i++) { + if (i > 0) { + writer.Write (", ", true); + } + Parameters [i].WriteAll (writer); + } + writer.Write (')', true); + } + + public List Parameters { get; private set; } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs new file mode 100644 index 000000000000..58ca3fdd70d0 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.SwiftLang { + public class SLParenthesisExpression : SLBaseExpr { + public SLParenthesisExpression (SLBaseExpr within) + { + Within = Exceptions.ThrowOnNull (within, "within"); + } + + public SLBaseExpr Within { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('(', true); + Within.WriteAll (writer); + writer.Write (')', true); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs new file mode 100644 index 000000000000..70735f8f2d0f --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + public class SLPostBang : SLBaseExpr, ISLLineable { + public SLPostBang (SLBaseExpr expr, bool addParens) + { + Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); + AddParens = addParens; + } + + public SLBaseExpr Expr { get; private set; } + public bool AddParens { get; set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (AddParens) + writer.Write ('(', false); + Expr.WriteAll (writer); + if (AddParens) + writer.Write (')', false); + writer.Write ('!', false); + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs new file mode 100644 index 000000000000..8be3e538c387 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLProperty : CodeElementCollection { + public SLProperty (Visibility vis, FunctionKind funcKind, SLType type, SLIdentifier name, + SLCodeBlock getter, SLCodeBlock setter, bool isAsync = false) + { + Visibility = vis; + Type = Exceptions.ThrowOnNull (type, nameof(type)); + Name = Exceptions.ThrowOnNull (name, nameof(name)); + GetterBody = Exceptions.ThrowOnNull (getter, nameof(getter)); + SetterBody = setter; + IsAsync = isAsync; + + List elems = new List (); + if (vis != Visibility.None) + elems.Add (SLFunc.ToVisibilityString (vis) + " "); + if ((funcKind & FunctionKind.Final) != 0) + elems.Add ("final "); + if ((funcKind & FunctionKind.Required) != 0) + elems.Add ("required "); + if ((funcKind & FunctionKind.Override) != 0) + elems.Add ("override "); + if ((funcKind & FunctionKind.Static) != 0) + elems.Add ("static "); + if ((funcKind & FunctionKind.Class) != 0) + elems.Add ("class "); + + elems.Add ("var "); + AddRange (elems.Select ((el, i) => i == 0 ? (ICodeElement)new SimpleLineElement (el, false, true, true) : new SimpleElement (el))); + Add (Name); + Add (new SimpleElement (":")); + Add (SimpleElement.Spacer); + Add (Type); + SLCodeBlock block = new SLCodeBlock (null); + block.Add (new SimpleElement ("get")); + block.Add (SimpleElement.Spacer); + if (isAsync) { + block.Add (new SimpleElement ("async")); + block.Add (SimpleElement.Spacer); + } + block.Add (GetterBody); + if (SetterBody != null) { + block.Add (new SimpleElement ("set")); + block.Add (SimpleElement.Spacer); + block.Add (SetterBody); + } + Add (block); + } + public Visibility Visibility { get; private set; } + public SLType Type { get; private set; } + public SLIdentifier Name { get; private set; } + public SLTupleType Parameters { get; private set; } + public SLCodeBlock GetterBody { get; private set; } + public SLCodeBlock SetterBody { get; private set; } + public bool IsAsync { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs new file mode 100644 index 000000000000..45020c6fdf57 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLReturn : DelegatedSimpleElement, ISLExpr, ISLLineable { + public SLReturn (ISLExpr expr) + { + Value = expr; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("return ", true); + if (Value != null) + Value.WriteAll (writer); + } + + public ISLExpr Value { get; private set; } + + public static SLLine ReturnLine (ISLExpr expr) + { + return new SLLine (new SLReturn (expr)); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs new file mode 100644 index 000000000000..9cdca1537562 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Linq; + +namespace SyntaxDynamo.SwiftLang { + public class SLSubscript : CodeElementCollection { + // VIS subscript(parms) -> type { + // get { + // } + // set { // newValue:type is implicit + // } + // } + // get is mandatory, set is optional + + public SLSubscript (Visibility vis, FunctionKind funcKind, SLType type, + SLParameterList parms, SLCodeBlock getter, SLCodeBlock setter, + bool isAsync = false) + { + IsAsync = isAsync; + Visibility = vis; + Type = Exceptions.ThrowOnNull (type, nameof(type)); + Parameters = Exceptions.ThrowOnNull (parms, nameof(parms)); + GetterBody = Exceptions.ThrowOnNull (getter, nameof(getter)); + SetterBody = setter; // can be null + + List elems = new List (); + if (vis != Visibility.None) + elems.Add (SLFunc.ToVisibilityString (vis) + " "); + if ((funcKind & FunctionKind.Final) != 0) + elems.Add ("final "); + if ((funcKind & FunctionKind.Override) != 0) + elems.Add ("override "); + if ((funcKind & FunctionKind.Required) != 0) + elems.Add ("required "); + if ((funcKind & FunctionKind.Static) != 0) + elems.Add ("static "); + if ((funcKind & FunctionKind.Class) != 0) + elems.Add ("class "); + elems.Add ("subscript "); + + AddRange (elems.Select ((el, i) => i == 0 ? (ICodeElement)new SimpleLineElement (el, false, true, true) : new SimpleElement (el))); + Add (Parameters); + Add (SimpleElement.Spacer); + Add (new SimpleElement ("->")); + Add (SimpleElement.Spacer); + Add (Type); + SLCodeBlock block = new SLCodeBlock (null); + block.Add (new SimpleElement ("get")); + block.Add (SimpleElement.Spacer); + if (isAsync) { + block.Add (new SimpleElement ("async")); + block.Add (SimpleElement.Spacer); + } + block.Add (GetterBody); + if (SetterBody != null) { + block.Add (new SimpleElement ("set")); + block.Add (SimpleElement.Spacer); + block.Add (SetterBody); + } + Add (block); + } + + public Visibility Visibility { get; private set; } + public SLType Type { get; private set; } + public SLParameterList Parameters { get; private set; } + public SLCodeBlock GetterBody { get; private set; } + public SLCodeBlock SetterBody { get; private set; } + public bool IsAsync { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs new file mode 100644 index 000000000000..951344f167a4 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLSubscriptExpr : SLBaseExpr { + public SLSubscriptExpr (SLIdentifier ident, CommaListElementCollection paramList) + { + Name = Exceptions.ThrowOnNull (ident, nameof(ident)); + Parameters = Exceptions.ThrowOnNull (paramList, nameof(paramList)); + } + + public SLSubscriptExpr (string identifier, params SLBaseExpr [] parameters) + : this (new SLIdentifier (identifier), new CommaListElementCollection (parameters)) + { + } + + public SLSubscriptExpr (SLIdentifier identifier, IEnumerable parameters) + : this (identifier, new CommaListElementCollection (parameters)) + { + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Name.WriteAll (writer); + writer.Write ("[", false); + Parameters.WriteAll (writer); + writer.Write ("]", false); + } + + public SLIdentifier Name { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs new file mode 100644 index 000000000000..ef6dea408660 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLCase : DelegatedSimpleElement, ISLStatement { + public SLCase (ICodeElement caseExpr, ICodeElement actions) + { + CaseExpr = caseExpr; + Actions = actions; + } + + public ICodeElement CaseExpr { get; private set; } + public ICodeElement Actions { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.BeginNewLine (true); + if (CaseExpr != null) { + writer.Write ("case ", true); + CaseExpr.WriteAll (writer); + } else { + writer.Write ("default", true); + } + writer.Write (" : ", true); + if (Actions != null) { + if (Actions is ICodeElementSet) { + writer.EndLine (); + writer.Indent (); + writer.BeginNewLine (true); + } + Actions.WriteAll (writer); + writer.EndLine (); + if (Actions is ICodeElementSet) { + writer.Exdent (); + } + } + } + } + + public class SLSwitch : ICodeElementSet, ISLStatement, ISLLineable { + public SLSwitch (ISLExpr switchOn, IEnumerable cases) + { + Cases = new List (); + if (cases != null) { + Cases.AddRange (cases); + } + SwitchOn = switchOn; + } + + public ISLExpr SwitchOn { get; set; } + public List Cases { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite (ICodeWriter writer) + { + writer.BeginNewLine (true); + OnBeginWrite (new WriteEventArgs (writer)); + return null; + } + + protected virtual void OnBeginWrite (WriteEventArgs args) + { + Begin (this, args); + } + + public virtual void Write (ICodeWriter writer, object o) + { + } + + public virtual void EndWrite (ICodeWriter writer, object o) + { + OnEndWrite (new WriteEventArgs (writer)); + } + + protected virtual void OnEndWrite (WriteEventArgs args) + { + End.FireInReverse (this, args); + } + + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements { + get { + yield return new SimpleElement ("switch"); + yield return SimpleElement.Spacer; + yield return SwitchOn; + yield return SimpleElement.Spacer; + SLCodeBlock caseBlock = new SLCodeBlock (Cases); + yield return caseBlock; + } + } + + #endregion + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs new file mode 100644 index 000000000000..bc4ebcef0544 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang +{ + public class SLThrow : SLBaseExpr, ISLStatement, ISLLineable + { + public SLThrow (SLBaseExpr expr) + { + Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); + } + + public SLBaseExpr Expr { get; private set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("throw ", true); + Expr.WriteAll (writer); + } + + #endregion + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs new file mode 100644 index 000000000000..93de5f989d88 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo.SwiftLang { + + public class SLTry : SLBaseExpr, ISLLineable { + public SLTry (SLBaseExpr expr) + : this (expr, false) + { + } + + public SLTry (SLBaseExpr expr, bool isTryBang) + { + Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); + IsTryBang = isTryBang; + } + + public SLBaseExpr Expr { get; private set; } + public bool IsTryBang { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + string bang = IsTryBang ? "!" : ""; + writer.Write ($"try{bang} ", true); + Expr.WriteAll (writer); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs new file mode 100644 index 000000000000..9fa7b7b11cf0 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace SyntaxDynamo.SwiftLang { + public class SLTupleExpr : SLBaseExpr { + public SLTupleExpr (IEnumerable values) + { + Values = new List (); + Values.AddRange (Exceptions.ThrowOnNull (values, nameof(values))); + } + + public List Values { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('(', true); + for (int i = 0; i < Values.Count; i++) { + if (i > 0) { + writer.Write (", ", true); + } + Values [i].WriteAll (writer); + } + writer.Write (')', true); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs new file mode 100644 index 000000000000..fdf113757ed8 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; + +namespace SyntaxDynamo.SwiftLang { + public abstract class SLType : DelegatedSimpleElement { + public SLType (bool isAny = false) + { + IsAny = isAny; + } + public override string ToString () => CodeWriter.WriteToString (this); + public bool IsAny { get; set; } + protected string AnyString => IsAny ? "any " : ""; + } + + public class SLCompoundType : SLType { + public SLCompoundType(SLType parent, SLType child, bool isAny = false) + : base (isAny) + { + Parent = Exceptions.ThrowOnNull (parent, nameof (parent)); + Child = Exceptions.ThrowOnNull (child, nameof (child)); + } + public SLType Parent { get; private set; } + public SLType Child { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write (AnyString, true); + Parent.Write (writer, o); + writer.Write ('.', false); + Child.Write (writer, o); + } + } + + public class SLSimpleType : SLType { + public SLSimpleType (string name, bool isAny = false) + : base (isAny) + { + Name = Exceptions.ThrowOnNull (name, nameof(name)); + } + + public string Name { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (AnyString, true); + writer.Write (Name, false); + } + + static SLType + tBool = new SLSimpleType ("Bool"), + tChar = new SLSimpleType ("Character"), + tInt8 = new SLSimpleType ("Int8"), + tInt16 = new SLSimpleType ("Int16"), + tInt32 = new SLSimpleType ("Int32"), + tInt64 = new SLSimpleType ("Int64"), + tInt = new SLSimpleType ("Int"), + tUint8 = new SLSimpleType ("UInt8"), + tUint16 = new SLSimpleType ("UInt16"), + tUint32 = new SLSimpleType ("UInt32"), + tUint64 = new SLSimpleType ("UInt64"), + tUint = new SLSimpleType ("UInt"), + tFloat = new SLSimpleType ("Float"), + tDouble = new SLSimpleType ("Double"), + tString = new SLSimpleType ("String"), + tVoid = new SLSimpleType ("Void"), + tOpaquePointer = new SLSimpleType("OpaquePointer") + ; + + public static SLType Bool { get { return tBool; } } + public static SLType Char { get { return tChar; } } + public static SLType Int { get { return tInt; } } + public static SLType Int8 { get { return tInt8; } } + public static SLType Int16 { get { return tInt16; } } + public static SLType Int32 { get { return tInt32; } } + public static SLType Int64 { get { return tInt64; } } + public static SLType UInt { get { return tUint; } } + public static SLType UInt8 { get { return tUint8; } } + public static SLType UInt16 { get { return tUint16; } } + public static SLType UInt32 { get { return tUint32; } } + public static SLType UInt64 { get { return tUint64; } } + public static SLType Float { get { return tFloat; } } + public static SLType Double { get { return tDouble; } } + public static SLType String { get { return tString; } } + public static SLType Void { get { return tVoid; } } + public static SLType OpaquePointer { get { return tOpaquePointer; } } + + } + + public class SLProtocolListType : SLType { + public SLProtocolListType () + { + Protocols = new List (); + } + + public SLProtocolListType (IEnumerable types) + : this () + { + Exceptions.ThrowOnNull (types, nameof (types)); + Protocols.AddRange (types); + } + + public List Protocols { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (Protocols.Count < 2) + throw new Exception ("Protocol list types must have at least two elements"); + Protocols [0].WriteAll (writer); + for (int i = 1; i < Protocols.Count; i++) { + writer.Write (" & ", true); + Protocols [i].WriteAll (writer); + } + } + } + + public class SLOptionalType : SLType { + public SLOptionalType (SLType opt) + : base (false) + { + Optional = Exceptions.ThrowOnNull (opt, nameof (opt)); + } + + public SLType Optional { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + bool containsFuncType = Optional is SLFuncType; + if (containsFuncType) + writer.Write ('(', true); + Optional.WriteAll (writer); + if (containsFuncType) + writer.Write (')', true); + writer.Write ('?', true); + } + } + + public class SLBoundGenericType : SLType { + public SLBoundGenericType (string name, IEnumerable boundTypes) + : base (false) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + BoundTypes = new List (); + if (boundTypes != null) + BoundTypes.AddRange (boundTypes); + } + + public SLBoundGenericType (string name, string singleBoundType) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + BoundTypes = new List (); + BoundTypes.Add (new SLSimpleType (singleBoundType)); + } + + public SLBoundGenericType (string name, SLType singleBoundType) + : this (name, new SLType [] { singleBoundType }) + { + } + + public string Name { get; private set; } + public List BoundTypes { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write (Name, false); + writer.Write ('<', true); + for (int i = 0; i < BoundTypes.Count; i++) { + if (i > 0) + writer.Write (", ", true); + BoundTypes [i].WriteAll (writer); + } + writer.Write ('>', true); + } + + } + + public class SLArrayType : SLType { + public SLArrayType (SLType elementType) + : base (false) + { + ElementType = Exceptions.ThrowOnNull (elementType, nameof (elementType)); + } + + public SLType ElementType { get; private set; } + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('[', true); + ElementType.WriteAll (writer); + writer.Write (']', true); + } + + } + + public class SLTupleType : SLType { + public SLTupleType (List pairs) + : base (false) + { + Elements = new List (); + if (pairs != null) + Elements.AddRange (pairs); + } + + public SLTupleType (params SLNameTypePair [] pairs) + : base (false) + { + Elements = new List (); + Elements.AddRange (pairs); + } + + public List Elements { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ('(', true); + for (int i = 0; i < Elements.Count; i++) { + if (i > 0) { + writer.Write (", ", true); + } + Elements [i].WriteAll (writer); + } + writer.Write (')', true); + } + + public static SLTupleType Of (SLIdentifier id, SLType type) + { + return new SLTupleType (new SLNameTypePair [] { new SLNameTypePair (id, type) }); + } + + public static SLTupleType Of (string id, SLType type) + { + return Of (new SLIdentifier (id), type); + } + } + + + public class SLFuncType : SLType { + public SLFuncType (SLType argType, SLType retType, bool hasThrows = false, bool isAsync = false) + : this (retType, ConvertSLTypeToParameters (argType), hasThrows, isAsync) + { + } + + public SLFuncType (SLType retType, IEnumerable parameters, + bool hasThrows = false, bool isAsync = false) + : base (false) + { + Exceptions.ThrowOnNull (parameters, nameof (parameters)); + Attributes = new List (); + Parameters = new List (); + if (parameters != null) + Parameters.AddRange (parameters); + ReturnType = Exceptions.ThrowOnNull (retType, nameof (retType)); + Throws = hasThrows; + IsAsync = isAsync; + } + + public List Parameters { get; private set; } + public SLType ReturnType { get; private set; } + public List Attributes { get; private set; } + public bool Throws { get; private set; } + public bool IsAsync { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + foreach (var attr in Attributes) { + attr.WriteAll (writer); + writer.Write (' ', true); + } + writer.Write ('(', true); + for (int i = 0; i < Parameters.Count; i++) { + if (i > 0) + writer.Write (", ", true); + Parameters [i].WriteAll (writer); + } + writer.Write (") ", true); + if (IsAsync) { + writer.Write ("async ", true); + } + if (Throws) { + writer.Write ("throws", true); + } + writer.Write ("-> ", true); + ReturnType.WriteAll (writer); + } + + static IEnumerable ConvertSLTypeToParameters (SLType type) + { + if (type is SLTupleType tuple) { + foreach (var elem in tuple.Elements) { + yield return new SLUnnamedParameter (elem.TypeAnnotation, elem.ParameterKind); + } + } else { + yield return new SLUnnamedParameter (type); + } + } + } + + public class SLDictionaryType : SLType { + public SLDictionaryType (SLType keyType, SLType valueType) + : base (false) + { + KeyType = Exceptions.ThrowOnNull (keyType, nameof (keyType)); + ValueType = Exceptions.ThrowOnNull (valueType, nameof (valueType)); + } + + public SLType KeyType { get; private set; } + public SLType ValueType { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + writer.Write ("[", true); + KeyType.WriteAll (writer); + writer.Write (" : ", true); + ValueType.WriteAll (writer); + writer.Write ("]", true); + } + } + + + public class SLGenericReferenceType : SLType { + public SLGenericReferenceType (int depth, int index, bool isMetatype = false, List associatedTypePath = null) + : base (false) + { + if (depth < 0) + throw new ArgumentOutOfRangeException (nameof (depth)); + if (index < 0) + throw new ArgumentOutOfRangeException (nameof (index)); + Depth = depth; + Index = index; + IsMetatype = isMetatype; + AssociatedTypePath = associatedTypePath; + } + + public int Depth { get; private set; } + public int Index { get; private set; } + public bool IsMetatype { get; private set; } + public Func ReferenceNamer { get; set; } + public List AssociatedTypePath { get; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + var suffix = IsMetatype ? ".Type" : ""; + string name; + if (AssociatedTypePath != null && AssociatedTypePath.Any ()) { + name = $"{Name}.{AssociatedTypePath.First ()}{suffix}"; + } else { + name = $"{Name}{suffix}"; + } + writer.Write (name, true); + } + + public string Name { + get { + Func namer = ReferenceNamer ?? DefaultNamer; + return namer (Depth, Index); + } + } + + const string kNames = "TUVWABCDEFGHIJKLMN"; + + public static string DefaultNamer (int depth, int index) + { + if (depth < 0 || depth >= kNames.Length) + throw new ArgumentOutOfRangeException (nameof (depth)); + if (index < 0) + throw new ArgumentOutOfRangeException (nameof (index)); + return String.Format ("{0}{1}", kNames [depth], index); + } + } + + public class SLVariadicType : SLType { + public SLVariadicType (SLType repeatingType) + : base (repeatingType.IsAny) + { + RepeatingType = Exceptions.ThrowOnNull (repeatingType, nameof (repeatingType)); + } + + public SLType RepeatingType { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + RepeatingType.WriteAll (writer); + writer.Write (" ...", true); + } + } +} + diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs new file mode 100644 index 000000000000..31eaadbd7712 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SyntaxDynamo.SwiftLang { + public class SLUnaryExpr : SLBaseExpr { + public SLUnaryExpr (string op, ISLExpr expr, bool isPrefix) + { + Operation = Exceptions.ThrowOnNull (op, nameof (op)); + Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); + IsPrefix = isPrefix; + } + + protected override void LLWrite (ICodeWriter writer, object o) + { + if (IsPrefix) { + writer.Write (' ', false); + writer.Write (Operation, false); + Expr.WriteAll (writer); + } else { + Expr.WriteAll (writer); + writer.Write (Operation, false); + writer.Write (' ', false); + } + } + + public bool IsPrefix { get; private set; } + public string Operation { get; private set; } + public ISLExpr Expr { get; private set; } + + public static SLUnaryExpr Await (ISLExpr expr) + { + return new SLUnaryExpr ("await ", expr, true); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs new file mode 100644 index 000000000000..6eaba12e94aa --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SyntaxDynamo.SwiftLang { + public class SLVariadicExpr : SLBaseExpr { + public SLVariadicExpr (DelegatedCommaListElemCollection paramList) + { + Parameters = paramList ?? new DelegatedCommaListElemCollection (WriteElement); + } + + public SLVariadicExpr (params SLBaseExpr [] paramList) + : this (new DelegatedCommaListElemCollection (WriteElement, paramList)) + { + } + + public static void WriteElement (ICodeWriter writer, int i, SLBaseExpr arg) + { + arg.WriteAll (writer); + } + + public DelegatedCommaListElemCollection Parameters { get; private set; } + + protected override void LLWrite (ICodeWriter writer, object o) + { + Parameters.WriteAll (writer); + } + } +} diff --git a/src/SyntaxDynamo/SyntaxDynamo.csproj b/src/SyntaxDynamo/SyntaxDynamo.csproj new file mode 100644 index 000000000000..9cce3e52d3c7 --- /dev/null +++ b/src/SyntaxDynamo/SyntaxDynamo.csproj @@ -0,0 +1,12 @@ + + + Library + net7.0 + enable + disable + true + + + + + diff --git a/src/SyntaxDynamo/WriteEventArgs.cs b/src/SyntaxDynamo/WriteEventArgs.cs new file mode 100644 index 000000000000..4b501a14df6f --- /dev/null +++ b/src/SyntaxDynamo/WriteEventArgs.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SyntaxDynamo { + public class WriteEventArgs : EventArgs { + public WriteEventArgs (ICodeWriter writer) + { + if (writer == null) + throw new ArgumentNullException (nameof(writer)); + Writer = writer; + } + + public ICodeWriter Writer { get; private set; } + } +} + From 8a1a04f645b4ee42f0aa882e85cd2e3b94816627 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 16:31:10 +0100 Subject: [PATCH 03/37] Add SwiftReflector project Introduces type mapping and API reflection of the tooling. Key components: - Inventory: Collects mangled names and generates entry points mapping. - Reflector and SwiftXmlReflection: Aggregates Swift public API. - TopLevelFunctionCompiler: Provides tools to generate C# methods, properties, and P/Invoke definitions. - TypeMapping: Facilitates Swift to C# type conversion, maintaining a type database. - BindingsCompiler: Handles generating the C# bindings onto the types from the Swift module. --- src/SwiftReflector/BindingsCompiler.cs | 270 + src/SwiftReflector/CSKeywords.cs | 44 + .../Demangling/ContextAttribute.cs | 9 + src/SwiftReflector/Demangling/Decomposer.cs | 1175 ++ src/SwiftReflector/Demangling/Enums.cs | 370 + src/SwiftReflector/Demangling/MatchRule.cs | 93 + src/SwiftReflector/Demangling/Node.cs | 245 + src/SwiftReflector/Demangling/RuleRunner.cs | 23 + .../Demangling/Swift4Demangler.cs | 1814 +++ .../Demangling/Swift4NodeToTLDefinition.cs | 1887 +++ .../Demangling/Swift5Demangler.cs | 2960 ++++ .../Demangling/Swift5NodeToTLDefinition.cs | 2065 +++ src/SwiftReflector/Demangling/TLDefinition.cs | 269 + src/SwiftReflector/Enums.cs | 182 + src/SwiftReflector/ErrorHandling.cs | 104 + .../ExceptionTools/ErrorHelper.cs | 177 + .../ExceptionTools/RuntimeException.cs | 58 + src/SwiftReflector/Extensions.cs | 238 + src/SwiftReflector/IOUtils/ExecAndCollect.cs | 115 + src/SwiftReflector/IOUtils/IFileProvider.cs | 10 + .../IOUtils/IXElementConvertible.cs | 11 + src/SwiftReflector/IOUtils/OffsetStream.cs | 154 + src/SwiftReflector/Inventory/ClassContents.cs | 307 + .../Inventory/ClassInventory.cs | 65 + .../Inventory/FunctionInventory.cs | 111 + src/SwiftReflector/Inventory/Inventory.cs | 43 + .../Inventory/ModuleContents.cs | 92 + .../Inventory/ModuleInventory.cs | 164 + .../Inventory/OverloadInventory.cs | 42 + .../Inventory/PropertyContents.cs | 189 + .../Inventory/PropertyInventory.cs | 54 + .../Inventory/ProtocolContents.cs | 85 + .../Inventory/ProtocolInventory.cs | 31 + .../Inventory/VariableContents.cs | 23 + .../Inventory/VariableInventory.cs | 51 + .../Inventory/WitnessInventory.cs | 67 + src/SwiftReflector/MachOHawley.cs | 1339 ++ src/SwiftReflector/MarshalEngine.cs | 278 + src/SwiftReflector/PunyCode.cs | 161 + src/SwiftReflector/ReflectorError.cs | 58 + src/SwiftReflector/StringSlice.cs | 216 + src/SwiftReflector/SwiftClassName.cs | 102 + .../SwiftInterfaceBaseListener.cs | 2131 +++ .../GeneratedParser/SwiftInterfaceLexer.cs | 1395 ++ .../GeneratedParser/SwiftInterfaceListener.cs | 1771 +++ .../GeneratedParser/SwiftInterfaceParser.cs | 13120 ++++++++++++++++ .../SwiftInterfaceReflector/IModuleLoader.cs | 27 + .../ObjCSelectorFactory.cs | 317 + .../SwiftInterfaceReflector/ParseException.cs | 18 + .../SwiftInterfaceReflector.cs | 2330 +++ .../SyntaxDesugaringParser.cs | 120 + src/SwiftReflector/SwiftName.cs | 44 + src/SwiftReflector/SwiftReflector.csproj | 15 + src/SwiftReflector/SwiftType.cs | 1118 ++ .../AssociatedTypeDeclaration.cs | 68 + .../AttributeDeclaration.cs | 149 + .../SwiftXmlReflection/BaseConstraint.cs | 190 + .../SwiftXmlReflection/BaseDeclaration.cs | 561 + .../SwiftXmlReflection/ClassDeclaration.cs | 30 + .../SwiftXmlReflection/EnumDeclaration.cs | 125 + .../SwiftXmlReflection/EnumElement.cs | 56 + .../SwiftXmlReflection/Enums.cs | 82 + .../ExtensionDeclaration.cs | 89 + .../SwiftXmlReflection/ExtensionMethods.cs | 46 + .../SwiftXmlReflection/FunctionDeclaration.cs | 471 + .../SwiftXmlReflection/GenericDeclaration.cs | 127 + .../GenericDeclarationCollection.cs | 44 + .../GenericReferenceAssociatedTypeProtocol.cs | 9 + .../SwiftXmlReflection/Inheritance.cs | 79 + .../SwiftXmlReflection/Member.cs | 49 + .../SwiftXmlReflection/ModuleDeclaration.cs | 189 + .../SwiftXmlReflection/OperatorDeclaration.cs | 50 + .../SwiftXmlReflection/ParameterItem.cs | 215 + .../SwiftXmlReflection/PropertyDeclaration.cs | 175 + .../SwiftXmlReflection/ProtocolDeclaration.cs | 71 + .../SwiftXmlReflection/Reflector.cs | 118 + .../SwiftXmlReflection/ShamDeclaration.cs | 44 + .../SwiftXmlReflection/StructDeclaration.cs | 17 + .../SubscriptDeclaration.cs | 20 + .../TypeAliasDeclaration.cs | 92 + .../SwiftXmlReflection/TypeAliasFolder.cs | 259 + .../SwiftXmlReflection/TypeDeclaration.cs | 538 + .../SwiftXmlReflection/TypeSpec.cs | 807 + .../SwiftXmlReflection/TypeSpecParser.cs | 302 + .../SwiftXmlReflection/TypeSpecToken.cs | 61 + .../SwiftXmlReflection/TypeSpecTokenizer.cs | 200 + .../TopLevelFunctionCompiler.cs | 335 + src/SwiftReflector/TypeMapping/Entity.cs | 81 + .../TypeMapping/ModuleDatabase.cs | 19 + src/SwiftReflector/TypeMapping/NetParam.cs | 18 + .../TypeMapping/NetTypeBundle.cs | 219 + .../TypeMapping/SwiftTypeToSLType.cs | 169 + .../TypeMapping/TypeDatabase.cs | 471 + src/SwiftReflector/TypeMapping/TypeMapper.cs | 1135 ++ .../TypeMapping/TypeSpecToSLType.cs | 393 + src/SwiftReflector/UnicodeMapper.cs | 121 + src/SwiftReflector/ValueWitnessTable.cs | 128 + src/SwiftReflector/XmlToTLFunctionMapper.cs | 489 + 98 files changed, 47068 insertions(+) create mode 100644 src/SwiftReflector/BindingsCompiler.cs create mode 100644 src/SwiftReflector/CSKeywords.cs create mode 100644 src/SwiftReflector/Demangling/ContextAttribute.cs create mode 100644 src/SwiftReflector/Demangling/Decomposer.cs create mode 100644 src/SwiftReflector/Demangling/Enums.cs create mode 100644 src/SwiftReflector/Demangling/MatchRule.cs create mode 100644 src/SwiftReflector/Demangling/Node.cs create mode 100644 src/SwiftReflector/Demangling/RuleRunner.cs create mode 100644 src/SwiftReflector/Demangling/Swift4Demangler.cs create mode 100644 src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs create mode 100644 src/SwiftReflector/Demangling/Swift5Demangler.cs create mode 100644 src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs create mode 100644 src/SwiftReflector/Demangling/TLDefinition.cs create mode 100644 src/SwiftReflector/Enums.cs create mode 100644 src/SwiftReflector/ErrorHandling.cs create mode 100644 src/SwiftReflector/ExceptionTools/ErrorHelper.cs create mode 100644 src/SwiftReflector/ExceptionTools/RuntimeException.cs create mode 100644 src/SwiftReflector/Extensions.cs create mode 100644 src/SwiftReflector/IOUtils/ExecAndCollect.cs create mode 100644 src/SwiftReflector/IOUtils/IFileProvider.cs create mode 100644 src/SwiftReflector/IOUtils/IXElementConvertible.cs create mode 100644 src/SwiftReflector/IOUtils/OffsetStream.cs create mode 100644 src/SwiftReflector/Inventory/ClassContents.cs create mode 100644 src/SwiftReflector/Inventory/ClassInventory.cs create mode 100644 src/SwiftReflector/Inventory/FunctionInventory.cs create mode 100644 src/SwiftReflector/Inventory/Inventory.cs create mode 100644 src/SwiftReflector/Inventory/ModuleContents.cs create mode 100644 src/SwiftReflector/Inventory/ModuleInventory.cs create mode 100644 src/SwiftReflector/Inventory/OverloadInventory.cs create mode 100644 src/SwiftReflector/Inventory/PropertyContents.cs create mode 100644 src/SwiftReflector/Inventory/PropertyInventory.cs create mode 100644 src/SwiftReflector/Inventory/ProtocolContents.cs create mode 100644 src/SwiftReflector/Inventory/ProtocolInventory.cs create mode 100644 src/SwiftReflector/Inventory/VariableContents.cs create mode 100644 src/SwiftReflector/Inventory/VariableInventory.cs create mode 100644 src/SwiftReflector/Inventory/WitnessInventory.cs create mode 100644 src/SwiftReflector/MachOHawley.cs create mode 100644 src/SwiftReflector/MarshalEngine.cs create mode 100644 src/SwiftReflector/PunyCode.cs create mode 100644 src/SwiftReflector/ReflectorError.cs create mode 100644 src/SwiftReflector/StringSlice.cs create mode 100644 src/SwiftReflector/SwiftClassName.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs create mode 100644 src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs create mode 100644 src/SwiftReflector/SwiftName.cs create mode 100644 src/SwiftReflector/SwiftReflector.csproj create mode 100644 src/SwiftReflector/SwiftType.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/EnumElement.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/Enums.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/Inheritance.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/Member.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/Reflector.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs create mode 100644 src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs create mode 100644 src/SwiftReflector/TopLevelFunctionCompiler.cs create mode 100644 src/SwiftReflector/TypeMapping/Entity.cs create mode 100644 src/SwiftReflector/TypeMapping/ModuleDatabase.cs create mode 100644 src/SwiftReflector/TypeMapping/NetParam.cs create mode 100644 src/SwiftReflector/TypeMapping/NetTypeBundle.cs create mode 100644 src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs create mode 100644 src/SwiftReflector/TypeMapping/TypeDatabase.cs create mode 100644 src/SwiftReflector/TypeMapping/TypeMapper.cs create mode 100644 src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs create mode 100644 src/SwiftReflector/UnicodeMapper.cs create mode 100644 src/SwiftReflector/ValueWitnessTable.cs create mode 100644 src/SwiftReflector/XmlToTLFunctionMapper.cs diff --git a/src/SwiftReflector/BindingsCompiler.cs b/src/SwiftReflector/BindingsCompiler.cs new file mode 100644 index 000000000000..c29dfcfa85fa --- /dev/null +++ b/src/SwiftReflector/BindingsCompiler.cs @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Xml; +using System.Xml.Linq; + +using SyntaxDynamo; +using SyntaxDynamo.CSLang; +using SwiftRuntimeLibrary; +using System.Threading.Tasks; +using System.Runtime.InteropServices; + +using SwiftReflector.Inventory; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.TypeMapping; + +using SwiftReflector.Demangling; +using SwiftReflector.ExceptionTools; +using SwiftReflector.SwiftInterfaceReflector; + +namespace SwiftReflector { + public class BindingsCompiler { + UnicodeMapper UnicodeMapper; + TypeMapper TypeMapper; + TopLevelFunctionCompiler TLFCompiler; + SwiftInterfaceReflector.SwiftInterfaceReflector Reflector; + + public BindingsCompiler () + { + UnicodeMapper = new UnicodeMapper (); + TypeMapper = new TypeMapper (null, UnicodeMapper); + + TLFCompiler = new TopLevelFunctionCompiler (TypeMapper); + Reflector = new SwiftInterfaceReflector.SwiftInterfaceReflector (null, null); + } + + public ModuleInventory GetModuleInventory (string dylibPath, ErrorHandling errors) { + var moduleInventory = ModuleInventory.FromFile (dylibPath, errors); + return moduleInventory; + } + + public List GetModuleDeclarations (string swiftinterfacePath) { + var xdoc = Reflector.Reflect (swiftinterfacePath); + + var outputFile = System.IO.Path.GetTempPath() + Path.GetFileName(swiftinterfacePath) + ".xml"; + xdoc.Save (outputFile); + var moduleDeclarations = SwiftXmlReflection.Reflector.FromXmlFile (outputFile, null); + return moduleDeclarations; + } + + public void CompileModules (List moduleDeclarations, ModuleInventory moduleInventory, + string swiftLibPath, string outputDirectory, + ErrorHandling errors) + { + foreach (ModuleDeclaration module in moduleDeclarations) { + bool successfulOutput = false; + successfulOutput |= CompileTopLevelEntities (module, moduleInventory, swiftLibPath, outputDirectory, errors); + // successfulOutput |= CompileProtocols (module.Protocols, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileClasses (module.Classes, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileStructs (module.Structs, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileEnums (module.Enums, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileExtensions (module.Extensions, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + if (!successfulOutput) + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 16, "binding-tools-for-swift could not generate any output. Check the logs and consider using '--verbose' for more information."); + } + } + + bool CompileTopLevelEntities (ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors) + { + var use = new CSUsingPackages ("System", "System.Runtime.InteropServices"); + + var picl = new CSClass (CSVisibility.Internal, PIClassName (module.Name + "." + "TopLevelEntities")); + var usedPinvokes = new List (); + + var cl = CompileTLFuncs (module.TopLevelFunctions, module, moduleInventory, + swiftLibPath, outputDirectory, errors, use, null, picl, usedPinvokes); + + cl = CompileTLProps (module.TopLevelProperties, module, moduleInventory, + swiftLibPath, outputDirectory, errors, use, cl, picl, usedPinvokes); + + + if (cl != null) { + string nameSpace = TypeMapper.MapModuleToNamespace (module.Name); + var nm = new CSNamespace (nameSpace); + + var csfile = new CSFile (use, new CSNamespace [] { nm }); + nm.Block.Add (cl); + nm.Block.Add (picl); + string csOutputFileName = string.Format ("{1}{0}.cs", nameSpace, cl.Name.Name); + string csOutputPath = Path.Combine (outputDirectory, csOutputFileName); + + CodeWriter.WriteToFile (csOutputPath, csfile); + + } else { + Console.WriteLine ("No top-level entities"); + return false; + } + return true; + } + + CSClass CompileTLFuncs (IEnumerable funcs, + ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors, + CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokeNames) + { + var methods = new List (); + + foreach (FunctionDeclaration func in funcs) { + try { + if (func.IsProperty) + continue; + + if (func.IsDeprecated || func.IsUnavailable) + continue; + + var tlf = XmlToTLFunctionMapper.ToTLFunction (func, moduleInventory, TypeMapper); + CompileToDirectFunction (func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames); + } catch (Exception e) { + errors.Add (e); + } + } + + if (methods.Count > 0) { + cl = cl ?? new CSClass (CSVisibility.Public, "TopLevelEntities"); + cl.Methods.AddRange (methods); + } + return cl; + } + + void CompileToDirectFunction (FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context, + CSUsingPackages use, string swiftLibPath, List methods, CSClass picl, + List usedPinvokeNames) + { + // FIXME - need to do operators + if (tlf.Operator != OperatorType.None) + return; + + var baseName = TypeMapper.SanitizeIdentifier (tlf.Name.Name); + var pinvokeMethodName = PIFuncName (baseName + homonymSuffix); + pinvokeMethodName = Uniqueify (pinvokeMethodName, usedPinvokeNames); + usedPinvokeNames.Add (pinvokeMethodName); + + var pinvokeMethodRef = PIClassName ($"{func.Module.Name}.TopLevelEntities") + "." + pinvokeMethodName; + + var piMethod = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath), + tlf.MangledName, pinvokeMethodName, true, true, false); + picl.Methods.Add (piMethod); + + var publicMethodOrig = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath), + tlf.MangledName, null, false, false, false); + + CSIdentifier wrapperName = GetMethodWrapperName (func, publicMethodOrig, homonymSuffix); + CSVisibility visibility = GetMethodWrapperVisibility (func, publicMethodOrig); + + // rebuild the method as static + var publicMethod = new CSMethod (visibility, CSMethodKind.Static, publicMethodOrig.Type, + wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body); + publicMethod.GenericParameters.AddRange (publicMethodOrig.GenericParameters); + publicMethod.GenericConstraints.AddRange (publicMethodOrig.GenericConstraints); + + var localIdents = new List { + publicMethod.Name.Name, pinvokeMethodName + }; + localIdents.AddRange (publicMethod.Parameters.Select (p => p.Name.Name)); + + var marshaler = new MarshalEngine (use, localIdents, TypeMapper, null); + var lines = marshaler.MarshalFunctionCall (func, false, pinvokeMethodRef, publicMethod.Parameters, + func, func.ReturnTypeSpec, publicMethod.Type, null, null, false, func, + false, -1, func.HasThrows); + publicMethod.Body.AddRange (lines); + methods.Add (publicMethod); + } + + CSClass CompileTLProps (IEnumerable props, + ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors, + CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokes) + { + var properties = new List (); + + foreach (PropertyDeclaration prop in props) { + if (prop.IsDeprecated || prop.IsUnavailable) + continue; + try { + cl = cl ?? new CSClass (CSVisibility.Public, "TopLevelEntities"); + + // Calculated properties have a matching __method + string backingMethodName = ("__" + prop.Name); + CSMethod backingMethod = cl.Methods.FirstOrDefault (x => x.Name.Name == backingMethodName); + } catch (Exception e) { + errors.Add (e); + } + } + + if (properties.Count > 0) { + cl.Properties.AddRange (properties); + } + return cl; + } + + string PIClassName (string fullClassName) + { + if (!fullClassName.Contains ('.')) + throw new ArgumentOutOfRangeException (nameof (fullClassName), String.Format ("Class name {0} should be a full class name.", fullClassName)); + fullClassName = fullClassName.Substring (fullClassName.IndexOf ('.') + 1).Replace ('.', '_'); + return "NativeMethodsFor" + fullClassName; + } + + string PIClassName (DotNetName fullClassName) + { + return PIClassName (fullClassName.Namespace + "." + fullClassName.TypeName); + } + + string PIClassName (SwiftClassName name) + { + return PIClassName (TypeMapper.GetDotNetNameForSwiftClassName (name)); + } + + string PIFuncName (SwiftName functionName) + { + return String.Format ("PIfunc_{0}", functionName.Name); + } + + string PIFuncName (string functionName) + { + return $"PIfunc_{functionName}"; + } + + CSIdentifier GetMethodWrapperName (FunctionDeclaration func, CSMethod method, string homonymSuffix) + { + string prefix = func.IsProperty ? "__" : ""; + return new CSIdentifier (prefix + method.Name.Name + homonymSuffix); + } + + + CSVisibility GetMethodWrapperVisibility (FunctionDeclaration func, CSMethod method) + { + return func.IsProperty ? CSVisibility.Private: method.Visibility; + } + + static string PInvokeName (string libFullPath, string originalLibrary = null) + { + return LibOrFrameworkFromPath (libFullPath); + } + + static string LibOrFrameworkFromPath (string libFullPath) + { + string directory = Path.GetDirectoryName (libFullPath); + string file = Path.GetFileName (libFullPath); + return file; + } + + public static string Uniqueify (string name, IEnumerable names) + { + int thisTime = 0; + var sb = new StringBuilder (name); + while (names.Contains (sb.ToString ())) { + sb.Clear ().Append (name).Append (thisTime++); + } + return sb.ToString (); + } + } +} diff --git a/src/SwiftReflector/CSKeywords.cs b/src/SwiftReflector/CSKeywords.cs new file mode 100644 index 000000000000..320fd467b1a7 --- /dev/null +++ b/src/SwiftReflector/CSKeywords.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector { + public class CSKeywords { + static HashSet keyWords; + static string [] keyArr = new string [] { + "abstract", "as", "base", "bool", "break", "byte", + "case", "catch", "char", "checked", "class", "const", + "continue", "decimal", "default", "delegate", "do", + "double", "else", "enum", "event", "explicit", "extern", + "false", "finally", "fixed", "float", "for", "foreach", + "goto", "if", "implicit", "in", "int", "interface", "internal", + "is", "lock", "long", "namespace", "new", "null", "object", + "operator", "out", "override", "params", "private", "protected", + "public", "readonly", "ref", "return", "sbyte", "sealed", "short", + "sizeof", "stackalloc", "static", "string", "struct", "switch", + "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", + "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", + "add", "alias", "ascending", "async", "await", "descending", "dynamic", + "from", "get", "global", "group", "into", "join", "let", "orderby", + "partial", "remove", "select", "set", "value", "var", "where", "yield" + }; + static CSKeywords () + { + keyWords = new HashSet (); + foreach (string s in keyArr) { + keyWords.Add (s); + } + } + + public static bool IsKeyword (string s) + { + Exceptions.ThrowOnNull (s, "s"); + return keyWords.Contains (s); + } + } +} + diff --git a/src/SwiftReflector/Demangling/ContextAttribute.cs b/src/SwiftReflector/Demangling/ContextAttribute.cs new file mode 100644 index 000000000000..fd3154e615eb --- /dev/null +++ b/src/SwiftReflector/Demangling/ContextAttribute.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SwiftReflector.Demangling { + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + public class ContextAttribute : Attribute { + } +} diff --git a/src/SwiftReflector/Demangling/Decomposer.cs b/src/SwiftReflector/Demangling/Decomposer.cs new file mode 100644 index 000000000000..8b60a3076c21 --- /dev/null +++ b/src/SwiftReflector/Demangling/Decomposer.cs @@ -0,0 +1,1175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftReflector.ExceptionTools; +using System.Text; + +namespace SwiftReflector.Demangling { + public class Decomposer { + const string kSwiftID = "__T"; + public const string kSwift4ID = "__T0"; + public const string kSwift4xID = "_$s"; + public const string kSwift5ID = "_$S"; + public static SwiftName kSwiftAllocatingConstructorName = new SwiftName (".ctor", false); + public static SwiftName kSwiftNonAllocatingConstructorName = new SwiftName (".nctor", false); + public static SwiftName kSwiftClassConstructorName = new SwiftName (".cctor", false); + public static SwiftName kSwiftDeallocatingDestructorName = new SwiftName (".dtor", false); + public static SwiftName kSwiftNonDeallocatingDestructorName = new SwiftName (".ndtor", false); + public static SwiftName kSwiftWitnessTableName = new SwiftName (".wtable", false); + public static SwiftName kSwiftValueWitnessTableName = new SwiftName (".vwtable", false); + public static SwiftName kSwiftProtocolWitnessTableName = new SwiftName (".pwtable", false); + public static SwiftName kSwiftProtocolWitnessTableAccessorName = new SwiftName (".pwtablea", false); + + List subs = new List (); + + List classes = new List (); + int position; + StringSlice slice; + string originalID; + SwiftName thisModule; + bool isOldVersion; + ulong offset; + + + Decomposer (string swiftIdentifier, bool isOldVersion, ulong offset) + { + if (swiftIdentifier == null) + throw new ArgumentNullException (nameof(swiftIdentifier)); + if (swiftIdentifier.Length == 0) + throw new ArgumentException ("swiftname is empty", nameof(swiftIdentifier)); + originalID = swiftIdentifier; + this.isOldVersion = isOldVersion; + this.offset = offset; + } + + int MarkOperatorPosition () + { + position = slice.Position; + return position; + } + + void Fail (string expected, string butGot = null) + { + if (butGot == null) { + butGot = slice.IsAtEnd ? "nothing at end of string" : slice.Current.ToString (); + } + var message = $"Error decomposing {slice.Original} at position {slice.Position}: expected {expected}, but got {butGot}"; + throw ErrorHelper.CreateError (ReflectorError.kDecomposeBase + 1, message); + } + + void Initialize () + { + thisModule = null; + classes.Clear (); + slice = new StringSlice (originalID); + MarkOperatorPosition (); + } + + public static TLDefinition Decompose (string swiftIdentifier, bool isOldVersion, ulong offset = 0) + { + if (swiftIdentifier.StartsWith (kSwift4xID, StringComparison.Ordinal)|| + swiftIdentifier.StartsWith (kSwift5ID, StringComparison.Ordinal)) { + var demangler5 = new Swift5Demangler (swiftIdentifier, offset); + return demangler5.Run (); + } + if (swiftIdentifier.StartsWith (kSwift4ID, StringComparison.Ordinal)) { + var demangler = new Swift4Demangler (swiftIdentifier, offset); + return demangler.Run (); + } else { + Decomposer decomp = new Decomposer (swiftIdentifier, isOldVersion, offset); + return decomp.Run (); + } + } + + public static string ExplodedView (string swiftIdentifier) + { + if (swiftIdentifier.StartsWith (kSwift4ID, StringComparison.Ordinal)) { + var demangler = new Swift4Demangler (swiftIdentifier, 0); + return demangler.ExplodedView (); + } + return null; + } + + public TLDefinition Run () + { + Initialize (); + + RemoveSwiftID (); + + char c = slice.Advance (); + switch (c) { + case 'Z': + if (slice.AdvanceIfEquals ('F')) { + return ToFunction (true, false); + } else if (slice.AdvanceIfEquals ('v')) { + return ToVariable (true); + } else { + Fail ("a static function (F)"); + } + break; + case 'F': + return ToFunction (false, false); + case 'M': + return ToMetadata (); + case 'W': + return ToWitnessTable (); + case 'v': + return ToVariable (false); + case 'T': + return ToThunk (); + case 'I': + return ToInitializer (); + default: + Fail ("one of Z, F, M, v, T, I or W", c.ToString ()); + break; + } + return null; + } + + void RemoveSwiftID () + { + if (!slice.StartsWith (kSwiftID)) + Fail ("Swift symbol (__T)", slice.Original.Substring (0, Math.Min (3, slice.Original.Length))); + slice.Advance (kSwiftID.Length); + } + + SwiftName GetModule () + { + return slice.ExtractSwiftName (); + } + + public static MemberNesting? ToMaybeMemberNesting (char c, bool throwOnFail) + { + switch (c) { + case 'C': + return MemberNesting.Class; + case 'V': + return MemberNesting.Struct; + case 'O': + return MemberNesting.Enum; + case 'P': + return MemberNesting.Protocol; + default: + if (throwOnFail) + throw new ArgumentOutOfRangeException (nameof(c)); + return null; + } + } + + MemberNesting ToMemberNesting (char c) + { + MemberNesting? nesting = ToMaybeMemberNesting (c, false); + if (!nesting.HasValue) { + Fail ("either a struct, class, enum, or protocol nesting marker (C, V, O, or P)"); + } + return nesting.Value; + } + + MemberType ToMemberType (char c) + { + switch (c) { + case 'C': + return MemberType.Allocator; + case 'c': + return MemberType.Constructor; + case 'D': + return MemberType.Deallocator; + case 'd': + return MemberType.Destructor; + case 'f': + return MemberType.UncurriedFunction; + case 'F': + return MemberType.Function; + case 'g': + return MemberType.Getter; + case 's': + return MemberType.Setter; + default: + Fail ("a member type marker (one of C, c, D, d, F, f, g, or s"); + return MemberType.Allocator; // never hit, thanks C#, you're the best + } + } + + CoreBuiltInType ToCoreScalar (char c) + { + switch (c) { + case 'b': + return CoreBuiltInType.Bool; + case 'd': + return CoreBuiltInType.Double; + case 'f': + return CoreBuiltInType.Float; + case 'i': + return CoreBuiltInType.Int; + case 'u': + return CoreBuiltInType.UInt; + default: + Fail ("a core type marker (one of b, d, f, i, or u)"); + return CoreBuiltInType.Bool; // never hit, thanks C#, you're the best + } + } + + IList GetNesting () + { + Stack st = new Stack (); + while (!Char.IsDigit (slice.Current)) { + MarkOperatorPosition (); + st.Push (ToMemberNesting (slice.Advance ())); + } + return st.ToList (); + } + + IList GetNestingAlt () + { + Stack st = new Stack (); + while (!slice.StartsWith ('S') && !slice.StartsWith ('s') && !Char.IsDigit (slice.Current)) { + MarkOperatorPosition (); + st.Push (ToMemberNesting (slice.Advance ())); + } + return st.ToList (); + } + + IList GetNestingNames (int expected) + { + List names = new List (expected); + for (int i = 0; i < expected; i++) { + MarkOperatorPosition (); + SwiftName sw = slice.ExtractSwiftName (); + if (sw == null) + Fail (String.Format ("{0} nested class names", expected)); + names.Add (sw); + } + return names; + } + + SwiftClassName ReadProtocolName () + { + MarkOperatorPosition (); + // module? + IList nesting = new List { MemberNesting.Protocol }; + + SwiftType st = ReadContext (); + SwiftClassType ct = st as SwiftClassType; + if (ct == null) { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail ("SwiftModuleNameType", st.GetType ().Name); + ct = new SwiftClassType (new SwiftClassName (mod.Name, new List (), new List ()), false, null); + } + + + IList nestingNames = GetNestingNames (nesting.Count); + return new SwiftClassName (ct.ClassName.Module, nesting, nestingNames); + } + + SwiftClassName CombineContextAndName (SwiftType context, SwiftName terminus, MemberNesting nesting, OperatorType oper) + { + if (context is SwiftModuleNameType) { + return new SwiftClassName (context.Name, new List { nesting }, + new List { terminus }); + } + if (context is SwiftClassType) { + SwiftClassType ct = context as SwiftClassType; + List newnesting = new List (); + newnesting.AddRange (ct.ClassName.Nesting); + newnesting.Add (nesting); + List newnames = new List (); + newnames.AddRange (ct.ClassName.NestingNames); + newnames.Add (terminus); + return new SwiftClassName (ct.ClassName.Module, newnesting, newnames, oper); + } + Fail ("a SwiftModuleNameType or a SwiftClassType", context.GetType ().Name); + return null; // never reached - thanks C# + } + + SwiftClassName ReadClassStructEnumNameAlt () + { + if (!slice.StartsWith ('C') && !slice.StartsWith ('V') && !slice.StartsWith ('O')) + Fail ("class, struct, or enum markers (C, V, or O)"); + MarkOperatorPosition (); + + MemberNesting nesting = ToMemberNesting (slice.Advance ()); + SwiftType context = ReadContext (); + OperatorType oper = OperatorType.None; + SwiftName name = slice.ExtractSwiftNameMaybeOperator (out oper); + SwiftClassName className = CombineContextAndName (context, name, nesting, oper); + return className; + } + + public SwiftClassType ReadClassStructOrEnum (SwiftName name, bool isReference) + { + if (!slice.StartsWith ('C') && !slice.StartsWith ('V') && !slice.StartsWith ('O')) + Fail ("class, struct, or enum markers (C, V, or O)"); + MarkOperatorPosition (); + SwiftClassName cn = ReadClassStructEnumNameAlt (); + SwiftClassType ct = new SwiftClassType (cn, isReference, name); + subs.Add (ct); + return ct; + } + + + SwiftType ReadContext () + { + if (slice.Current == 'S') { + return DemangleSubstitution (null, false); + } + if (slice.AdvanceIfEquals ('s')) { + return new SwiftModuleNameType (new SwiftName ("Swift", false), false); + } + if (slice.StartsWith ('C') || slice.StartsWith ('V') || slice.StartsWith ('O')) { + return ReadClassStructOrEnum (null, false); + } + SwiftName module = GetModule (); + SwiftModuleNameType modName = new SwiftModuleNameType (module, false); + subs.Add (modName); + return modName; + } + + + TLDefinition ToMetadata () + { + MarkOperatorPosition (); + // current version doesn't use 'd', but is implicit + + + char c = (slice.Current == 'C' || slice.Current == 'V' || slice.Current == 'O') ? 'd' : slice.Advance (); + SwiftClassName className = c != 'p' ? ReadClassStructEnumNameAlt () : ReadProtocolName (); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType (className, false); + subs.Add (cl); + + switch (c) { + case 'a': + return new TLFunction (slice.Original, thisModule, kSwiftClassConstructorName, cl, + new SwiftClassConstructorType (new SwiftMetaClassType (cl, false), false), offset); + case 'L': + return new TLLazyCacheVariable (slice.Original, thisModule, cl, offset); + case 'd': + return new TLDirectMetadata (slice.Original, thisModule, cl, offset); + case 'm': + return new TLMetaclass (slice.Original, thisModule, cl, offset); + case 'n': + return new TLNominalTypeDescriptor (slice.Original, thisModule, cl, offset); + case 'p': + return new TLProtocolTypeDescriptor (slice.Original, thisModule, cl, offset); + case 'P': + return new TLGenericMetadataPattern (slice.Original, thisModule, cl, offset); + default: + Fail ("a metaclass descriptor (a, L, d, m, or n, p)", c.ToString ()); + return null; + } + } + + TLVariable ToVariable (bool isStatic) + { + MarkOperatorPosition (); + SwiftType st = ReadContext (); + SwiftClassType cl = st as SwiftClassType; + if (cl == null) { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail ("a SwiftModuleType", st.GetType ().Name); + cl = new SwiftClassType (new SwiftClassName (mod.Name, new List (), + new List ()), false); + } + SwiftName module = cl.ClassName.Module; + if (cl.ClassName.Nesting.Count == 0) + cl = null; + SwiftName varName = slice.ExtractSwiftName (); + SwiftType ofType = ReadType (false); + return new TLVariable (slice.Original, module, cl, varName, ofType, isStatic, offset); + } + + TLThunk ToThunk () + { + MarkOperatorPosition (); + ThunkType thunkType = ToThunkType (); + SwiftClassName className = ReadClassStructEnumNameAlt (); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType (className, false); + return new TLThunk (thunkType, slice.Original, thisModule, cl, offset); + } + + ThunkType ToThunkType () + { + char c = slice.Advance (); + switch (c) { + case 'R': + return ThunkType.ReabstractionHelper; + case 'r': + return ThunkType.Reabstraction; + case 'W': + return ThunkType.ProtocolWitness; + default: + Fail ("a thunk type marker, one of R, r, or W", c.ToString ()); + return ThunkType.ProtocolWitness; // can't happen + } + } + + TLDefinition ToInitializer () + { + MarkOperatorPosition (); + if (slice.AdvanceIfEquals ('v')) { + return ToInitializer (InitializerType.Variable); + } else { + Fail ("expected a variable initializer marker (v)"); + return null; // stupid compile + } + } + + TLDefinition ToInitializer (InitializerType type) + { + SwiftType readType = ReadContext (); + SwiftClassType owner = readType as SwiftClassType; + if (owner == null) + Fail ("SwiftClassType", readType.GetType ().Name); + thisModule = owner.ClassName.Module; + + SwiftName varName = slice.ExtractSwiftName (); + SwiftType varType = ReadType (false); + return new TLFunction (slice.Original, thisModule, + varName, owner, + new SwiftInitializerType (InitializerType.Variable, varType, owner, varName), + offset); + } + + + TLDefinition ToWitnessTable () + { + MarkOperatorPosition (); + if (slice.StartsWith ('v')) + return ToFieldOffset (); + if (slice.StartsWith ('V')) + return ToValueWitnessTable (); + if (slice.StartsWith ('P')) + return ToProtocolWitnessTable (); + if (slice.StartsWith ('a')) + return ToProtocolWitnessTableAccessor (); + if (!slice.AdvanceIfEquals ('o')) + Fail ("expected witness table offset marker (o)"); + if (!slice.AdvanceIfEquals ('F')) + Fail ("expected a function marker (F) after witness table offset"); + + SwiftClassName className = ReadClassStructEnumNameAlt (); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType (className, false); + subs.Add (cl); + + MarkOperatorPosition (); + + // A witness table is not strictly a function, but the overall structure of its descriptor + // matches an uncurried function closely enough that we can make it pass for one. + // The consuming code doesn't care and pulls it out as is. + SwiftWitnessTableType wit = new SwiftWitnessTableType (WitnessType.Class); + + TLFunction func = new TLFunction (slice.Original, thisModule, null, cl, wit, offset); + return func; + } + + TLDefinition ToValueWitnessTable () + { + return ToWitnessFoo ('V', "value witness table", WitnessType.Value); + } + + TLDefinition ToProtocolWitnessTable () + { + return ToWitnessFoo ('P', "protocol witness table", WitnessType.Protocol); + } + + TLDefinition ToProtocolWitnessTableAccessor () + { + return ToWitnessFoo ('a', "protocol witness table accessor", WitnessType.ProtocolAccessor); + } + + TLDefinition ToWitnessFoo (char marker, string descriptor, WitnessType witnessType) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals (marker)) + Fail (String.Format ("{0} marker ({1})", descriptor, marker)); + + SwiftClassName className = ReadClassStructEnumNameAlt (); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType (className, false); + subs.Add (cl); + + + SwiftClassName protoName = witnessType == WitnessType.Protocol ? ReadProtocolName () : null; + SwiftClassType proto = protoName != null ? new SwiftClassType (protoName, false) : null; + + MarkOperatorPosition (); + // this is likely wrong, but it's less wrong than it was + SwiftWitnessTableType witf = new SwiftWitnessTableType (witnessType, proto); + TLFunction func = new TLFunction (slice.Original, thisModule, null, cl, witf, offset); + return func; + } + + TLDefinition ToFieldOffset () + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('v')) + Fail ("a field offset marker (v)"); + if (!(slice.StartsWith ('d') || slice.StartsWith ('i'))) + Fail ("a direct or indirect marker (d, i)"); + bool direct = slice.StartsWith ('d'); + slice.Advance (); + + slice.Advance (); + + SwiftClassType cl = ReadType (false) as SwiftClassType; + if (cl == null) + Fail ("a class descriptor"); + thisModule = cl.ClassName.Module; + + SwiftName ident = slice.ExtractSwiftName (); + SwiftType type = ReadType (false); + + return new TLFieldOffset (slice.Original, thisModule, cl, direct, ident, type, offset); + } + + + TLFunction ToFunction (bool isStatic, bool isReference) + { + MarkOperatorPosition (); + if (slice.StartsWith ('F')) { + return ReadExplicitClosure (isReference); + } + + SwiftType st = ReadContext (); + SwiftClassType cl = st as SwiftClassType; + if (cl == null) { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail ("a SwiftModuleType", st.GetType ().Name); + cl = new SwiftClassType (new SwiftClassName (mod.Name, new List (), + new List ()), false); + } + + MarkOperatorPosition (); + OperatorType oper = OperatorType.None; + SwiftName functionName = slice.ExtractSwiftNameMaybeOperator (out oper); + + + SwiftBaseFunctionType baseFunc = null; + + switch (slice.Current) { + case 'C': + baseFunc = ReadAllocatorType (isReference); + break; + case 'c': + baseFunc = ReadConstructorType (isReference); + break; + case 'D': + baseFunc = new SwiftDestructorType (true, cl, isReference, false); + break; + case 'd': + baseFunc = new SwiftDestructorType (false, cl, isReference, false); + break; + case 'g': + baseFunc = ReadGetter (cl, isStatic, isReference); + break; + case 's': + baseFunc = ReadSetter (cl, isStatic, isReference); + break; + case 'm': + baseFunc = ReadMaterializer (cl, isStatic, isReference); + break; + case 'a': + baseFunc = ReadAddressorMutable (cl, isReference); + break; + case 'l': + baseFunc = ReadAddressor (cl, isReference); + break; + default: + baseFunc = ReadType (isReference) as SwiftBaseFunctionType; + if (isStatic && baseFunc is SwiftUncurriedFunctionType) { + SwiftUncurriedFunctionType ucf = baseFunc as SwiftUncurriedFunctionType; + baseFunc = new SwiftStaticFunctionType (ucf.Parameters, ucf.ReturnType, ucf.IsReference, ucf.CanThrow, ucf.UncurriedParameter as SwiftClassType, ucf.Name); + } + break; + } + + + if (baseFunc == null) + Fail ("a function"); + + functionName = functionName ?? baseFunc.Name; + + if (functionName == null) + throw new ArgumentNullException ("blah"); + + return new TLFunction (slice.Original, cl.ClassName.Module, functionName, cl, baseFunc, offset, oper); + } + + SwiftType ReadType (bool isReference, SwiftName name = null) + { + name = slice.IsNameNext ? slice.ExtractSwiftName () : name; + char t = slice.Current; + MarkOperatorPosition (); + switch (t) { + case 'f': + return ReadUncurriedFunctionType (name, isReference, subs.Last () as SwiftClassType); + + case 'F': + return ReadFunctionType (name, isReference); + case 'c': + return ReadCFunctionType (name, isReference); + case 'G': + return ReadBoundGenericType (name, isReference); + case 'S': + return DemangleSubstitution (name, isReference); + case 'V': + case 'C': + case 'O': + return ReadClassOrStructOrEnum (name, isReference); + case 'P': + return ReadProtocolList (name, isReference); + case 'M': + return ReadMetaClassType (name, isReference); + case 'R': + slice.Advance (); + return ReadType (true, name); + case 'T': + return ReadTupleType (name, isReference); + case 'u': + return ReadUnboundGenericType (name, isReference); + case 'x': + slice.Advance (); + return new SwiftGenericArgReferenceType (0, 0, isReference, name); + case 'q': + return ReadGenericReferenceType (name, isReference); + default: + Fail ("a type marker (one of F, G, S, V, C, O, M, R, T, u, x, or q)"); + return null; + } + } + + TLFunction ReadExplicitClosure (bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('F')) + Fail ("an explicit closure marker (F)"); + + SwiftClassType st = ReadType (isReference) as SwiftClassType; + if (st == null) + Fail ("a class type"); + return new TLFunction (slice.Original, st.ClassName.Module, st.Name, st, new SwiftExplicitClosureType (isReference), offset); + } + + SwiftUncurriedFunctionType ReadUncurriedFunctionType (SwiftName name, bool isReference, SwiftType implicitType) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('f')) + Fail ("an uncurried function type (f)"); + bool canThrow = slice.AdvanceIfEquals ('z'); + if (isOldVersion) { + SwiftType uncurriedParamType = ReadType (false); + SwiftFunctionType func = ReadFunctionType (null, false); + return new SwiftUncurriedFunctionType (uncurriedParamType, func.Parameters, func.ReturnType, isReference, canThrow, name); + } else { + SwiftType args = ReadType (false); + SwiftType ret = ReadType (false); + return new SwiftUncurriedFunctionType (implicitType, args, ret, isReference, canThrow, name); + } + } + + SwiftConstructorType ReadAllocOrCons (bool isAllocator, char advanceOn, string expected, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals (advanceOn)) + Fail (expected); + SwiftUncurriedFunctionType ucf = ReadUncurriedFunctionType (null, false, new SwiftMetaClassType (subs.Last () as SwiftClassType, false, null)); + return new SwiftConstructorType (isAllocator, ucf.UncurriedParameter, ucf.Parameters, ucf.ReturnType, isReference, ucf.CanThrow); + } + + SwiftAddressorType ReadAddressorMutable (SwiftClassType cl, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('a')) + Fail ("an addressor"); + AddressorType theType = AddressorType.UnsafeMutable; + char c = slice.Advance (); + switch (c) { + case 'O': + theType = AddressorType.OwningMutable; + break; + case 'o': + theType = AddressorType.NativeOwningMutable; + break; + case 'p': + theType = AddressorType.NativePinningMutable; + break; + case 'u': + theType = AddressorType.UnsafeMutable; + break; + default: + Fail ("one of O, o, p, or u", c.ToString ()); + break; + } + if (!slice.IsNameNext) + Fail ("a swift name"); + SwiftName addressorName = slice.ExtractSwiftName (); + SwiftType ofType = ReadType (true); // addressors return the address of the entity + return new SwiftAddressorType (theType, ofType, isReference, addressorName); + } + + SwiftAddressorType ReadAddressor (SwiftClassType cl, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('l')) + Fail ("an addressor"); + AddressorType theType = AddressorType.UnsafeMutable; + char c = slice.Advance (); + switch (c) { + case 'O': + theType = AddressorType.Owning; + break; + case 'o': + theType = AddressorType.NativeOwning; + break; + case 'p': + theType = AddressorType.NativePinning; + break; + case 'u': + theType = AddressorType.Unsafe; + break; + default: + Fail ("one of O, o, p, or u", c.ToString ()); + break; + } + if (!slice.IsNameNext) + Fail ("a swift name"); + SwiftName addressorName = slice.ExtractSwiftName (); + SwiftType ofType = ReadType (true); // addressors return the address of the entity + return new SwiftAddressorType (theType, ofType, isReference, addressorName); + } + + SwiftPropertyType ReadGetter (SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('g')) + Fail ("a property getter (g)"); + return ReadProperty (cl, PropertyType.Getter, isStatic, isReference); + } + + SwiftPropertyType ReadSetter (SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('s')) + Fail ("a property setter"); + return ReadProperty (cl, PropertyType.Setter, isStatic, isReference); + } + + SwiftPropertyType ReadMaterializer (SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('m')) + Fail ("a property materializer"); + return ReadProperty (cl, PropertyType.Materializer, isStatic, isReference); + } + + SwiftPropertyType ReadProperty (SwiftClassType cl, PropertyType propType, bool isStatic, bool isReference) + { + SwiftName privateName = null; + MarkOperatorPosition (); + if (slice.AdvanceIfEquals ('P')) + privateName = slice.ExtractSwiftName (); + MarkOperatorPosition (); + if (!slice.IsNameNext) + Fail ("a swift name"); + SwiftName propName = slice.ExtractSwiftName (); + + if (IsSubscript (propName)) { + SwiftType subscriptType = ReadType (false); + SwiftBaseFunctionType subscriptFunc = subscriptType as SwiftBaseFunctionType; + if (subscriptFunc == null) + Fail ("a function type in an indexed property", subscriptType.GetType ().Name); + + if (propType == PropertyType.Setter && subscriptFunc.ReturnType != null && !subscriptFunc.ReturnType.IsEmptyTuple) { + // oh hooray! + // If I define an indexer in swift like this: + // public subscript(T index) -> U { + // get { return getSomeUValue(index); } + // set (someUValue) { setSomeUValue(index, someUValue); } + // } + // This signature of the function attached to both properties is: + // T -> U + // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but + // the setter is (T, U) -> void + // + // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect + // what's really happening. + + // need to change this so that the tail parameters get names? Maybe just the head? + + SwiftTupleType newParameters = subscriptFunc.ParameterCount == 1 ? + new SwiftTupleType (false, null, subscriptFunc.ReturnType, + subscriptFunc.Parameters.RenamedCloneOf (new SwiftName (subscriptFunc.ReturnType.Name == null || + subscriptFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) + : new SwiftTupleType (Enumerable.Concat (subscriptFunc.ReturnType.Yield (), subscriptFunc.EachParameter), + false, null); + subscriptFunc = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, subscriptFunc.CanThrow, subscriptFunc.Name); + } + return new SwiftPropertyType (cl, propType, propName, privateName, (SwiftFunctionType)subscriptFunc, isStatic, isReference); + + } else { + SwiftType ofType = ReadType (false); + + return new SwiftPropertyType (cl, propType, propName, privateName, ofType, isStatic, isReference); + } + } + + public static bool IsSubscript (SwiftName name) + { + return name.Name == "subscript"; + } + + SwiftConstructorType ReadAllocatorType (bool isReference) + { + return ReadAllocOrCons (true, 'C', "an allocating constructor (C)", isReference); + } + + SwiftConstructorType ReadConstructorType (bool isReference) + { + return ReadAllocOrCons (false, 'c', "a non-allocating constructor (c)", isReference); + } + + SwiftType ReadProtocolList (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('P')) + Fail ("A protocol list marker ('P')"); + if (slice.Current == 'M') { + return ReadExistentialMetatype (name, isReference); + } + List protocols = new List (); + while (slice.Current != '_') { + SwiftClassName className = ReadProtocolName (); + SwiftClassType theProtocol = new SwiftClassType (className, false, null); + subs.Add (theProtocol); + protocols.Add (theProtocol); + } + slice.Advance (); + return new SwiftProtocolListType (protocols, isReference, name); + } + + SwiftClassType ReadClassOrStructOrEnum (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + SwiftClassName className = ReadClassStructEnumNameAlt (); + SwiftClassType clType = new SwiftClassType (className, isReference, name); + subs.Add (clType); + return clType; + } + + SwiftMetaClassType ReadMetaClassType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('M')) + Fail ("a metaclass marker (M)"); + SwiftClassType cl = ReadType (false) as SwiftClassType; + if (cl == null) + Fail ("a class type"); + return new SwiftMetaClassType (cl, isReference, name); + } + + SwiftExistentialMetaType ReadExistentialMetatype (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('M')) + Fail ("a metaclass marker (M)"); + SwiftProtocolListType pl = ReadType (false) as SwiftProtocolListType; + if (pl == null) + Fail ("a protocol list type"); + return new SwiftExistentialMetaType (pl, isReference, name); + } + + + SwiftType ReadUnboundGenericType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('u')) + Fail ("an unbound generic type (u)"); + MarkOperatorPosition (); + List parms = ReadGenericArguments (); + SwiftType dependentType = ReadType (isReference, name); + SwiftBaseFunctionType bft = dependentType as SwiftBaseFunctionType; + if (bft != null) { + bft.GenericArguments.AddRange (parms); + return bft; + } + return new SwiftUnboundGenericType (dependentType, parms, isReference, dependentType.Name); + } + + + List ReadGenericArguments () + { + int count = 0; + while (slice.Current != 'R' && slice.Current != 'r') { + count = DemangleIndex (); + } + count += 1; + List args = new List (count); + for (int i = 0; i < count; i++) { + args.Add (new GenericArgument (0, i)); + } + if (slice.AdvanceIfEquals ('r')) + return args; + if (!slice.AdvanceIfEquals ('R')) + Fail ("A generic argument requirements marker (R)"); + while (!slice.AdvanceIfEquals ('r')) { + int depth = 0; + int index = 0; + if (slice.AdvanceIfEquals ('d')) { + depth = DemangleIndex (); + index = DemangleIndex (); + } else if (slice.AdvanceIfEquals ('x')) { + // no change + } else { + index = DemangleIndex () + 1; + } + if (slice.StartsWith ('C')) { + SwiftType constraintType = ReadType (false, null); + args [index].Constraints.Add (constraintType); + } else { + SwiftClassName className = ReadProtocolName (); + SwiftClassType theProtocol = new SwiftClassType (className, false, null); + args [index].Constraints.Add (theProtocol); + } + args [index].Depth = depth; + } + // currently swift name mangling is done incorrectly to get the actual + // depth. In the case where there is a 'where' clause, we can figure it out + // and correct it. + int maxDepth = 0; + foreach (GenericArgument gen in args) { + maxDepth = Math.Max (maxDepth, gen.Depth); + } + foreach (GenericArgument gen in args) { + gen.Depth = maxDepth; + } + return args; + } + + SwiftGenericArgReferenceType ReadGenericReferenceType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('q')) + Fail ("a generic argument reference"); + MarkOperatorPosition (); + int depth = 0; + int index = 0; + if (slice.AdvanceIfEquals ('d')) { + depth = DemangleIndex () + 1; + index = DemangleIndex () + 1; + } else { + index = DemangleIndex () + 1; + } + return new SwiftGenericArgReferenceType (depth, index, isReference, name); + } + + SwiftBoundGenericType ReadBoundGenericType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('G')) + Fail ("a bound generic type (G)"); + MarkOperatorPosition (); + SwiftType baseType = ReadType (false); + + List generics = new List (); + while (!slice.AdvanceIfEquals ('_')) { + MarkOperatorPosition (); + SwiftType t = ReadType (false); + if (t != null) + generics.Add (t); + } + return new SwiftBoundGenericType (baseType, generics, isReference, name); + } + + SwiftArrayType ReadArrayType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('S') || !slice.AdvanceIfEquals ('a')) + Fail ("an Array type (Sa)"); + return new SwiftArrayType (isReference, name); + } + + SwiftFunctionType ReadFunctionType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('F')) + Fail ("a function marker (F)"); + bool canThrow = slice.AdvanceIfEquals ('z'); + SwiftType parms = ReadType (false); + SwiftType ret = ReadType (false); + return new SwiftFunctionType (parms, ret, isReference, canThrow, name); + } + + SwiftCFunctionType ReadCFunctionType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('c')) + Fail ("a C function marker (c)"); + SwiftType parms = ReadType (false); + SwiftType ret = ReadType (false); + return new SwiftCFunctionType (parms, ret, isReference, name); + } + + SwiftType ReadScalarType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('S')) + Fail ("a core built in type marker (S)"); + if (slice.Current == 'S') { + slice.Advance (); + return ClassForBuiltInType (name, "String", MemberNesting.Struct, isReference); + } else if (slice.Current == 'q') { + slice.Advance (); + return ClassForBuiltInType (name, "Optional", MemberNesting.Enum, isReference); + } else if (slice.Current == 'Q') { + slice.Advance (); + return ClassForBuiltInType (name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); + } else if (slice.Current == 'P') { + slice.Advance (); + return ClassForBuiltInType (name, "UnsafePointer", MemberNesting.Struct, isReference); + } else if (slice.Current == 'p') { + slice.Advance (); + return ClassForBuiltInType (name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); + } else if (slice.Current == 'R') { + slice.Advance (); + return ClassForBuiltInType (name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); + } else if (slice.Current == 'r') { + slice.Advance (); + return ClassForBuiltInType (name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); + } else { + CoreBuiltInType scalarType = ToCoreScalar (slice.Advance ()); + return new SwiftBuiltInType (scalarType, isReference, name); + } + } + + SwiftTupleType ReadTupleType (SwiftName name, bool isReference) + { + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('T')) + Fail ("a tuple marker (T)"); + + List contents = new List (); + while (!slice.AdvanceIfEquals ('_')) { + MarkOperatorPosition (); + SwiftType ty = ReadType (false); + contents.Add (ty); + } + return new SwiftTupleType (contents, isReference, name); + } + + static SwiftClassType ClassForBuiltInType (SwiftName name, string className, MemberNesting nesting, bool isReference) + { + return new SwiftClassType (new SwiftClassName (new SwiftName ("Swift", false), + new List { nesting }, + new List { new SwiftName (className, false) }), isReference, name); + } + + SwiftType DemangleSubstitution (SwiftName name, bool isReference) + { + if (!slice.AdvanceIfEquals ('S')) + Fail ("a core built in type marker (S)"); + if (slice.AdvanceIfEquals ('a')) { + return ClassForBuiltInType (name, "Array", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('c')) { + return ClassForBuiltInType (name, "UnicodeScalar", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('S')) { + return ClassForBuiltInType (name, "String", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('q')) { + return ClassForBuiltInType (name, "Optional", MemberNesting.Enum, isReference); + } + if (slice.AdvanceIfEquals ('Q')) { + return ClassForBuiltInType (name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('P')) { + return ClassForBuiltInType (name, "UnsafePointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('p')) { + return ClassForBuiltInType (name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('R')) { + return ClassForBuiltInType (name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('r')) { + return ClassForBuiltInType (name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('V')) { + return ClassForBuiltInType (name, "UnsafeRawPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('v')) { + return ClassForBuiltInType (name, "UnsafeMutableRawPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals ('b')) { + return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); + } + if (slice.AdvanceIfEquals ('d')) { + return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); + } + if (slice.AdvanceIfEquals ('f')) { + return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); + } + if (slice.AdvanceIfEquals ('i')) { + return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); + } + if (slice.AdvanceIfEquals ('u')) { + return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); + } + if (slice.AdvanceIfEquals ('s')) { + return new SwiftModuleNameType (new SwiftName ("Swift", false), isReference); + } + int index = DemangleIndex (); + SwiftType st = subs [index]; + SwiftClassType sct = st as SwiftClassType; + if (sct == null) { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail ("a SwiftModuleNameType", st.GetType ().Name); + return mod; + } + return new SwiftClassType (sct.ClassName, isReference, name); + } + + int DemangleIndex () + { + if (slice.AdvanceIfEquals ('_')) { + return 0; + } + MarkOperatorPosition (); + if (!Char.IsDigit (slice.Current)) + Fail ("a number", slice.Current.ToString ()); + int index = ReadNumber (); + MarkOperatorPosition (); + if (!slice.AdvanceIfEquals ('_')) + Fail ("a macro terminator '-'", slice.Current.ToString ()); + return index + 1; + } + + int ReadNumber () + { + int number = 0; + while (Char.IsDigit (slice.Current)) { + number = 10 * number + slice.Current - '0'; + slice.Advance (); + } + return number; + } + } +} + diff --git a/src/SwiftReflector/Demangling/Enums.cs b/src/SwiftReflector/Demangling/Enums.cs new file mode 100644 index 000000000000..f79773f0e226 --- /dev/null +++ b/src/SwiftReflector/Demangling/Enums.cs @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +namespace SwiftReflector.Demangling { + public enum NodeKind { + [Context] + Allocator, + [Context] + AnonymousContext, + AnyProtocolConformanceList, + ArgumentTuple, + AssociatedType, + AssociatedTypeRef, + AssociatedTypeMetadataAccessor, + DefaultAssociatedTypeMetadataAccessor, + AssociatedTypeWitnessTableAccessor, + BaseWitnessTableAccessor, + AutoClosureType, + BoundGenericClass, + BoundGenericEnum, + BoundGenericStructure, + BoundGenericProtocol, + BoundGenericOtherNominalType, + BoundGenericTypeAlias, + BoundGenericFunction, + BuiltinTypeName, + CFunctionPointer, + [Context] + Class, + ClassMetadataBaseOffset, + ConcreteProtocolConformance, + [Context] + Constructor, + CoroutineContinuationPrototype, + [Context] + Deallocator, + DeclContext, + [Context] + DefaultArgumentInitializer, + DependentAssociatedConformance, + DependentAssociatedTypeRef, + DependentGenericConformanceRequirement, + DependentGenericParamCount, + DependentGenericParamType, + DependentGenericSameTypeRequirement, + DependentGenericLayoutRequirement, + DependentGenericSignature, + DependentGenericType, + DependentMemberType, + DependentPseudogenericSignature, + DependentProtocolConformanceRoot, + DependentProtocolConformanceInherited, + DependentProtocolConformanceAssociated, + [Context] + Destructor, + [Context] + DidSet, + Directness, + DynamicAttribute, + DirectMethodReferenceAttribute, + DynamicSelf, + DynamicallyReplaceableFunctionImpl, + DynamicallyReplaceableFunctionKey, + DynamicallyReplaceableFunctionVar, + [Context] + Enum, + EnumCase, + ErrorType, + EscapingAutoClosureType, + NoEscapeFunctionType, + ExistentialMetatype, + [Context] + ExplicitClosure, + [Context] + Extension, + FieldOffset, + FullTypeMetadata, + [Context] + Function, + FunctionSignatureSpecialization, + FunctionSignatureSpecializationParam, + FunctionSignatureSpecializationParamKind, + FunctionSignatureSpecializationParamPayload, + FunctionType, + GenericPartialSpecialization, + GenericPartialSpecializationNotReAbstracted, + GenericProtocolWitnessTable, + GenericProtocolWitnessTableInstantiationFunction, + ResilientProtocolWitnessTable, + GenericSpecialization, + GenericSpecializationNotReAbstracted, + GenericSpecializationParam, + InlinedGenericFunction, + GenericTypeMetadataPattern, + [Context] + Getter, + Global, + [Context] + GlobalGetter, + Identifier, + Index, + [Context] + IVarInitializer, + [Context] + IVarDestroyer, + ImplEscaping, + ImplConvention, + ImplFunctionAttribute, + ImplFunctionType, + [Context] + ImplicitClosure, + ImplParameter, + ImplResult, + ImplErrorResult, + InOut, + InfixOperator, + [Context] + Initializer, + KeyPathGetterThunkHelper, + KeyPathSetterThunkHelper, + KeyPathEqualsThunkHelper, + KeyPathHashThunkHelper, + LazyProtocolWitnessTableAccessor, + LazyProtocolWitnessTableCacheVariable, + LocalDeclName, + [Context] + MaterializeForSet, + MergedFunction, + Metatype, + MetatypeRepresentation, + Metaclass, + MethodLookupFunction, + ObjCMetadataUpdateFunction, + [Context] + ModifyAccessor, + [Context] + Module, + [Context] + NativeOwningAddressor, + [Context] + NativeOwningMutableAddressor, + [Context] + NativePinningAddressor, + [Context] + NativePinningMutableAddressor, + NominalTypeDescriptor, + NonObjCAttribute, + Number, + ObjCAttribute, + ObjCBlock, + [Context] + OtherNominalType, + [Context] + OwningAddressor, + [Context] + OwningMutableAddressor, + PartialApplyForwarder, + PartialApplyObjCForwarder, + PostfixOperator, + PrefixOperator, + PrivateDeclName, + PropertyDescriptor, + [Context] + Protocol, + [Context] + ProtocolSymbolicReference, + ProtocolConformance, + ProtocolConformanceRefInTypeModule, + ProtocolConformanceRefInProtocolModule, + ProtocolConformanceRefInOtherModule, + ProtocolDescriptor, + ProtocolConformanceDescriptor, + ProtocolList, + ProtocolListWithClass, + ProtocolListWithAnyObject, + ProtocolSelfConformanceDescriptor, + ProtocolSelfConformanceWitness, + ProtocolSelfConformanceWitnessTable, + ProtocolWitness, + ProtocolWitnessTable, + ProtocolWitnessTableAccessor, + ProtocolWitnessTablePattern, + ReabstractionThunk, + ReabstractionThunkHelper, + [Context] + ReadAccessor, + RelatedEntityDeclName, + RetroactiveConformance, + ReturnType, + Shared, + Owned, + SILBoxType, + SILBoxTypeWithLayout, + SILBoxLayout, + SILBoxMutableField, + SILBoxImmutableField, + [Context] + Setter, + SpecializationPassID, + SpecializationIsFragile, + [Context] + Static, + [Context] + Structure, + [Context] + Subscript, + Suffix, + ThinFunctionType, + Tuple, + TupleElement, + TupleElementName, + Type, + [Context] + TypeSymbolicReference, + [Context] + TypeAlias, + TypeList, + TypeMangling, + TypeMetadata, + TypeMetadataAccessFunction, + TypeMetadataCompletionFunction, + TypeMetadataInstantiationCache, + TypeMetadataInstantiationFunction, + TypeMetadataSingletonInitializationCache, + TypeMetadataLazyCache, + Unowned, + UncurriedFunctionType, + Weak, + + Unmanaged, + [Context] + UnsafeAddressor, + [Context] + UnsafeMutableAddressor, + ValueWitness, + ValueWitnessTable, + [Context] + Variable, + VTableThunk, + VTableAttribute, // note: old mangling only + [Context] + WillSet, + ReflectionMetadataBuiltinDescriptor, + ReflectionMetadataFieldDescriptor, + ReflectionMetadataAssocTypeDescriptor, + ReflectionMetadataSuperclassDescriptor, + GenericTypeParamDecl, + CurryThunk, + DispatchThunk, + MethodDescriptor, + ProtocolRequirementsBaseDescriptor, + AssociatedConformanceDescriptor, + DefaultAssociatedConformanceAccessor, + BaseConformanceDescriptor, + AssociatedTypeDescriptor, + ThrowsAnnotation, + EmptyList, + FirstElementMarker, + VariadicMarker, + OutlinedBridgedMethod, + OutlinedCopy, + OutlinedConsume, + OutlinedRetain, + OutlinedRelease, + OutlinedInitializeWithTake, + OutlinedInitializeWithCopy, + OutlinedAssignWithTake, + OutlinedAssignWithCopy, + OutlinedDestroy, + OutlinedVariable, + AssocTypePath, + LabelList, + ModuleDescriptor, + ExtensionDescriptor, + AnonymousDescriptor, + AssociatedTypeGenericParamRef, + } + + public enum PayloadKind { + None, + Text, + Index, + } + + public enum GenericTypeKind { + Generic, + Assoc, + CompoundAssoc, + Substitution, + } + + public enum GenericConstraintKind { + Protocol, + BaseClass, + SameType, + Layout, + } + + public enum FunctionSigSpecializationParamKind : uint { + ConstantPropFunction = 0, + ConstantPropGlobal = 1, + ConstantPropInteger = 2, + ConstantPropFloat = 3, + ConstantPropString = 4, + ClosureProp = 5, + BoxToValue = 6, + BoxToStack = 7, + + // Option Set Flags use bits 6-31. This gives us 26 bits to use for option + // flags. + Dead = 1 << 6, + OwnedToGuaranteed = 1 << 7, + SROA = 1 << 8, + GuaranteedToOwned = 1 << 9, + ExistentialToGeneric = 1 << 10, + } + + public enum Directness { + Direct, + Indirect, + } + + public enum FunctionEntityArgs { + None, + Type, + TypeAndName, + TypeAndMaybePrivateName, + TypeAndIndex, + Index, + } + + public enum ValueWitnessKind { + AllocateBuffer, + AssignWithCopy, + AssignWithTake, + DeallocateBuffer, + Destroy, + DestroyBuffer, + DestroyArray, + InitializeBufferWithCopyOfBuffer, + InitializeBufferWithCopy, + InitializeWithCopy, + InitializeBufferWithTake, + InitializeWithTake, + ProjectBuffer, + InitializeBufferWithTakeOfBuffer, + InitializeArrayWithCopy, + InitializeArrayWithTakeFrontToBack, + InitializeArrayWithTakeBackToFront, + StoreExtraInhabitant, + GetExtraInhabitantIndex, + GetEnumTag, + DestructiveProjectEnumData, + DestructiveInjectEnumTag, + GetEnumTagSinglePayload, + StoreEnumTagSinglePayload + } + + public enum MatchNodeContentType { + None, + Index, + Text, + AlwaysMatch, + } + + public enum SymbolicReferenceKind { + Context, + } +} diff --git a/src/SwiftReflector/Demangling/MatchRule.cs b/src/SwiftReflector/Demangling/MatchRule.cs new file mode 100644 index 000000000000..7838a49541bd --- /dev/null +++ b/src/SwiftReflector/Demangling/MatchRule.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Demangling { + public class MatchRule { + public MatchRule () + { + Name = ""; + NodeKind = NodeKind.Type; // arbitrary + MatchContent = MatchNodeContentType.AlwaysMatch; + ChildRules = new List (); + MatchChildCount = false; + Reducer = (n, b, name) => null; + } + + public string Name { get; set; } + public NodeKind NodeKind { + get { + if (NodeKindList.Count != 1) + throw new InvalidOperationException ($"NodeKind is invalid when NodeKindList has {NodeKindList.Count} entries."); + return NodeKindList [0]; + } + set { + NodeKindList = new List { value }; + } + } + public List NodeKindList { get; set; } + public MatchNodeContentType MatchContent { get; set; } + public List ChildRules { get; set; } + public bool MatchChildCount { get; set; } + public Func Reducer { get; set; } + + + public bool Matches(Node n) + { + Exceptions.ThrowOnNull (n, nameof (n)); + // 3 match criteria: NodeKind, Content type, children + return NodeKindMatches (n) && ContentMatches (n) && + ChildrenMatches (n); + } + + bool NodeKindMatches(Node n) + { + return NodeKindList.Contains (n.Kind); + } + + bool ContentMatches(Node n) + { + // Only care about the content type not its value + switch (MatchContent) + { + case MatchNodeContentType.AlwaysMatch: + return true; + case MatchNodeContentType.Index: + return n.HasIndex; + case MatchNodeContentType.Text: + return n.HasText; + case MatchNodeContentType.None: + return !n.HasIndex && !n.HasText; + default: + throw new InvalidOperationException ($"Unknown match instruction {MatchContent} in match rule."); + } + } + + bool ChildrenMatches (Node n) + { + // if the rule says the child count matters, apply + if (MatchChildCount && n.Children.Count != ChildRules.Count) + return false; + + // match up to the minimum of each list + // if MatchChileCount is true, min is the size of both lists + int minimumChildCount = Math.Min (n.Children.Count, ChildRules.Count); + for (var i = 0; i < minimumChildCount; i++) { + var childRule = ChildRules [i]; + // recurse + if (!childRule.Matches (n.Children [i])) + return false; + } + return true; + } + + public override string ToString() + { + return Name; + } + } +} diff --git a/src/SwiftReflector/Demangling/Node.cs b/src/SwiftReflector/Demangling/Node.cs new file mode 100644 index 000000000000..8e1a030a84d1 --- /dev/null +++ b/src/SwiftReflector/Demangling/Node.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SwiftReflector.Demangling { + public class Node { + Node (NodeKind kind, PayloadKind payload) + { + Kind = kind; + PayloadKind = payload; + Children = new List (); + } + + public Node (NodeKind kind) + : this (kind, PayloadKind.None) + { + } + + public Node (NodeKind kind, string text) + : this (kind, PayloadKind.Text) + { + stringPayload = text; + } + + public Node (NodeKind kind, long index) + : this (kind, PayloadKind.Index) + { + indexPayload = index; + } + + string stringPayload = null; + long indexPayload = 0; + + public List Children { get; private set; } + + public NodeKind Kind { get; private set; } + public PayloadKind PayloadKind { get; private set; } + + public bool HasText { get { return PayloadKind == PayloadKind.Text; } } + public string Text { + get { + if (!HasText) + throw new InvalidOperationException ($"Expected a text payload, but this has a {PayloadKind} payload"); + return stringPayload; + } + } + + public bool HasIndex { get { return PayloadKind == PayloadKind.Index; } } + public long Index { + get { + if (!HasIndex) + throw new InvalidOperationException ($"Expected an index payload, but this has a {PayloadKind} payload"); + return indexPayload; + } + } + + public void AddChild (Node child) + { + Children.Add (child); + } + + public void RemoveChildAt(int pos) + { + Children.RemoveAt (pos); + } + + public void ReverseChildren (int startingAt = 0) + { + var last = Children.Count - 1; + if (startingAt < 0 || startingAt > Children.Count) + throw new ArgumentOutOfRangeException (nameof (startingAt)); + while (startingAt < last) { + Node temp = Children [startingAt]; + Children [startingAt] = Children [last]; + Children [last] = temp; + startingAt++; + last--; + } + } + + + public static bool IsDeclName (NodeKind kind) + { + switch (kind) { + case NodeKind.Identifier: + case NodeKind.LocalDeclName: + case NodeKind.PrivateDeclName: + case NodeKind.RelatedEntityDeclName: + case NodeKind.PrefixOperator: + case NodeKind.PostfixOperator: + case NodeKind.InfixOperator: + case NodeKind.TypeSymbolicReference: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + public static bool IsContext (NodeKind kind) + { + var type = typeof (NodeKind); + var memberInfo = type.GetMember (kind.ToString ()); + var attrs = memberInfo [0].GetCustomAttributes (typeof (ContextAttribute), false); + return attrs != null && attrs.Length == 1; + } + + public static bool IsAnyGeneric (NodeKind kind) + { + switch (kind) { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + case NodeKind.OtherNominalType: + case NodeKind.TypeAlias: + case NodeKind.TypeSymbolicReference: + return true; + default: + return false; + } + } + + public static bool IsNominal (NodeKind kind) + { + switch (kind) { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + return true; + default: + return false; + } + } + + public static bool IsEntity (NodeKind kind) + { + if (kind == NodeKind.Type) + return true; + return IsContext (kind); + } + + public static bool IsRequirement (NodeKind kind) + { + switch (kind) { + case NodeKind.DependentGenericSameTypeRequirement: + case NodeKind.DependentGenericLayoutRequirement: + case NodeKind.DependentGenericConformanceRequirement: + return true; + default: + return false; + } + } + + public static bool IsFunctionAttribute (NodeKind kind) + { + switch (kind) { + case NodeKind.FunctionSignatureSpecialization: + case NodeKind.GenericSpecialization: + case NodeKind.InlinedGenericFunction: + case NodeKind.GenericSpecializationNotReAbstracted: + case NodeKind.GenericPartialSpecialization: + case NodeKind.GenericPartialSpecializationNotReAbstracted: + case NodeKind.ObjCAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.DirectMethodReferenceAttribute: + case NodeKind.VTableAttribute: + case NodeKind.PartialApplyForwarder: + case NodeKind.PartialApplyObjCForwarder: + case NodeKind.OutlinedVariable: + case NodeKind.OutlinedBridgedMethod: + case NodeKind.MergedFunction: + case NodeKind.DynamicallyReplaceableFunctionImpl: + case NodeKind.DynamicallyReplaceableFunctionKey: + case NodeKind.DynamicallyReplaceableFunctionVar: + return true; + default: + return false; + } + } + + public override string ToString () + { + var sb = new StringBuilder (); + ToString (0, sb); + return sb.ToString (); + } + + void ToString (int indent, StringBuilder sb) + { + for (int i = 0; i < indent; i++) { + sb.Append (' '); + } + sb.Append ("->").Append (Kind.ToString ()); + switch (PayloadKind) { + case PayloadKind.None: + sb.Append (Environment.NewLine); + break; + case PayloadKind.Index: + sb.Append ($" ({Index})\n"); + break; + case PayloadKind.Text: + sb.Append ($" (\"{Text}\")\n"); + break; + } + foreach (var node in Children) { + node.ToString (indent + 2, sb); + } + } + + public bool IsAttribute () + { + switch (Kind) { + case NodeKind.ObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.ImplFunctionAttribute: + case NodeKind.DirectMethodReferenceAttribute: + return true; + default: + return false; + } + } + + public SwiftTypeAttribute ExtractAttribute () + { + switch (Kind) { + case NodeKind.ObjCAttribute: return SwiftTypeAttribute.ObjC; + case NodeKind.DynamicAttribute: return SwiftTypeAttribute.Dynamic; + case NodeKind.NonObjCAttribute: return SwiftTypeAttribute.NonObjC; + case NodeKind.ImplFunctionAttribute: return SwiftTypeAttribute.ImplFunction; + case NodeKind.DirectMethodReferenceAttribute: return SwiftTypeAttribute.DirectMethodReference; + default: + throw new NotSupportedException ($"{Kind} is not an attribute"); + } + } + } +} diff --git a/src/SwiftReflector/Demangling/RuleRunner.cs b/src/SwiftReflector/Demangling/RuleRunner.cs new file mode 100644 index 000000000000..380d1c3dfe26 --- /dev/null +++ b/src/SwiftReflector/Demangling/RuleRunner.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SwiftReflector.Demangling { + public class RuleRunner { + List rules = new List (); + public RuleRunner (IEnumerable rules) + { + this.rules.AddRange (rules); + } + + public SwiftType RunRules(Node node, bool isReference, SwiftName name) + { + var rule = rules.FirstOrDefault (r => r.Matches (node)); + + return rule != null ? rule.Reducer (node, isReference, name) : null; + } + } +} diff --git a/src/SwiftReflector/Demangling/Swift4Demangler.cs b/src/SwiftReflector/Demangling/Swift4Demangler.cs new file mode 100644 index 000000000000..cd5a071cb498 --- /dev/null +++ b/src/SwiftReflector/Demangling/Swift4Demangler.cs @@ -0,0 +1,1814 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; +using SwiftReflector.ExceptionTools; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Demangling { + public class Swift4Demangler { + public const int kMaxRepeatCount = 2048; + ulong offset; + string originalIdentifier; + Stack nodeStack = new Stack (); + List substitutions = new List (); + List pendingSubstitutions = new List (); + List words = new List (); + StringSlice slice; + + public Swift4Demangler (string swiftIdentifier, ulong offset = 0) + { + Exceptions.ThrowOnNull (swiftIdentifier, nameof (swiftIdentifier)); + if (!swiftIdentifier.StartsWith (Decomposer.kSwift4ID, StringComparison.Ordinal)) + throw new ArgumentOutOfRangeException (nameof (swiftIdentifier), $"Expecting '{swiftIdentifier}' to start with '{Decomposer.kSwift4ID}'"); + this.offset = offset; + originalIdentifier = swiftIdentifier; + slice = new StringSlice (originalIdentifier); + slice.Advance (Decomposer.kSwift4ID.Length); + } + + public TLDefinition Run() + { + Node topLevelNode = DemangleType (); + if (topLevelNode != null && topLevelNode.IsAttribute() && nodeStack.Count >= 1) { + var attribute = topLevelNode.ExtractAttribute (); + var tld = Run (); + if (tld != null && tld is TLFunction tlf) { + tlf.Signature.Attributes.Add (attribute); + } + return tld; + } else { + Swift4NodeToTLDefinition converter = new Swift4NodeToTLDefinition (originalIdentifier, offset); + return converter.Convert (topLevelNode); + } + } + + public string ExplodedView() + { + Node topLevelNode = DemangleType (); + return topLevelNode != null ? topLevelNode.ToString () : null; + } + + Node DemangleType() + { + if (!ParseAndPushNodes ()) + throw ErrorHelper.CreateError (ReflectorError.kDecomposeBase + 2, $"Error decomposing {slice.Original} at {slice.Position}"); + var node = PopNode (); + if (node != null) + return node; + return new Node (NodeKind.Suffix, slice.Original); + } + + bool ParseAndPushNodes() + { + while (!slice.IsAtEnd) { + var node = DemangleOperator (); + if (node == null) + return false; + PushNode (node); + } + return true; + } + + bool NextIf (string str) + { + if (slice.StartsWith (str)) { + slice.Advance (str.Length); + return true; + } + return false; + + } + + char PeekChar () + { + if (slice.IsAtEnd) + return (char)0; + return slice.Current; + } + + char NextChar () + { + return slice.Advance (); + } + + bool NextIf (char c) + { + return slice.AdvanceIfEquals (c); + } + + void PushBack () + { + slice.Rewind (); + } + + string ConsumeAll () + { + return slice.ConsumeRemaining (); + } + + void PushNode (Node node) + { + nodeStack.Push (node); + } + + Node PopNode () + { + if (nodeStack.Count == 0) + return null; + return nodeStack.Pop (); + } + + Node PopNode (NodeKind kind) + { + if (nodeStack.Count == 0) + return null; + if (kind != nodeStack.Peek ().Kind) + return null; + return PopNode (); + } + + Node PopNode (Predicate pred) + { + if (nodeStack.Count == 0) + return null; + if (!pred (nodeStack.Peek ().Kind)) + return null; + return PopNode (); + } + + void AddSubstitution (Node nd) + { + if (nd != null) + substitutions.Add (nd); + } + + Node AddChild (Node parent, Node child) + { + if (parent == null || child == null) + return null; + parent.Children.Add (child); + return parent; + } + + Node CreateWithChild (NodeKind kind, Node child) + { + if (child == null) + return null; + var node = new Node (kind); + node.Children.Add (child); + return node; + } + + Node CreateType (Node child) + { + return CreateWithChild (NodeKind.Type, child); + } + + Node CreateWithChildren (NodeKind kind, params Node [] children) + { + foreach (var nd in children) + if (nd == null) + throw new ArgumentOutOfRangeException (nameof (children)); + var node = new Node (kind); + node.Children.AddRange (children); + return node; + } + + Node CreateWithPoppedType(NodeKind kind) + { + return CreateWithChild (kind, PopNode (NodeKind.Type)); + } + + Node ChangeKind (Node node, NodeKind newKind) + { + Node newNode = null; + if (node.HasText) { + newNode = new Node (node.Kind, node.Text); + } else if (node.HasIndex) { + newNode = new Node (node.Kind, node.Index); + } else { + newNode = new Node (node.Kind); + } + newNode.Children.AddRange (node.Children); + return newNode; + } + + Node DemangleOperator () + { + var c = NextChar (); + switch (c) { + case 'A': return DemangleMultiSubstitutions (); + case 'B': return DemangleBuiltinType (); + case 'C': return DemangleAnyGenericType (NodeKind.Class); + case 'D': return CreateWithChild (NodeKind.TypeMangling, PopNode (NodeKind.Type)); + case 'E': return DemangleExtensionContext (); + case 'F': return DemanglePlainFunction (); + case 'G': return DemangleBoundGenericType (); + case 'I': return DemangleImplFunctionType (); + case 'K': return new Node (NodeKind.ThrowsAnnotation); + case 'L': return DemangleLocalIdentifier (); + case 'M': return DemangleMetatype (); + case 'N': return CreateWithChild (NodeKind.TypeMetadata, PopNode (NodeKind.Type)); + case 'O': return DemangleAnyGenericType (NodeKind.Enum); + case 'P': return DemangleAnyGenericType (NodeKind.Protocol); + case 'Q': return DemangleArchetype (); + case 'R': return DemangleGenericRequirement (); + case 'S': return DemangleStandardSubstitution (); + case 'T': return DemangleThunkOrSpecialization (); + case 'V': return DemangleAnyGenericType (NodeKind.Structure); + case 'W': return DemangleWitness (); + case 'X': return DemangleSpecialType (); + case 'Z': return CreateWithChild (NodeKind.Static, PopNode (Node.IsEntity)); + case 'a': return DemangleAnyGenericType (NodeKind.TypeAlias); + case 'c': return PopFunctionType (NodeKind.FunctionType); + case 'd': return new Node (NodeKind.VariadicMarker); + case 'f': return DemangleFunctionEntity (); + case 'i': return DemangleEntity (NodeKind.Subscript); + case 'l': return DemangleGenericSignature (false); + case 'm': return CreateType (CreateWithChild (NodeKind.Metatype, PopNode (NodeKind.Type))); + case 'o': return DemangleOperatorIdentifier (); + case 'p': return DemangleProtocolListType (); + case 'q': return CreateType (DemangleGenericParamIndex ()); + case 'r': return DemangleGenericSignature (true); + case 's': return new Node (NodeKind.Module, "Swift"); + case 't': return PopTuple (); + case 'u': return DemangleGenericType (); + case 'v': return DemangleEntity (NodeKind.Variable); + case 'w': return DemangleValueWitness (); + case 'x': return CreateType (GetDependentGenericParamType (0, 0)); + case 'y': return new Node (NodeKind.EmptyList); + case 'z': return CreateType (CreateWithChild (NodeKind.InOut, PopTypeAndGetChild ())); + case '_': return new Node (NodeKind.FirstElementMarker); + case '.': + PushBack (); + return new Node (NodeKind.Suffix, ConsumeAll ()); + default: + PushBack (); + return DemangleIdentifier (); + } + } + + Node DemangleLocalIdentifier() + { + if (NextIf('L')) { + var adiscriminator = PopNode (NodeKind.Identifier); + var aname = PopNode (Node.IsDeclName); + return CreateWithChildren (NodeKind.PrivateDeclName, adiscriminator, aname); + } + if (NextIf('l')) { + var adiscriminator = PopNode (NodeKind.Identifier); + return CreateWithChild (NodeKind.PrivateDeclName, adiscriminator); + } + var discriminator = DemangleIndexAsNode (); + var name = PopNode (Node.IsDeclName); + return CreateWithChildren (NodeKind.LocalDeclName, discriminator, name); + } + + Node PopModule() + { + var ident = PopNode (NodeKind.Identifier); + if (ident != null) + return ChangeKind (ident, NodeKind.Module); + return PopNode (NodeKind.Module); + } + + Node PopContext() + { + var mod = PopModule (); + if (mod != null) + return mod; + Node ty = PopNode (NodeKind.Type); + if (ty != null) { + if (ty.Children.Count != 1) + return null; + var child = ty.Children [0]; + if (!Node.IsContext (child.Kind)) + return null; + return child; + } + return PopNode (Node.IsContext); + } + + Node PopTypeAndGetChild () + { + Node ty = PopNode (NodeKind.Type); + if (ty == null || ty.Children.Count != 1) + return null; + return ty.Children [0]; + } + + Node PopTypeAndGetNominal() + { + var child = PopTypeAndGetChild (); + if (child != null && Node.IsNominal (child.Kind)) + return child; + return null; + } + + Node DemangleBuiltinType() + { + Node ty = null; + switch (NextChar ()) { + case 'b': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); + break; + case 'B': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); + break; + case 'f': { + int size = DemangleIndex () - 1; + if (size <= 0) + return null; + string name = $"Builtin.Float{size}"; + ty = new Node (NodeKind.BuiltinTypeName, name); + break; + } + case 'i': { + int size = DemangleIndex () - 1; + if (size <= 0) + return null; + string name = $"Builtin.Int{size}"; + ty = new Node (NodeKind.BuiltinTypeName, name); + break; + } + case 'v': { + int elts = DemangleIndex () - 1; + if (elts <= 0) + return null; + Node eltType = PopTypeAndGetChild (); + if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || + !eltType.Text.StartsWith ("Builtin.", StringComparison.Ordinal)) + return null; + string name = $"Builtin.Vec{elts}x{eltType.Text.Substring ("Builtin.".Length)}"; + ty = new Node (NodeKind.BuiltinTypeName, name); + break; + } + case 'O': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); + break; + case 'o': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.NativeObject"); + break; + case 'p': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.RawPointer"); + break; + case 'w': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.Word"); + break; + default: + return null; + } + return CreateType (ty); + } + + Node DemangleAnyGenericType(NodeKind kind) + { + var name = PopNode (Node.IsDeclName); + var ctx = PopContext (); + var nty = CreateType (CreateWithChildren (kind, ctx, name)); + AddSubstitution (nty); + return nty; + } + + Node DemangleExtensionContext() + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var module = PopModule (); + var type = PopTypeAndGetNominal (); + var ext = CreateWithChildren (NodeKind.Extension, module, type); + if (genSig != null) + ext = AddChild (ext, genSig); + return ext; + } + + Node DemanglePlainFunction() + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var type = PopFunctionType (NodeKind.FunctionType); + if (genSig != null) + type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); + var name = PopNode (Node.IsDeclName); + var ctx = PopContext (); + return CreateWithChildren (NodeKind.Function, ctx, name, type); + } + + Node PopFunctionType(NodeKind kind) + { + var funcType = new Node (kind); + AddChild (funcType, PopNode (NodeKind.ThrowsAnnotation)); + funcType = AddChild (funcType, PopFunctionParams (NodeKind.ArgumentTuple)); + funcType = AddChild (funcType, PopFunctionParams (NodeKind.ReturnType)); + return CreateType (funcType); + } + + Node PopFunctionParams(NodeKind kind) + { + Node parmsType = null; + if (PopNode(NodeKind.EmptyList) != null) { + parmsType = CreateType (new Node (NodeKind.Tuple)); + } else { + parmsType = PopNode (NodeKind.Type); + } + return CreateWithChild (kind, parmsType); + } + + Node PopTuple() + { + var root = new Node (NodeKind.Tuple); + + if (PopNode(NodeKind.EmptyList) == null) { + bool firstElem = false; + do { + firstElem = PopNode (NodeKind.FirstElementMarker) != null; + var tupleElmt = new Node (NodeKind.TupleElement); + AddChild (tupleElmt, PopNode (NodeKind.VariadicMarker)); + Node ident = null; + if ((ident = PopNode (NodeKind.Identifier)) != null) { + tupleElmt.Children.Add (new Node (NodeKind.TupleElementName, ident.Text)); + } + var ty = PopNode (NodeKind.Type); + if (ty == null) + return null; + tupleElmt.Children.Add (ty); + root.Children.Add (tupleElmt); + } while (!firstElem); + root.ReverseChildren (); + } + return CreateType (root); + } + + + Node DemangleMultiSubstitutions () + { + var repeatCount = -1; + while (true) { + var c = NextChar (); + if (c == 0) { + return null; + } + if (Char.IsLower (c)) { + Node nd = PushMultiSubstitutions (repeatCount, c - 'a'); + if (nd == null) + return null; + PushNode (nd); + repeatCount = -1; + continue; + } + if (Char.IsUpper (c)) { + return PushMultiSubstitutions (repeatCount, c - 'A'); + } + if (c == '_') { + var index = repeatCount + 27; + if (index >= substitutions.Count) + return null; + return substitutions [index]; + } + PushBack (); + repeatCount = DemangleNatural (); + if (repeatCount < 0) + return null; + } + } + + int DemangleNatural() + { + if (!Char.IsDigit (PeekChar ())) + return -1000; + int num = 0; + while (true) { + var c = PeekChar (); + if (!Char.IsDigit (c)) + return num; + int newNum = (10 * num) + (c - '0'); + if (newNum < num) + return -1000; + num = newNum; + NextChar (); + } + } + + int DemangleIndex() + { + if (NextIf ('_')) + return 0; + int num = DemangleNatural (); + if (num >= 0 && NextIf ('_')) + return num + 1; + return -1000; + } + + Node DemangleIndexAsNode() + { + int idx = DemangleIndex (); + if (idx >= 0) + return new Node (NodeKind.Number, idx); + return null; + } + + Node PushMultiSubstitutions(int repeatCount, int index) + { + if (index >= substitutions.Count) + return null; + if (repeatCount > kMaxRepeatCount) + return null; + Node nd = substitutions [index]; + while (repeatCount-- > 1) { + PushNode (nd); + } + return nd; + } + + Node CreateSwiftType(NodeKind typeKind, string name) { + return CreateType (CreateWithChildren (typeKind, + new Node (NodeKind.Module, "Swift"), + new Node (NodeKind.Identifier, name))); + } + + Node DemangleStandardSubstitution() + { + char c = NextChar (); + switch(c) { + case 'o': + return new Node (NodeKind.Module, "__ObjC"); + case 'C': + return new Node (NodeKind.Module, "__C"); + case 'g': { + var optionalTy = CreateType (CreateWithChildren (NodeKind.BoundGenericEnum, + CreateSwiftType (NodeKind.Enum, "Optional"), + CreateWithChild (NodeKind.TypeList, PopNode (NodeKind.Type)))); + AddSubstitution (optionalTy); + return optionalTy; + } + default: { + PushBack (); + var repeatCount = DemangleNatural (); + if (repeatCount > kMaxRepeatCount) + return null; + var nd = CreateStandardSubstitution (NextChar ()); + if (nd != null) { + while (repeatCount-- > 1) { + PushNode (nd); + } + return nd; + } + return null; + } + } + } + + Node CreateStandardSubstitution(char subst) + { + var kind = NodeKind.Structure; // most common + string name = null; + switch (subst) { + case 'a': name = "Array"; break; + case 'b': name = "Bool"; break; + case 'c': name = "UnicodeScalar"; break; + case 'd': name = "Double"; break; + case 'f': name = "Float"; break; + case 'i': name = "Int"; break; + case 'V': name = "UnsafeRawPointer"; break; + case 'v': name = "UnsafeMutableRawPointer"; break; + case 'P': name = "UnsafePointer"; break; + case 'p': name = "UnsafeMutablePointer"; break; + case 'R': name = "UnsafeBufferPointer"; break; + case 'r': name = "UnsafeMutableBufferPointer"; break; + case 'S': name = "String"; break; + case 'u': name = "UInt"; break; + case 'q': name = "Optional"; kind = NodeKind.Enum; break; + case 'Q': name = "ImplicitlyUnwrappedOptional"; kind = NodeKind.Enum; break; + default: return null; + } + return CreateSwiftType (kind, name); + } + + Node DemangleIdentifier() + { + var hasWordSubsts = false; + var isPunycoded = false; + var c = PeekChar (); + if (!Char.IsDigit (c)) + return null; + if (c == '0') { + NextChar (); + if (PeekChar() == '0') { + NextChar (); + isPunycoded = true; + } else { + hasWordSubsts = true; + } + } + var identifier = new StringBuilder (); + do { + while (hasWordSubsts && Char.IsLetter (PeekChar ())) { + var cc = NextChar (); + var wordIdx = 0; + if (Char.IsLower (cc)) { + wordIdx = cc - 'a'; + } else { + wordIdx = cc - 'A'; + hasWordSubsts = false; + } + if (wordIdx >= words.Count) + return null; + string piece0 = words [wordIdx]; + identifier.Append (piece0); + } + if (NextIf ('0')) + break; + var numChars = DemangleNatural (); + if (numChars <= 0) + return null; + if (isPunycoded) + NextIf ('_'); + if (numChars > slice.Length) + return null; + string piece = slice.Substring (slice.Position, numChars); + if (isPunycoded) { + PunyCode puny = new PunyCode (); + string punyCodedString = puny.Decode (piece); + identifier.Append (punyCodedString); + } else { + identifier.Append (piece); + var wordStartPos = -1; + for (int idx = 0; idx <= piece.Length; idx++) { + char ccc = idx < piece.Length ? piece [idx] : (char)0; + if (wordStartPos >= 0 && IsWordEnd (ccc, piece [idx - 1])) { + if (idx - wordStartPos >= 2 && words.Count < 26) { + var word = piece.Substring (wordStartPos, idx - wordStartPos); + words.Add (word); + } + wordStartPos = -1; + } + if (wordStartPos < 0 && IsWordStart(ccc)) { + wordStartPos = idx; + } + } + } + slice.Advance (numChars); + } while (hasWordSubsts); + if (identifier.Length == 0) + return null; + var ident = new Node (NodeKind.Identifier, identifier.ToString()); + AddSubstitution (ident); + return ident; + } + + bool IsWordStart(char ch) { + return !Char.IsDigit (ch) && ch != '_' && ch != (char)0; + } + + bool IsWordEnd(char ch, char prevCh) + { + if (ch == '_' || ch == (char)0) + return true; + if (!Char.IsUpper (prevCh) && Char.IsUpper (ch)) + return true; + return false; + } + Node DemangleOperatorIdentifier() + { + var ident = PopNode (NodeKind.Identifier); + if (ident == null) + return null; + var op_char_table = "& @/= > <*!|+?%-~ ^ ."; + StringBuilder opStr = new StringBuilder (); + foreach (var c in ident.Text) { + if (c > 0x7f) { + opStr.Append (c); + continue; + } + if (!Char.IsLower (c)) + return null; + char o = op_char_table [c - 'a']; + if (o == ' ') + return null; + opStr.Append (o); + } + switch (NextChar()) { + case 'i': return new Node (NodeKind.InfixOperator, opStr.ToString ()); + case 'p': return new Node (NodeKind.PrefixOperator, opStr.ToString ()); + case 'P': return new Node (NodeKind.PostfixOperator, opStr.ToString ()); + default: return null; + } + } + + Node PopTypeList() + { + var root = new Node (NodeKind.TypeList); + if (PopNode(NodeKind.EmptyList) == null) { + bool firstElem = false; + do { + firstElem = PopNode (NodeKind.FirstElementMarker) != null; + var ty = PopNode (NodeKind.Type); + if (ty == null) + return null; + root.Children.Add (ty); + } while (!firstElem); + root.ReverseChildren (); + } + return root; + } + + Node PopProtocol() + { + var name = PopNode (Node.IsDeclName); + var ctx = PopContext (); + var proto = CreateWithChildren (NodeKind.Protocol, ctx, name); + return CreateType (proto); + } + + Node DemangleBoundGenericType() + { + var typeListList = new List (4); + while (true) { + var tlist = new Node (NodeKind.TypeList); + typeListList.Add (tlist); + Node ty = null; + while ((ty = PopNode(NodeKind.Type)) != null) { + tlist.Children.Add (ty); + } + tlist.ReverseChildren (); + if (PopNode (NodeKind.EmptyList) != null) + break; + if (PopNode (NodeKind.FirstElementMarker) == null) + return null; + } + var nominal = PopTypeAndGetNominal (); + var nty = CreateType (DemangleBoundGenericArgs (nominal, typeListList, 0)); + AddSubstitution (nty); + return nty; + } + + Node DemangleBoundGenericArgs(Node nominal, List typeLists, int typeListIdx) + { + if (nominal == null || nominal.Children.Count < 2) + return null; + + if (typeListIdx >= typeLists.Count) + return null; + var args = typeLists [typeListIdx++]; + + var context = nominal.Children [0]; + + if (typeListIdx < typeLists.Count) { + Node boundParent = null; + if (context.Kind == NodeKind.Extension) { + boundParent = DemangleBoundGenericArgs (context.Children [1], typeLists, typeListIdx); + boundParent = CreateWithChildren (NodeKind.Extension, context.Children [0], boundParent); + + if (context.Children.Count == 3) { + AddChild (boundParent, context.Children [2]); + } + + } else { + boundParent = DemangleBoundGenericArgs (context, typeLists, typeListIdx); + } + nominal = CreateWithChildren (nominal.Kind, boundParent, nominal.Children [1]); + if (nominal == null) + return null; + } + + if (args.Children.Count == 0) + return nominal; + + NodeKind kind = NodeKind.Type; // arbitrary + switch (nominal.Kind) { + case NodeKind.Class: + kind = NodeKind.BoundGenericClass; + break; + case NodeKind.Structure: + kind = NodeKind.BoundGenericStructure; + break; + case NodeKind.Enum: + kind = NodeKind.BoundGenericEnum; + break; + default: + return null; + } + return CreateWithChildren (kind, CreateType (nominal), args); + } + + Node DemangleImplParamConvention() + { + string attr = null; + switch (NextChar ()) { + case 'i': attr = "@in"; break; + case 'c': attr = "@in_constant"; break; + case 'l': attr = "@inout"; break; + case 'b': attr = "@inout_aliasable"; break; + case 'n': attr = "@in_guaranteed"; break; + case 'x': attr = "@owned"; break; + case 'g': attr = "@guaranteed"; break; + case 'e': attr = "@deallocating"; break; + case 'y': attr = "@unowned"; break; + default: + PushBack (); + return null; + } + return CreateWithChild (NodeKind.ImplParameter, new Node (NodeKind.ImplConvention, attr)); + } + + Node DemangleImplResultConvention(NodeKind convKind) + { + string attr = null; + switch (NextChar ()) { + case 'r': attr = "@out"; break; + case 'o': attr = "@owned"; break; + case 'd': attr = "@unowned"; break; + case 'u': attr = "@unowned_inner_pointer"; break; + case 'a': attr = "@autoreleased"; break; + default: + PushBack (); + return null; + } + return CreateWithChild (convKind, new Node (NodeKind.ImplConvention, attr)); + } + + Node DemangleImplFunctionType() + { + var type = new Node (NodeKind.ImplFunctionType); + var genSig = PopNode (NodeKind.DependentGenericSignature); + if (genSig != null && NextIf ('P')) + genSig = ChangeKind (genSig, NodeKind.DependentPseudogenericSignature); + + string cAttr = null; + switch (NextChar()) { + case 'y': cAttr = "@callee_unowned"; break; + case 'g': cAttr = "@callee_guaranteed"; break; + case 'x': cAttr = "@callee_owned"; break; + case 't': cAttr = "@convention(thin)"; break; + default: + return null; + } + type.Children.Add (new Node (NodeKind.ImplConvention, cAttr)); + + string fAttr = null; + switch (NextChar ()) { + case 'B': fAttr = "@convention(block)"; break; + case 'C': fAttr = "@convention(c)"; break; + case 'M': fAttr = "@convention(method)"; break; + case 'O': fAttr = "@convention(objc_method)"; break; + case 'K': fAttr = "@convention(closure)"; break; + case 'W': fAttr = "@convention(witness_method)"; break; + default: + PushBack (); + break; + } + if (fAttr != null) + type.Children.Add (new Node (NodeKind.ImplFunctionAttribute, fAttr)); + + AddChild (type, genSig); + + int numTypesToAdd = 0; + Node parameter = null; + while ((parameter = DemangleImplParamConvention()) != null) { + type = AddChild (type, parameter); + numTypesToAdd++; + } + Node result = null; + while ((result = DemangleImplResultConvention(NodeKind.ImplResult)) != null) { + type = AddChild (type, result); + numTypesToAdd++; + } + if (NextIf('z')) { + var errorResult = DemangleImplResultConvention (NodeKind.ImplErrorResult); + if (errorResult == null) + return null; + type = AddChild (type, errorResult); + numTypesToAdd++; + } + if (!NextIf ('_')) + return null; + + for (int idx = 0; idx < numTypesToAdd; idx++) { + var convTy = PopNode (NodeKind.Type); + if (convTy == null) + return null; + type.Children [type.Children.Count - idx - 1].Children.Add (convTy); + } + return CreateType (type); + } + + Node DemangleMetatype() + { + switch (NextChar ()) { + case 'f': + return CreateWithPoppedType (NodeKind.FullTypeMetadata); + case 'P': + return CreateWithPoppedType (NodeKind.GenericTypeMetadataPattern); + case 'a': + return CreateWithPoppedType (NodeKind.TypeMetadataAccessFunction); + case 'L': + return CreateWithPoppedType (NodeKind.TypeMetadataLazyCache); + case 'm': + return CreateWithPoppedType (NodeKind.Metaclass); + case 'n': + return CreateWithPoppedType (NodeKind.NominalTypeDescriptor); + case 'p': + return CreateWithChild (NodeKind.ProtocolDescriptor, PopProtocol ()); + case 'B': + return CreateWithChild (NodeKind.ReflectionMetadataBuiltinDescriptor, PopNode (NodeKind.Type)); + case 'F': + return CreateWithChild (NodeKind.ReflectionMetadataFieldDescriptor, PopNode (NodeKind.Type)); + case 'A': + return CreateWithChild (NodeKind.ReflectionMetadataAssocTypeDescriptor, PopProtocolConformance ()); + case 'C': { + var ty = PopNode (NodeKind.Type); + if (ty == null || !Node.IsNominal (ty.Children [0].Kind)) + return null; + return CreateWithChild (NodeKind.ReflectionMetadataSuperclassDescriptor, ty.Children [0]); + } + default: + return null; + } + } + + Node DemangleArchetype() + { + switch (NextChar ()) { + case 'a': { + var ident = PopNode (NodeKind.Identifier); + var archeTy = PopTypeAndGetChild (); + var assocTy = CreateType (CreateWithChildren (NodeKind.AssociatedTypeRef, archeTy, ident)); + AddSubstitution (assocTy); + return assocTy; + } + case 'y': { + var T = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); + AddSubstitution (T); + return T; + } + case 'z': { + var T = DemangleAssociatedTypeSimple (GetDependentGenericParamType (0, 0)); + AddSubstitution (T); + return T; + } + case 'Y': { + var T = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); + AddSubstitution (T); + return T; + } + case 'Z': { + var T = DemangleAssociatedTypeCompound (GetDependentGenericParamType (0, 0)); + AddSubstitution (T); + return T; + } + + default: + return null; + } + } + + Node DemangleAssociatedTypeSimple(Node genericParamIndex) { + var GPI = CreateType (genericParamIndex); + var atName = PopAssocTypeName (); + return CreateType (CreateWithChildren (NodeKind.DependentMemberType, GPI, atName)); + } + + Node DemangleAssociatedTypeCompound(Node genericParamIdx) + { + var assocTypeNames = new List (4); + bool firstElem = false; + do { + firstElem = PopNode (NodeKind.FirstElementMarker) != null; + var assocTyName = PopAssocTypeName (); + if (assocTyName == null) + return null; + assocTypeNames.Add (assocTyName); + } while (!firstElem); + + var baseClass = genericParamIdx; + + for (int index = assocTypeNames.Count - 1; index >= 0; index--) { + var assocTy = assocTypeNames [index]; + var depTy = new Node (NodeKind.DependentMemberType); + depTy = AddChild (depTy, CreateType (baseClass)); + baseClass = AddChild (depTy, assocTy); + } + return CreateType (baseClass); + } + + + + Node PopAssocTypeName() + { + var proto = PopNode (NodeKind.Type); + if (proto != null && proto.Children [0].Kind != NodeKind.Protocol) + return null; + + var id = PopNode (NodeKind.Identifier); + var assocTy = ChangeKind (id, NodeKind.DependentAssociatedTypeRef); + AddChild (assocTy, proto); + return assocTy; + } + + Node GetDependentGenericParamType(int depth, int index) + { + if (depth < 0 || index < 0) + return null; + + StringBuilder name = new StringBuilder (); + int idxChar = index; + do { + name.Append ((char)('A' + (idxChar % 26))); + idxChar /= 26; + } while (idxChar != 0); + if (depth != 0) + name.Append (depth); + var paramTy = new Node (NodeKind.DependentGenericParamType, name.ToString ()); + paramTy.Children.Add (new Node (NodeKind.Index, depth)); + paramTy.Children.Add (new Node (NodeKind.Index, index)); + return paramTy; + } + + Node DemangleGenericParamIndex() + { + if (NextIf('d')) { + var depth = DemangleIndex () + 1; + var index = DemangleIndex (); + return GetDependentGenericParamType (depth, index); + } + if (NextIf('z')) { + return GetDependentGenericParamType (0, 0); + } + return GetDependentGenericParamType (0, DemangleIndex () + 1); + } + + + Node PopProtocolConformance() + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var module = PopModule (); + var proto = PopProtocol (); + var type = PopNode (NodeKind.Type); + Node ident = null; + if (type == null) { + ident = PopNode (NodeKind.Identifier); + type = PopNode (NodeKind.Type); + } + if (genSig != null) { + type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); + } + var conf = CreateWithChildren (NodeKind.ProtocolConformance, type, proto, module); + AddChild (conf, ident); + return conf; + } + + Node DemangleThunkOrSpecialization() + { + char c = NextChar (); + switch (c) { + case 'c': return CreateWithChild (NodeKind.CurryThunk, PopNode (Node.IsEntity)); + case 'o': return new Node (NodeKind.ObjCAttribute); + case 'O': return new Node (NodeKind.NonObjCAttribute); + case 'D': return new Node (NodeKind.DynamicAttribute); + case 'd': return new Node (NodeKind.DirectMethodReferenceAttribute); + case 'a': return new Node (NodeKind.PartialApplyObjCForwarder); + case 'A': return new Node (NodeKind.PartialApplyForwarder); + case 'm': return new Node (NodeKind.MergedFunction); + case 'V': { + var baseClass = PopNode (Node.IsEntity); + var derived = PopNode (Node.IsEntity); + return CreateWithChildren (NodeKind.VTableThunk, derived, baseClass); + } + case 'W': { + var entity = PopNode (Node.IsEntity); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.ProtocolWitness, conf, entity); + } + case 'R': + case 'r': { + var thunk = new Node (c == 'R' ? NodeKind.ReabstractionThunkHelper : NodeKind.ReabstractionThunk); + var genSig = PopNode (NodeKind.DependentGenericSignature); + if (genSig != null) { + AddChild (thunk, genSig); + } + var ty2 = PopNode (NodeKind.Type); + thunk = AddChild (thunk, PopNode (NodeKind.Type)); + return AddChild (thunk, ty2); + + } + case 'g': return DemangleGenericSpecialization (NodeKind.GenericSpecialization); + case 'G': return DemangleGenericSpecialization (NodeKind.GenericSpecializationNotReAbstracted); + case 'p': { + var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecialization); + var parameter = CreateWithChild (NodeKind.GenericSpecialization, PopNode (NodeKind.Type)); + return AddChild (spec, parameter); + } + case 'P': { + var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecializationNotReAbstracted); + var parameter = CreateWithChild (NodeKind.GenericSpecialization, PopNode (NodeKind.Type)); + return AddChild (spec, parameter); + } + case 'f': return DemangleFunctionSpecialization (); + case 'K': + case 'k': { + var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper : NodeKind.KeyPathSetterThunkHelper; + var types = new List (); + var node = PopNode (); + if (node == null || node.Kind != NodeKind.Type) + return null; + do { + types.Add (node); + node = PopNode (); + } while (node != null && node.Kind == NodeKind.Type); + Node result = null; + if (node != null) { + if (node.Kind == NodeKind.DependentGenericSignature) { + var decl = PopNode (); + result = CreateWithChildren (nodeKind, decl, node); + } else { + result = CreateWithChild (nodeKind, node); + } + } else { + return null; + } + foreach (var i in types) { + result.Children.Add (i); + } + return result; + } + case 'H': + case 'h': { + var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper : NodeKind.KeyPathHashThunkHelper; + Node genericSig = null; + var types = new List (); + var node = PopNode (); + if (node != null) { + if (node.Kind == NodeKind.DependentGenericSignature) { + genericSig = node; + } else if (node.Kind == NodeKind.Type) { + types.Add (node); + } else { + return null; + } + } else { + return null; + } + + while ((node = PopNode ()) != null) { + if (node.Kind != NodeKind.Type) { + return null; + } + types.Add (node); + } + + var result = new Node (nodeKind); + foreach (var i in types) { + result.Children.Add (i); + } + if (genericSig != null) + result.Children.Add (genericSig); + return result; + } + default: + return null; + + } + } + + Node DemangleGenericSpecialization(NodeKind specKind) + { + var spec = DemangleSpecAttributes (specKind); + if (spec == null) + return null; + var typeList = PopTypeList (); + if (typeList == null) + return null; + foreach (var ty in typeList.Children) { + spec.Children.Add (CreateWithChild (NodeKind.GenericSpecializationParam, ty)); + } + return spec; + } + + Node DemangleFunctionSpecialization() + { + var spec = DemangleSpecAttributes (NodeKind.FunctionSignatureSpecialization, true); + uint parmIdx = 0; + while (spec != null && !NextIf('_')) { + spec = AddChild (spec, DemangleFuncSpecParam (parmIdx)); + parmIdx++; + } + if (!NextIf ('n')) + spec = AddChild (spec, DemangleFuncSpecParam (~(ulong)0)); + + if (spec == null) + return null; + + for (int idx = 0, num = spec.Children.Count; idx < num; idx++) { + var param = spec.Children [num - idx - 1]; + if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) + continue; + + if (param.Children.Count == 0) + continue; + var kindNd = param.Children [0]; + var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; + + switch (paramKind) { + case FunctionSigSpecializationParamKind.ConstantPropFunction: + case FunctionSigSpecializationParamKind.ConstantPropGlobal: + case FunctionSigSpecializationParamKind.ConstantPropString: + case FunctionSigSpecializationParamKind.ClosureProp: { + int fixedChildren = param.Children.Count; + Node ty = null; + while ((ty = PopNode(NodeKind.Type)) != null) { + if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) + return null; + param = AddChild (param, ty); + } + var name = PopNode (NodeKind.Identifier); + if (name == null) + return null; + string text = name.Text; + if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && + text.Length > 0 && text[0] == '_') { + text = text.Substring (1); + } + AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, text)); + param.ReverseChildren (fixedChildren); + break; + } + default: + break; + } + } + return spec; + } + + Node DemangleFuncSpecParam(ulong paramIdx) + { + var param = new Node (NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); + switch (NextChar ()) { + case 'n': + return param; + case 'c': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ClosureProp)); + case 'p': + switch (NextChar ()) { + case 'f': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropFunction)); + case 'g': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); + case 'i': + return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropInteger); + case 'd': + return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropFloat); + case 's': { + string encoding = null; + switch (NextChar ()) { + case 'b': encoding = "u8"; break; + case 'w': encoding = "u16"; break; + case 'c': encoding = "objc"; break; + default: + return null; + } + AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropString)); + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); + } + default: + return null; + } + case 'd': { + uint value = (uint)FunctionSigSpecializationParamKind.Dead; + if (NextIf ('G')) + value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'g': { + uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'x': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.SROA)); + case 'i': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.BoxToValue)); + case 's': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.BoxToStack)); + default: + return null; + } + } + + Node AddFuncSpecParamNumber(Node param, FunctionSigSpecializationParamKind kind) + { + param.Children.Add (new Node (NodeKind.FunctionSignatureSpecializationParamKind, (long)kind)); + StringBuilder str = new StringBuilder (); + while (Char.IsDigit(PeekChar())) { + str.Append (NextChar ()); + } + if (str.Length == 0) + return null; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString())); + } + + Node DemangleSpecAttributes(NodeKind specKind, bool demangleUniqueID = false) + { + bool isFragile = NextIf ('q'); + + var passID = (int)NextChar () - '0'; + if (passID < 0 || passID > 9) + return null; + + var idx = -1; + if (demangleUniqueID) + idx = DemangleNatural (); + + Node specNd = null; + if (idx >= 0) { + specNd = new Node (specKind, idx); + } else { + specNd = new Node (specKind); + } + if (isFragile) + specNd.Children.Add (new Node (NodeKind.SpecializationIsFragile)); + specNd.Children.Add (new Node (NodeKind.SpecializationPassID, passID)); + return specNd; + } + + Node DemangleWitness() + { + switch (NextChar ()) { + case 'V': + return CreateWithChild (NodeKind.ValueWitnessTable, PopNode (NodeKind.Type)); + case 'v': { + uint directness = 0; + switch (NextChar ()) { + case 'd': directness = (uint)Directness.Direct; break; + case 'i': directness = (uint)Directness.Indirect; break; + default: return null; + } + return CreateWithChildren (NodeKind.FieldOffset, new Node (NodeKind.Directness, (long)directness), + PopNode (Node.IsEntity)); + } + case 'P': + return CreateWithChild (NodeKind.ProtocolWitnessTable, PopProtocolConformance ()); + case 'G': + return CreateWithChild (NodeKind.GenericProtocolWitnessTable, PopProtocolConformance ()); + case 'I': + return CreateWithChild (NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance ()); + case 'l': { + var conf = PopProtocolConformance (); + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.LazyProtocolWitnessTableAccessor, type, conf); + } + case 'L': { + var conf = PopProtocolConformance (); + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); + } + case 'a': + return CreateWithChild (NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance ()); + case 't': { + var name = PopNode (Node.IsDeclName); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name); + } + case 'T': { + var protoTy = PopNode (NodeKind.Type); + var name = PopNode (Node.IsDeclName); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name, protoTy); + } + case 'y': { + return CreateWithChild (NodeKind.OutlinedCopy, PopNode (NodeKind.Type)); + } + case 'e': { + return CreateWithChild (NodeKind.OutlinedConsume, PopNode (NodeKind.Type)); + } + case 'r': { + return CreateWithChild (NodeKind.OutlinedRetain, PopNode (NodeKind.Type)); + } + case 's': { + return CreateWithChild (NodeKind.OutlinedRelease, PopNode (NodeKind.Type)); + } + default: + return null; + } + } + + Node DemangleSpecialType() + { + var specialChar = NextChar (); + switch (specialChar) { + case 'f': + return PopFunctionType (NodeKind.ThinFunctionType); + case 'K': + return PopFunctionType (NodeKind.AutoClosureType); + case 'U': + return PopFunctionType (NodeKind.UncurriedFunctionType); + case 'B': + return PopFunctionType (NodeKind.ObjCBlock); + case 'C': + return PopFunctionType (NodeKind.CFunctionPointer); + case 'o': + return CreateType (CreateWithChild (NodeKind.Unowned, PopNode (NodeKind.Type))); + case 'u': + return CreateType (CreateWithChild (NodeKind.Unmanaged, PopNode (NodeKind.Type))); + case 'w': + return CreateType (CreateWithChild (NodeKind.Weak, PopNode (NodeKind.Type))); + case 'b': + return CreateType (CreateWithChild (NodeKind.SILBoxType, PopNode (NodeKind.Type))); + case 'D': + return CreateType (CreateWithChild (NodeKind.DynamicSelf, PopNode (NodeKind.Type))); + case 'M': { + var MTR = DemangleMetatypeRepresentation (); + var type = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.Metatype, MTR, type)); + } + case 'm': { + var MTR = DemangleMetatypeRepresentation (); + var type = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.ExistentialMetatype, MTR, type)); + } + case 'p': + return CreateType (CreateWithChild (NodeKind.ExistentialMetatype, PopNode (NodeKind.Type))); + case 'c': { + var superClass = PopNode (NodeKind.Type); + var protocols = DemangleProtocolList (); + return CreateType (CreateWithChildren (NodeKind.ProtocolListWithClass, protocols, superClass)); + } + case 'l': { + var protocols = DemangleProtocolList (); + return CreateType (CreateWithChild (NodeKind.ProtocolListWithAnyObject, protocols)); + } + case 'X': + case 'x': { + Node signature = null, genericArgs = null; + if (specialChar == 'X') { + signature = PopNode (NodeKind.DependentGenericSignature); + if (signature == null) + return null; + genericArgs = PopTypeList (); + if (genericArgs == null) + return null; + } + + var fieldTypes = PopTypeList (); + if (fieldTypes == null) + return null; + + var layout = new Node (NodeKind.SILBoxLayout); + for (int i = 0; i < fieldTypes.Children.Count; i++) { + var fieldType = fieldTypes.Children [i]; + var isMutable = false; + if (fieldType.Children [0].Kind == NodeKind.InOut) { + isMutable = true; + fieldType = CreateType (fieldType.Children [0].Children [0]); + } + var field = new Node (isMutable ? NodeKind.SILBoxMutableField : NodeKind.SILBoxImmutableField); + field.Children.Add (fieldType); + layout.Children.Add (field); + } + var boxTy = new Node (NodeKind.SILBoxTypeWithLayout); + boxTy.Children.Add (layout); + if (signature != null) { + boxTy.Children.Add (signature); + boxTy.Children.Add (genericArgs); + } + return CreateType (boxTy); + } + case 'e': + return CreateType (new Node (NodeKind.ErrorType)); + default: + return null; + } + } + + Node DemangleMetatypeRepresentation() + { + switch (NextChar ()) { + case 't': + return new Node (NodeKind.MetatypeRepresentation, "@thin"); + case 'T': + return new Node (NodeKind.MetatypeRepresentation, "@thick"); + case 'o': + return new Node (NodeKind.MetatypeRepresentation, "@objc_metatype"); + default: + return null; + } + } + + Node DemangleFunctionEntity() + { + var kind = NodeKind.EmptyList; + var args = FunctionEntityArgs.None; + switch (NextChar ()) { + case 'D': args = FunctionEntityArgs.None; kind = NodeKind.Deallocator; break; + case 'd': args = FunctionEntityArgs.None; kind = NodeKind.Destructor; break; + case 'E': args = FunctionEntityArgs.None; kind = NodeKind.IVarDestroyer; break; + case 'e': args = FunctionEntityArgs.None; kind = NodeKind.IVarInitializer; break; + case 'i': args = FunctionEntityArgs.None; kind = NodeKind.Initializer; break; + case 'C': args = FunctionEntityArgs.TypeAndMaybePrivateName; kind = NodeKind.Allocator; break; + case 'c': args = FunctionEntityArgs.TypeAndMaybePrivateName; kind = NodeKind.Constructor; break; + case 'g': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.Getter; break; + case 'G': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.GlobalGetter; break; + case 's': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.Setter; break; + case 'm': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.MaterializeForSet; break; + case 'w': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.WillSet; break; + case 'W': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.DidSet; break; + case 'a': { + args = FunctionEntityArgs.TypeAndName; + switch (NextChar ()) { + case 'O': kind = NodeKind.OwningMutableAddressor; break; + case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; + case 'P': kind = NodeKind.NativePinningMutableAddressor; break; + case 'u': kind = NodeKind.UnsafeMutableAddressor; break; + default: return null; + } + } + break; + case 'l': { + args = FunctionEntityArgs.TypeAndName; + switch (NextChar ()) { + case 'O': kind = NodeKind.OwningAddressor; break; + case 'o': kind = NodeKind.NativeOwningAddressor; break; + case 'p': kind = NodeKind.NativePinningAddressor; break; + case 'u': kind = NodeKind.UnsafeAddressor; break; + default: + return null; + } + } + break; + case 'U': args = FunctionEntityArgs.TypeAndIndex; kind = NodeKind.ExplicitClosure; break; + case 'u': args = FunctionEntityArgs.TypeAndIndex; kind = NodeKind.ImplicitClosure; break; + case 'A': args = FunctionEntityArgs.Index; kind = NodeKind.DefaultArgumentInitializer; break; + case 'p': return DemangleEntity (NodeKind.GenericTypeParamDecl); + default: + return null; + + } + + Node child1 = null, child2 = null; + switch (args) { + case FunctionEntityArgs.None: + break; + case FunctionEntityArgs.Type: + child1 = PopNode (NodeKind.Type); + break; + case FunctionEntityArgs.TypeAndName: + child2 = PopNode (NodeKind.Type); + child1 = PopNode (Node.IsDeclName); + break; + case FunctionEntityArgs.TypeAndMaybePrivateName: + child1 = PopNode (NodeKind.PrivateDeclName); + child2 = PopNode (NodeKind.Type); + break; + case FunctionEntityArgs.TypeAndIndex: + child1 = DemangleIndexAsNode (); + child2 = PopNode (NodeKind.Type); + break; + case FunctionEntityArgs.Index: + child1 = DemangleIndexAsNode (); + break; + } + var entity = CreateWithChild (kind, PopContext ()); + switch (args) { + case FunctionEntityArgs.None: + break; + case FunctionEntityArgs.Type: + case FunctionEntityArgs.Index: + entity = AddChild (entity, child1); + break; + case FunctionEntityArgs.TypeAndMaybePrivateName: + if (child1 != null) + entity = AddChild (entity, child1); + entity = AddChild (entity, child2); + break; + case FunctionEntityArgs.TypeAndName: + case FunctionEntityArgs.TypeAndIndex: + entity = AddChild (entity, child1); + entity = AddChild (entity, child2); + break; + } + return entity; + } + + Node DemangleEntity(NodeKind kind) + { + var type = PopNode (NodeKind.Type); + var name = PopNode (Node.IsDeclName); + var context = PopContext (); + return CreateWithChildren (kind, context, name, type); + } + + Node DemangleProtocolList() + { + var typeList = new Node (NodeKind.TypeList); + var protoList = CreateWithChild (NodeKind.ProtocolList, typeList); + if (PopNode(NodeKind.EmptyList) == null) { + bool firstElem = false; + do { + firstElem = PopNode (NodeKind.FirstElementMarker) != null; + var proto = PopProtocol (); + if (proto == null) + return null; + typeList.Children.Add (proto); + } while (!firstElem); + typeList.ReverseChildren (); + } + return protoList; + } + + Node DemangleProtocolListType() + { + var protoList = DemangleProtocolList (); + return CreateType (protoList); + } + + Node DemangleGenericSignature(bool hasParamCounts) + { + var sig = new Node (NodeKind.DependentGenericSignature); + if (hasParamCounts) { + while (!NextIf('l')) { + var count = 0; + if (!NextIf ('z')) + count = DemangleIndex () + 1; + if (count < 0) + return null; + sig.Children.Add (new Node (NodeKind.DependentGenericParamCount, count)); + } + } else { + sig.Children.Add (new Node (NodeKind.DependentGenericParamCount, 1L)); + } + if (sig.Children.Count == 0) + return null; + var numCounts = sig.Children.Count; + Node req = null; + while ((req = PopNode(Node.IsRequirement)) != null) { + sig.Children.Add (req); + } + sig.ReverseChildren (numCounts); + return sig; + } + + Node DemangleGenericRequirement() + { + GenericTypeKind typeKind = GenericTypeKind.Assoc; + GenericConstraintKind constraintKind = GenericConstraintKind.BaseClass; + + switch (NextChar ()) { + case 'c': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Assoc; break; + case 'C': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.CompoundAssoc; break; + case 'b': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Generic; break; + case 'B': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Substitution; break; + case 't': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Assoc; break; + case 'T': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.CompoundAssoc; break; + case 's': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Generic; break; + case 'S': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Substitution; break; + case 'm': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Assoc; break; + case 'M': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.CompoundAssoc; break; + case 'l': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Generic; break; + case 'L': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Substitution; break; + case 'p': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Assoc; break; + case 'P': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.CompoundAssoc; break; + case 'Q': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Substitution; break; + default: constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Generic; PushBack (); break; + } + + Node constrTy = null; + switch (typeKind) { + case GenericTypeKind.Generic: + constrTy = CreateType (DemangleGenericParamIndex ()); + break; + case GenericTypeKind.Assoc: + constrTy = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); + AddSubstitution (constrTy); + break; + case GenericTypeKind.CompoundAssoc: + constrTy = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); + AddSubstitution (constrTy); + break; + case GenericTypeKind.Substitution: + constrTy = PopNode (NodeKind.Type); + break; + } + + switch (constraintKind) { + case GenericConstraintKind.Protocol: + return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, constrTy, PopProtocol ()); + case GenericConstraintKind.BaseClass: + return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, constrTy, PopNode (NodeKind.Type)); + case GenericConstraintKind.SameType: + return CreateWithChildren (NodeKind.DependentGenericSameTypeRequirement, constrTy, PopNode (NodeKind.Type)); + case GenericConstraintKind.Layout: { + var c = NextChar (); + Node size = null; + Node alignment = null; + string name = null; + if (c == 'U') { + name = "U"; + } else if (c == 'R') { + name = "R"; + } else if (c == 'N') { + name = "N"; + } else if (c == 'C') { + name = "C"; + } else if (c == 'D') { + name = "D"; + } else if (c == 'T') { + name = "T"; + } else if (c == 'E') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + name = "E"; + } else if (c == 'e') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + name = "e"; + } else if (c == 'M') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + alignment = DemangleIndexAsNode (); + name = "M"; + } else if (c == 'm') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + name = "m"; + } else { + return null; + } + + var nameNode = new Node (NodeKind.Identifier, name); + var layoutRequirement = CreateWithChildren (NodeKind.DependentGenericLayoutRequirement, constrTy, nameNode); + if (size != null) + AddChild (layoutRequirement, size); + if (alignment != null) + AddChild (layoutRequirement, alignment); + return layoutRequirement; + } + } + return null; + } + + Node DemangleGenericType() + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var ty = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, ty)); + } + + static int DecodeValueWitnessKind(string codeStr) + { + switch (codeStr) { + case "al": return (int)ValueWitnessKind.AllocateBuffer; + case "ca": return (int)ValueWitnessKind.AssignWithCopy; + case "ta": return (int)ValueWitnessKind.AssignWithTake; + case "de": return (int)ValueWitnessKind.DeallocateBuffer; + case "xx": return (int)ValueWitnessKind.Destroy; + case "XX": return (int)ValueWitnessKind.DestroyBuffer; + case "Xx": return (int)ValueWitnessKind.DestroyArray; + case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; + case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; + case "cp": return (int)ValueWitnessKind.InitializeWithCopy; + case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; + case "tk": return (int)ValueWitnessKind.InitializeWithTake; + case "pr": return (int)ValueWitnessKind.ProjectBuffer; + case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; + case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; + case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; + case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; + case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; + case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; + case "ug": return (int)ValueWitnessKind.GetEnumTag; + case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; + case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; + default: + return -1; + } + } + + Node DemangleValueWitness() + { + char [] code = new char [2]; + code [0] = NextChar (); + code [1] = NextChar (); + var kind = DecodeValueWitnessKind (new string (code, 0, 2)); + if (kind < 0) + return null; + var vw = new Node (NodeKind.ValueWitness, (long)kind); + return AddChild (vw, PopNode (NodeKind.Type)); + } + } + +} diff --git a/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs b/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs new file mode 100644 index 000000000000..8e0b30e2a1f7 --- /dev/null +++ b/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs @@ -0,0 +1,1887 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Demangling { + public class Swift4NodeToTLDefinition { + static List nominalNodeKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure + }; + static List nominalAndProtocolNodeKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol + }; + + static List boundGenericNominalNodeKinds = new List { + NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure + }; + + static List identifierOrOperator = new List { + NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator + }; + + static List identifierOrOperatorOrPrivateDecl = new List { + NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator,NodeKind.PrivateDeclName + }; + + static List identifierOrPrivateDeclName = new List { + NodeKind.Identifier, NodeKind.PrivateDeclName + }; + string mangledName; + ulong offset; + + RuleRunner ruleRunner; + List rules; + + public Swift4NodeToTLDefinition (string mangledName, ulong offset = 0) + { + this.mangledName = mangledName; + this.offset = offset; + rules = BuildMatchRules (); + ruleRunner = new RuleRunner (rules); + } + + List BuildMatchRules () + { + return new List { + new MatchRule { + Name = "ReturnType", + NodeKind = NodeKind.ReturnType, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "ArgumentTuple", + NodeKind = NodeKind.ArgumentTuple, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "Tuple", + NodeKind = NodeKind.Tuple, + Reducer = ConvertToTuple + }, + new MatchRule { + Name = "Structure", + NodeKind = NodeKind.Structure, + Reducer = ConvertToStruct + }, + new MatchRule { + Name = "ClassEnum", + NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "Weak", + NodeKind = NodeKind.Weak, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "AutoClosure", + NodeKind = NodeKind.AutoClosureType, + Reducer = ConvertToFunctionType + }, + new MatchRule { + Name = "ProtocolList", + NodeKind = NodeKind.ProtocolList, + Reducer = ConvertToProtocolList, + ChildRules = new List { + new MatchRule { + Name = "TypeList", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "Protocol", + NodeKind = NodeKind.Protocol, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "NamedTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToNamedTupleElement, + ChildRules = new List { + new MatchRule { + Name = "NamedTupleElementName", + NodeKind = NodeKind.TupleElementName + }, + new MatchRule { + Name = "NamedTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "VariadicNamedTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToNamedTupleElement, + ChildRules = new List { + new MatchRule { + Name = "VariadicNamedTupleElementMarker", + NodeKind = NodeKind.VariadicMarker + }, + new MatchRule { + Name = "VariadicNamedTupleElementName", + NodeKind = NodeKind.TupleElementName + }, + new MatchRule { + Name = "VariadicNamedTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "VariadicMarkerTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToUnnamedTupleElement, + ChildRules = new List { + new MatchRule { + Name = "VariadicNamedTupleElementMarker", + NodeKind = NodeKind.VariadicMarker + }, + new MatchRule { + Name = "VariadicMarkerTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "TupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToUnnamedTupleElement, + ChildRules = new List { + new MatchRule { + Name = "TupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "VariadicTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToVariadicTupleElement, + ChildRules = new List { + new MatchRule { + Name = "VariadicElementType", + NodeKind = NodeKind.VariadicMarker, + }, + new MatchRule { + Name = "NamedTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "ProtocolListWithAnyObject", + NodeKind = NodeKind.ProtocolListWithAnyObject, + Reducer = ConvertToAnyObject + }, + new MatchRule { + Name = "InOutType", + NodeKind = NodeKind.Type, + Reducer = ConvertToReferenceType, + ChildRules = new List { + new MatchRule { + Name = "InOutChild", + NodeKind = NodeKind.InOut + } + } + }, + new MatchRule { + Name = "ProtocolWitnessTable", + NodeKindList = new List { + NodeKind.ProtocolWitnessTable, + NodeKind.ProtocolWitnessTableAccessor + }, + Reducer = ConvertToProtocolWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChild", + NodeKind = NodeKind.ProtocolConformance, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChildTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildProtocolTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildModuleChild", + NodeKind = NodeKind.Identifier + } + } + } + } + }, + new MatchRule { + Name = "ValueWitnessTable", + NodeKind = NodeKind.ValueWitnessTable, + Reducer = ConvertToValueWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ValueWitnessTableChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "Static", + NodeKind = NodeKind.Static, + Reducer = ConvertToStatic, + }, + new MatchRule { + Name = "UncurriedFunction", + NodeKind = NodeKind.Function, + Reducer = ConvertToMethod, + ChildRules = new List { + new MatchRule { + Name = "FunctionNominalChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "UncurriedGenericFunction", + NodeKind = NodeKind.Function, + Reducer = ConvertToMethod, + ChildRules = new List { + new MatchRule { + Name = "GenericFunctionNominalChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "GenericFunctionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "GenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "GenericFunctionTypeChildChild", + NodeKind = NodeKind.DependentGenericType + } + } + } + } + }, + new MatchRule { + Name = "Constructor", + NodeKind = NodeKind.Constructor, + Reducer = ConvertToNonAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ConstructorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "Allocator", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "Destructor", + NodeKind = NodeKind.Destructor, + Reducer = ConvertToDestructor, + ChildRules = new List { + new MatchRule { + Name = "DestructorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "Deallocator", + NodeKind = NodeKind.Deallocator, + Reducer = ConvertToDeallocator, + ChildRules = new List { + new MatchRule { + Name = "DeallocatorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "Function", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "GlobalMutableAddressor", + NodeKind = NodeKind.UnsafeMutableAddressor, + Reducer = ConvertToGlobalUnsafeMutableAddressor, + ChildRules = new List { + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "FunctionExtension", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule { + Name = "FunctionExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "FunctionExtIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "FunctionExtTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "GenericFunctionExtension", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule { + Name = "GenericFunctionExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "GenericFunctionExtensionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "GenericFunctionExtensionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "GenericFunctionExtensionTypeChildChild", + NodeKind = NodeKind.DependentGenericType + } + } + }, + } + }, + new MatchRule { + Name = "GenericFunction", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "FunctionIdentifierChild", + NodeKindList = identifierOrOperatorOrPrivateDecl, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.DependentGenericType, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + } + } + }, + } + }, + new MatchRule { + Name = "FunctionThrowsType", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionThrowsType, + ChildRules = new List { + new MatchRule { + Name = "FunctionChildThrows", + NodeKind = NodeKind.ThrowsAnnotation + }, + new MatchRule { + Name = "FunctionChildArgumentTuple", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule { + Name = "FunctionChildReturnType", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule { + Name = "FunctionType", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionType, + ChildRules = new List { + new MatchRule { + Name = "FunctionChildArgumentTuple", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule { + Name = "FunctionChildReturnType", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule { + Name = "CFunctionPointerType", + NodeKind = NodeKind.CFunctionPointer, + Reducer = ConvertToCFunctionPointerType, + ChildRules = new List { + new MatchRule { + Name = "CFunctionPointerChildArgumentTuple", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule { + Name = "CFunctionPointerChildReturnType", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule { + Name = "SubscriptGetter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToSubscriptGetter, + ChildRules = new List { + new MatchRule { + Name = "SubscriptGetterContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "SubscriptGetterIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "SubscriptGetterTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "SubscriptFunction", + NodeKind = NodeKind.FunctionType + } + } + } + } + }, + new MatchRule { + Name = "SubscriptSetter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSubscriptSetter, + ChildRules = new List { + new MatchRule { + Name = "SubscriptGetterContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "SubscriptGetterIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "SubscriptGetterTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "SubscriptFunction", + NodeKind = NodeKind.FunctionType + } + } + } + } + }, + new MatchRule { + Name = "Getter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToGetter, + ChildRules = new List { + new MatchRule { + Name = "GetterContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "GetterIdentifierChild", + NodeKindList = identifierOrPrivateDeclName + }, + new MatchRule { + Name = "GetterTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "Setter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSetter, + ChildRules = new List { + new MatchRule { + Name = "SetterContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "SetterIdentifierChild", + NodeKindList = identifierOrPrivateDeclName + }, + new MatchRule { + Name = "SetterTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "DidSet", + NodeKind = NodeKind.DidSet, + Reducer = ConvertToDidSet, + ChildRules = new List { + new MatchRule { + Name = "DidSetContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "DidSetIdentifierChild", + NodeKindList = identifierOrPrivateDeclName + }, + new MatchRule { + Name = "DidSetTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "WillSet", + NodeKind = NodeKind.WillSet, + Reducer = ConvertToWillSet, + ChildRules = new List { + new MatchRule { + Name = "WillSetContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "WillSetIdentifierChild", + NodeKindList = identifierOrPrivateDeclName + }, + new MatchRule { + Name = "WillSetTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "MaterializeForSet", + NodeKind = NodeKind.MaterializeForSet, + Reducer = ConvertToMaterializer, + ChildRules = new List { + new MatchRule { + Name = "MaterializerContextChild", + NodeKindList = nominalAndProtocolNodeKinds, + }, + new MatchRule { + Name = "MaterializerIdentifierChild", + NodeKindList = identifierOrPrivateDeclName + }, + new MatchRule { + Name = "MaterializerTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "MaterializeForSetExtension", + NodeKind = NodeKind.MaterializeForSet, + Reducer = ConvertToMaterializer, + ChildRules = new List { + new MatchRule { + Name = "MaterializeForSetExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "MaterializeForSetExtensionIdentifierChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "MaterializeForSetExtensionTypeChild", + NodeKind = NodeKind.Type, + }, + } + }, + new MatchRule { + Name = "GlobalGetter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToGlobalGetter, + ChildRules = new List { + new MatchRule { + Name = "GetterModuleChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "GetterIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "GetterTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "GlobalExtensionGetter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToGlobalGetter, + ChildRules = new List { + new MatchRule { + Name = "GetterExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "GetterExtIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "GetterExtTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "GlobalSetter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToGlobalSetter, + ChildRules = new List { + new MatchRule { + Name = "SetterModuleChild", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "SetterIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "SetterTypeChild", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "GlobalExtensionSetter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToGlobalSetter, + ChildRules = new List { + new MatchRule { + Name = "SetterExtensionModuleChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "SetterExtensionIdentifierChild", + NodeKind = NodeKind.Identifier + }, + new MatchRule { + Name = "SetterExtensionTypeChild", + NodeKind = NodeKind.Type + } + } + }, + + new MatchRule { + Name = "DependentGenericFunctionType", + NodeKind = NodeKind.DependentGenericType, + Reducer = ConvertToGenericFunction, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + }, + new MatchRule { + Name = "BoundGenericNominal", + NodeKindList = boundGenericNominalNodeKinds, + Reducer = ConvertToBoundGeneric, + ChildRules = new List { + new MatchRule { + Name = "TypeChild", + NodeKind = NodeKind.Type + }, + new MatchRule { + Name = "TypeListChild", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "Variable", + NodeKind = NodeKind.Variable, + Reducer = ConvertToVariable, + ChildRules = new List { + new MatchRule { + Name = "VariableChildContext", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "VariableChildIdentifier", + NodeKind = NodeKind.Identifier, + }, + new MatchRule { + Name = "VariableChildType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "DependentGenericParameter", + NodeKind = NodeKind.DependentGenericParamType, + Reducer = ConvertToGenericReference, + ChildRules = new List { + new MatchRule { + Name = "Depth", + NodeKind = NodeKind.Index + }, + new MatchRule { + Name = "Index", + NodeKind = NodeKind.Index + } + } + }, + new MatchRule { + Name = "DependentMemberType", + NodeKind = NodeKind.DependentMemberType, + Reducer = ConvertFirstChildToSwiftType, + ChildRules = new List { + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type + }, + } + }, + + new MatchRule { + Name = "DynamicSelf", + NodeKind = NodeKind.DynamicSelf, + Reducer = ConvertFirstChildToSwiftType, + MatchChildCount = false + }, + + new MatchRule { + Name = "ExitentialMetatype", + NodeKind = NodeKind.ExistentialMetatype, + Reducer = ConvertToMetatype, + ChildRules = new List { + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type + }, + } + }, + + // Probably should be last + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type, + Reducer = ConvertFirstChildToSwiftType, + MatchChildCount = false + } + }; + } + + public TLDefinition Convert (Node node) + { + Exceptions.ThrowOnNull (node, nameof (node)); + + + switch (node.Kind) { + case NodeKind.Type: + return Convert (node.Children [0]); + case NodeKind.Static: + return ConvertStatic (node); + case NodeKind.Function: + return ConvertFunction (node); + case NodeKind.Constructor: + case NodeKind.Allocator: + return ConvertFunctionConstructor (node); + case NodeKind.Destructor: + case NodeKind.Deallocator: + return ConvertFunctionDestructor (node); + case NodeKind.Getter: + case NodeKind.Setter: + case NodeKind.DidSet: + case NodeKind.MaterializeForSet: + case NodeKind.WillSet: + return ConvertFunctionProp (node); + case NodeKind.Variable: + return ConvertVariable (node, false); + case NodeKind.TypeMetadataAccessFunction: + return ConvertCCtor (node); + case NodeKind.TypeMetadata: + return ConvertMetadata (node); + case NodeKind.NominalTypeDescriptor: + return ConvertNominalTypeDescriptor (node); + case NodeKind.ProtocolDescriptor: + return ConvertProtocolDescriptor (node); + case NodeKind.Initializer: + return ConvertInitializer (node); + case NodeKind.TypeMetadataLazyCache: + return ConvertLazyCacheVariable (node); + case NodeKind.ProtocolWitnessTable: + case NodeKind.ProtocolWitnessTableAccessor: + case NodeKind.ValueWitnessTable: + return ConvertProtocolWitnessTable (node); + case NodeKind.FieldOffset: + return ConvertFieldOffset (node); + case NodeKind.DefaultArgumentInitializer: + return ConvertDefaultArgumentInitializer (node); + case NodeKind.Metaclass: + return ConvertMetaclass (node); + case NodeKind.UnsafeMutableAddressor: + return ConvertUnsafeMutableAddressor (node); + case NodeKind.CurryThunk: + return ConvertCurryThunk (node); + case NodeKind.Global: + return Convert (node); + default: + return null; + } + } + + TLFunction ConvertFunction (Node node) + { + var swiftType = ConvertToSwiftType (node, false, null); + var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) { + // method + var context = uncurriedFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = new SwiftName (context.Last (), false); + return new TLFunction (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset); + } + + var plainFunction = swiftType as SwiftFunctionType; + if (plainFunction != null) { + var context = plainFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context [context.Length - 2] [0] == '|') { + Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); + } + var functionName = new SwiftName (context.Last (), false); + return new TLFunction (mangledName, module, functionName, null, plainFunction, offset, operatorType); + } + return null; + } + + TLDefinition ConvertStatic (Node node) + { + if (node.Children [0].Kind == NodeKind.Variable) { + return ConvertVariable (node.Children [0], true); + } + var swiftType = ConvertToSwiftType (node, false, null); + var propType = swiftType as SwiftPropertyType; + if (propType != null) { + var context = propType.DiscretionaryString.Split ('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); + } + + var staticFunction = swiftType as SwiftStaticFunctionType; + if (staticFunction != null) { + var context = staticFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context [context.Length - 2] [0] == '|') { + Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); + } + var functionName = new SwiftName (context.Last (), false); + return new TLFunction (mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); + } + return null; + } + + TLFunction ConvertFunctionConstructor (Node node) + { + var swiftType = ConvertToSwiftType (node, false, null); + var constructor = swiftType as SwiftConstructorType; + if (constructor != null) { + var context = constructor.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = constructor.Name; + var metaType = constructor.UncurriedParameter as SwiftMetaClassType; + return new TLFunction (mangledName, module, functionName, metaType.Class, constructor, offset); + } + return null; + } + + TLFunction ConvertFunctionDestructor (Node node) + { + var swiftType = ConvertToSwiftType (node, false, null); + var destructor = swiftType as SwiftDestructorType; + if (destructor != null) { + var context = destructor.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = destructor.Name; + var className = destructor.Parameters as SwiftClassType; + if (className == null) + throw new NotSupportedException ($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType ().Name}"); + return new TLFunction (mangledName, module, functionName, className, destructor, offset); + } + return null; + } + + TLFunction ConvertFunctionProp (Node node) + { + var propType = ConvertToSwiftType (node, false, null) as SwiftPropertyType; + if (propType == null) + return null; + var context = propType.DiscretionaryString.Split ('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); + } + + TLVariable ConvertVariable (Node node, bool isStatic) + { + if (node.Children.Count != 3) + throw new ArgumentOutOfRangeException (nameof (node), $"Expected 3 children in a variable node, but got {node.Children.Count}"); + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (classType == null && !node.Children [0].HasText) + return null; + var module = classType != null ? classType.ClassName.Module : new SwiftName (node.Children [0].Text, false); + var name = new SwiftName (PrivateNamePublicName (node.Children [1]).Item2, false); + var variableType = ConvertToSwiftType (node.Children [2], false, null); + return new TLVariable (mangledName, module, classType, name, variableType, isStatic, offset); + } + + TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer (Node node) + { + if (node.Children.Count != 2) + return null; + var baseFunction = ConvertToSwiftType (node.Children [0], false, null) as SwiftBaseFunctionType; + if (baseFunction == null) + return null; + var context = baseFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var argumentIndex = (int)node.Children [1].Index; + return new TLDefaultArgumentInitializer (mangledName, module, baseFunction, argumentIndex, offset); + } + + TLFieldOffset ConvertFieldOffset (Node node) + { + if (node.Children.Count != 2 || node.Children [0].Kind != NodeKind.Directness) + return null; + var variable = ConvertToVariable (node.Children [1], false, null) as SwiftInitializerType; + if (variable == null) + return null; + + var context = variable.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var className = variable.Owner; + + return new TLFieldOffset (mangledName, module, className, node.Children [0].Index == 0, variable.Name, + variable.ReturnType, offset); + } + + TLFunction ConvertCCtor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var metaType = new SwiftMetaClassType (classType, false); + var cctor = new SwiftClassConstructorType (metaType, false); + return new TLFunction (mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, + cctor, offset); + } + + TLDirectMetadata ConvertMetadata (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLDirectMetadata (mangledName, classType.ClassName.Module, classType, offset); + } + + + TLNominalTypeDescriptor ConvertNominalTypeDescriptor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLNominalTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); + } + + TLProtocolTypeDescriptor ConvertProtocolDescriptor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLProtocolTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); + } + + TLFunction ConvertInitializer (Node node) + { + var swiftInitializer = ConvertToSwiftType (node.Children [0], false, null) as SwiftInitializerType; + var context = swiftInitializer.DiscretionaryString.Split ('.'); + return new TLFunction (mangledName, new SwiftName (context [0], false), swiftInitializer.Name, swiftInitializer.Owner, swiftInitializer, offset); + } + + TLLazyCacheVariable ConvertLazyCacheVariable (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLLazyCacheVariable (mangledName, classType.ClassName.Module, classType, offset); + } + + TLFunction ConvertProtocolWitnessTable (Node node) + { + var witnessTable = ConvertToSwiftType (node, false, null) as SwiftWitnessTableType; + + var rebuiltWitnessTable = new SwiftWitnessTableType (witnessTable.WitnessType, witnessTable.ProtocolType); + + return new TLFunction (mangledName, new SwiftName (witnessTable.DiscretionaryString, false), null, + witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); + } + + TLMetaclass ConvertMetaclass (Node node) + { + if (node.Children [0].Kind != NodeKind.Type) + return null; + var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; + if (classType == null) + return null; + var module = classType.ClassName.Module; + return new TLMetaclass (mangledName, module, classType, offset); + } + + SwiftType ConvertToGlobalUnsafeMutableAddressor (Node node, bool isReference, SwiftName name) + { + string module = node.Children [0].Text; + var operatorType = ToOperatorType (node.Children [1].Kind); + var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; + var functionName = module + + (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + + "." + funcName; + var function = ConvertToSwiftType (node.Children [2], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; + function.DiscretionaryString = functionName; + return function; + } + + TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (classType != null) { + var privatePublicName = PrivateNamePublicName (node.Children [1]).Item2; + var ofType = ConvertToSwiftType (node.Children [2], false, null); + if (classType == null || ofType == null) + return null; + + return new TLUnsafeMutableAddressor (mangledName, classType.ClassName.Module, classType, new SwiftName (privatePublicName, false), ofType, offset); + } else { + var funcType = ConvertToSwiftType (node, false, null) as SwiftFunctionType; + if (funcType != null) { + var parts = funcType.DiscretionaryString.Split ('.'); + var moduleName = parts [0]; + var funcName = funcType.Name; + return new TLUnsafeMutableAddressor (mangledName, new SwiftName (moduleName, false), null, funcName, funcType, offset); + } + } + return null; + } + + TLThunk ConvertCurryThunk (Node node) + { + TLFunction func = ConvertFunction (node.Children [0]); + return new TLThunk (ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); + } + + + + + + + + + // All the ConvertTo... functions are called from the tree reduction rules + + SwiftType ConvertToSwiftType (Node node, bool isReference, SwiftName name) + { + return ruleRunner.RunRules (node, isReference, name); + } + + SwiftType ConvertFirstChildToSwiftType (Node node, bool isReference, SwiftName name) + { + if (node.Children.Count == 0) + throw new ArgumentOutOfRangeException (nameof (node)); + return ConvertToSwiftType (node.Children [0], isReference, name); + } + + SwiftType ConvertToReferenceType (Node node, bool isReference, SwiftName name) + { + return ConvertToSwiftType (node.Children [0].Children [0], true, name); + } + + SwiftType ConvertToMetatype (Node node, bool isReference, SwiftName name) + { + var subType = ConvertFirstChildToSwiftType (node, isReference, name); + var classType = subType as SwiftClassType; + if (classType == null) + throw new ArgumentOutOfRangeException (nameof (node)); + return new SwiftMetaClassType (classType, isReference); + } + + SwiftType ConvertToTuple (Node node, bool isReference, SwiftName name) + { + if (node.Children.Count == 0) + return SwiftTupleType.Empty; + var args = new List (); + foreach (var n in node.Children) { + args.Add (ConvertToSwiftType (n, false, null)); + } + var st = new SwiftTupleType (args, isReference, name); + return st; + } + + SwiftType ConvertToVariable (Node node, bool isReference, SwiftName name) + { + var context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var variableName = node.Children [1].Text; + var variableType = ConvertToSwiftType (node.Children [2], false, null); + var initializerExpr = new SwiftInitializerType (InitializerType.Variable, variableType, context, new SwiftName (variableName, false)); + initializerExpr.DiscretionaryString = context.ClassName.ToFullyQualifiedName (true); + return initializerExpr; + } + + SwiftType ConvertToGenericReference (Node node, bool isReference, SwiftName name) + { + long depth = node.Children [0].Index; + long index = node.Children [1].Index; + return new SwiftGenericArgReferenceType ((int)depth, (int)index, isReference, name); + } + + SwiftType ConvertToBoundGeneric (Node node, bool isReference, SwiftName name) + { + var baseType = ConvertToSwiftType (node.Children [0], false, null); + var boundTypes = ConvertTypeList (node.Children [1]); + return new SwiftBoundGenericType (baseType, boundTypes, isReference, name); + } + + List ConvertTypeList (Node node) + { + var typeList = new List (node.Children.Count); + foreach (var childNode in node.Children) { + typeList.Add (ConvertToSwiftType (childNode, false, null)); + } + return typeList; + } + + SwiftType ConvertToNamedTupleElement (Node node, bool isReference, SwiftName name) + { + var offset = node.Children [0].Kind == NodeKind.VariadicMarker ? 1 : 0; + name = new SwiftName (node.Children [0 + offset].Text, false); + SwiftType type = ConvertToSwiftType (node.Children [1 + offset], isReference, name); + if (node.Children [0].Kind == NodeKind.VariadicMarker) + type.IsVariadic = true; + return type; + } + + SwiftType ConvertToVariadicTupleElement (Node node, bool isReference, SwiftName name) + { + SwiftType type = ConvertToSwiftType (node.Children [1], isReference, name); + type.IsVariadic = true; + return type; + } + + SwiftType ConvertToSubscript (Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + SwiftClassType context = null; + SwiftType extensionOn = null; + string module = null; + if (node.Children [0].Kind == NodeKind.Extension) { + var extNode = node.Children [0]; + extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); + module = extNode.Children [0].Text; + } else { + context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + module = context.ClassName.Module.Name; + } + + + var propName = new SwiftName (node.Children [1].Text, false); + var getterType = ConvertToSwiftType (node.Children [2], false, null) as SwiftFunctionType; + if (propertyType == PropertyType.Setter && getterType.ReturnType != null && !getterType.ReturnType.IsEmptyTuple) { + // oh hooray! + // If I define an indexer in swift like this: + // public subscript(T index) -> U { + // get { return getSomeUValue(index); } + // set (someUValue) { setSomeUValue(index, someUValue); } + // } + // This signature of the function attached to both properties is: + // T -> U + // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but + // the setter is (T, U) -> void + // + // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect + // what's really happening. + + // need to change this so that the tail parameters get names? Maybe just the head? + SwiftTupleType newParameters = getterType.ParameterCount == 1 ? + new SwiftTupleType (false, null, getterType.ReturnType, + getterType.Parameters.RenamedCloneOf (new SwiftName (getterType.ReturnType.Name == null || + getterType.ReturnType.Name.Name != "a" ? "a" : "b", false))) + : new SwiftTupleType (Enumerable.Concat (getterType.ReturnType.Yield (), getterType.EachParameter), + false, null); + getterType = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, getterType.CanThrow, getterType.Name); + + } + var prop = new SwiftPropertyType (context, propertyType, propName, null, getterType, false, isReference); + prop.ExtensionOn = extensionOn; + prop.DiscretionaryString = module; + return prop; + } + + SwiftType ConvertToSubscriptGetter (Node node, bool isReference, SwiftName name) + { + return ConvertToSubscript (node, isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSubscriptSetter (Node node, bool isReference, SwiftName name) + { + return ConvertToSubscript (node, isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToProperty (Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + var context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var privatePublicName = PrivateNamePublicName (node.Children [1]); + var propName = new SwiftName (privatePublicName.Item2, false); + var privateName = privatePublicName.Item1 != null ? new SwiftName (privatePublicName.Item1, false) : null; + + if (Decomposer.IsSubscript (propName)) + return ConvertToSubscript (node, isReference, name, propertyType); + + var getterType = ConvertToSwiftType (node.Children [2], false, propertyType == PropertyType.Setter ? new SwiftName ("newValue", false) : null); + var prop = new SwiftPropertyType (context, propertyType, propName, privateName, getterType, false, isReference); + prop.DiscretionaryString = context.ClassName.ToFullyQualifiedName (true); + return prop; + } + + SwiftType ConvertToGetter (Node node, bool isReference, SwiftName name) + { + return ConvertToProperty (node, isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSetter (Node node, bool isReference, SwiftName name) + { + return ConvertToProperty (node, isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToMaterializer (Node node, bool isReference, SwiftName name) + { + if (node.Children [0].Kind == NodeKind.Extension) { + return ConvertToGlobalProperty (node, isReference, name, PropertyType.Materializer); + } + return ConvertToProperty (node, isReference, name, PropertyType.Materializer); + } + + SwiftType ConvertToDidSet (Node node, bool isReference, SwiftName name) + { + return ConvertToProperty (node, isReference, name, PropertyType.DidSet); + } + + SwiftType ConvertToWillSet (Node node, bool isReference, SwiftName name) + { + return ConvertToProperty (node, isReference, name, PropertyType.WillSet); + } + + + SwiftType ConvertToGlobalProperty (Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + string module = null; + SwiftType extensionOn = null; + if (node.Children [0].Kind == NodeKind.Extension) { + var extNode = node.Children [0]; + module = extNode.Children [0].Text; + extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); + } else { + module = node.Children [0].Text; + } + SwiftName propName = null; + SwiftName privateName = null; + if (node.Children [1].Kind == NodeKind.PrivateDeclName) { + propName = new SwiftName (node.Children [1].Children [0].Text, false); + privateName = new SwiftName (node.Children [1].Children [1].Text, false); + + } else if (node.Children [1].Kind == NodeKind.Identifier) { + propName = new SwiftName (node.Children [1].Text, false); + // materializers are formatted oddly and come in + // as globals like willSet and didSet + // We don't care very much about materializers, but enough + // that they should go to the correct place (subscript vs property). + if (Decomposer.IsSubscript (propName)) { + return ConvertToSubscript (node, isReference, name, propertyType); + } + } + var getterType = ConvertToSwiftType (node.Children [2], false, null); + var prop = new SwiftPropertyType (null, propertyType, propName, privateName, getterType, false, isReference, extensionOn); + prop.DiscretionaryString = module; + return prop; + } + + SwiftType ConvertToGlobalGetter (Node node, bool isReference, SwiftName name) + { + return ConvertToGlobalProperty (node, isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToGlobalSetter (Node node, bool isReference, SwiftName name) + { + return ConvertToGlobalProperty (node, isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToUnnamedTupleElement (Node node, bool isReference, SwiftName name) + { + var offset = node.Children [0].Kind == NodeKind.VariadicMarker ? 1 : 0; + return ConvertToSwiftType (node.Children [offset], false, null); + } + + SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name) + { + if (node.Children.Count != 1) + throw new NotSupportedException ("ProtocolList node with more than 1 child not supported"); + if (node.Children [0].Kind != NodeKind.TypeList || node.Children [0].Children.Count > 1) + throw new NotSupportedException ($"Given a ProtocolList node with child type {node.Children [0].Kind.ToString ()} and {node.Children [0].Children.Count} children, but expected a TypeList with exactly 1 child."); + // If the number of elements is 0, it means that this is an "Any" type in swift. + // I'm assuming it's lodged here as a protocol list is that an empty protocol list is + // represented by an existential container which is also used to represent a protocol list. + if (node.Children [0].Children.Count == 0) { + var className = SwiftClassName.FromFullyQualifiedName ("Swift.Any", OperatorType.None, 'P'); + var classType = new SwiftClassType (className, isReference, name); + return classType; + } + return ConvertToSwiftType (node.Children [0].Children [0], isReference, name); + } + + SwiftType ConvertToProtocolWitnessTable (Node node, bool isReference, SwiftName name) + { + var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? + WitnessType.Protocol : WitnessType.ProtocolAccessor; + var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; + var protoType = ConvertToSwiftType (node.Children [0].Children [1], false, null) as SwiftClassType; + var protoWitness = new SwiftWitnessTableType (witnessType, protoType, classType); + protoWitness.DiscretionaryString = node.Children [0].Children [2].Text; + return protoWitness; + } + + SwiftType ConvertToValueWitnessTable (Node node, bool isReference, SwiftName name) + { + var valueType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var valueWitnessTable = new SwiftWitnessTableType (WitnessType.Value, null, valueType); + valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; + return valueWitnessTable; + } + + SwiftType ConvertToFunction (Node node, bool isReference, SwiftName name) + { + string module = null; + SwiftType extensionOn = null; + if (node.Children [0].Kind == NodeKind.Extension) { + var extNode = node.Children [0]; + module = extNode.Children [0].Text; + extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); + } else { + module = node.Children [0].Text; + } + var operatorType = ToOperatorType (node.Children [1].Kind); + var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; + var functionName = module + + (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + + "." + funcName; + var function = ConvertToSwiftType (node.Children [2], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; + if (extensionOn != null) + function.ExtensionOn = extensionOn; + function.DiscretionaryString = functionName; + return function; + } + + SwiftType ConvertToFunctionType (Node node, bool isReference, SwiftName name) + { + var args = ConvertToSwiftType (node.Children [0], false, null); + var ret = ConvertToSwiftType (node.Children [1], false, null); + var function = new SwiftFunctionType (args, ret, isReference, false, name); + return function; + } + + SwiftType ConvertToCFunctionPointerType (Node node, bool isReference, SwiftName name) + { + var args = ConvertToSwiftType (node.Children [0], false, null); + var ret = ConvertToSwiftType (node.Children [1], false, null); + var function = new SwiftCFunctionPointerType (args, ret, isReference, false, name); + return function; + } + + SwiftType ConvertToFunctionThrowsType (Node node, bool isReference, SwiftName name) + { + var args = ConvertToSwiftType (node.Children [1], false, null); + var ret = ConvertToSwiftType (node.Children [2], false, null); + var function = new SwiftFunctionType (args, ret, isReference, true, name); + return function; + } + + SwiftType ConvertToStatic (Node node, bool isReference, SwiftName name) + { + var functionType = ConvertToSwiftType (node.Children [0], isReference, name); + if (functionType == null) + return null; + var propType = functionType as SwiftPropertyType; + if (propType != null) { + return propType.RecastAsStatic (); + } + var uncurriedFunction = functionType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) { + var staticFunction = new SwiftStaticFunctionType (uncurriedFunction.Parameters, uncurriedFunction.ReturnType, + uncurriedFunction.IsReference, uncurriedFunction.CanThrow, + uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); + staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; + return staticFunction; + } + var baseFunctionType = functionType as SwiftBaseFunctionType; + if (baseFunctionType != null) { + var staticFunction = new SwiftStaticFunctionType (baseFunctionType.Parameters, baseFunctionType.ReturnType, + baseFunctionType.IsReference, baseFunctionType.CanThrow, + null, baseFunctionType.Name); + staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; + staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; + return staticFunction; + } + var initializerType = functionType as SwiftInitializerType; + if (initializerType != null) { + return initializerType; // this doesn't need a static recast? + } + throw new ArgumentOutOfRangeException ($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType ().Name}"); + } + + SwiftType ConvertToMethod (Node node, bool isReference, SwiftName name) + { + var instanceType = ConvertToSwiftType (node.Children [0], false, null); + var sct = instanceType as SwiftClassType; + if (sct == null) + throw new NotSupportedException ($"Expected an SwiftClassType for the instance type but got {instanceType.GetType ().Name}."); + var operatorType = ToOperatorType (node.Children [1].Kind); + var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; + var functionName = sct.ClassName.ToFullyQualifiedName (true) + + (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + + "." + funcName; + + sct.ClassName.Operator = operatorType; + var functionType = node.Children [2].Children [0]; + var genericArguments = new List (); + if (functionType.Children[0].Kind == NodeKind.DependentGenericSignature) { + genericArguments = GetGenericArguments (functionType); + functionType = functionType.Children [1].Children[0]; + } + var throws = functionType.Children.Count == 3; + var startIndex = throws ? 1 : 0; + var args = ConvertToSwiftType (functionType.Children [startIndex + 0], false, null); + var ret = ConvertToSwiftType (functionType.Children [startIndex + 1], false, null); + var uncurriedFunction = new SwiftUncurriedFunctionType (instanceType, args, ret, isReference, throws, name); + uncurriedFunction.DiscretionaryString = functionName; + uncurriedFunction.GenericArguments.AddRange (genericArguments); + return uncurriedFunction; + } + + SwiftType ConvertToAnyObject(Node node, bool isReference, SwiftName name) + { + var className = SwiftClassName.FromFullyQualifiedName ("Swift.AnyObject", OperatorType.None, 'C'); + var classType = new SwiftClassType (className, isReference, name); + return classType; + } + + OperatorType ToOperatorType (NodeKind kind) + { + switch (kind) { + default: + case NodeKind.Identifier: + return OperatorType.None; + case NodeKind.PrefixOperator: + return OperatorType.Prefix; + case NodeKind.InfixOperator: + return OperatorType.Infix; + case NodeKind.PostfixOperator: + return OperatorType.Postfix; + } + } + + SwiftType ConvertToAllocatingConstructor (Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor (node, isReference, name, true); + } + + SwiftType ConvertToNonAllocatingConstructor (Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor (node, isReference, name, false); + } + + SwiftType ConvertToConstructor (Node node, bool isReference, SwiftName name, bool isAllocating) + { + var instanceType = ConvertToSwiftType (node.Children [0], false, null); + var sct = instanceType as SwiftClassType; + if (sct == null) + throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in constructor but got {instanceType.GetType ().Name}."); + var metadata = new SwiftMetaClassType (sct, false, null); + var functionType = node.Children [1].Children [0]; + var functionThrows = functionType.Children.Count == 3 && functionType.Children [0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; + var args = ConvertToSwiftType (functionType.Children [0 + functionThrows], false, null); + var ret = ConvertToSwiftType (functionType.Children [1 + functionThrows], false, null); + var constructor = new SwiftConstructorType (isAllocating, metadata, args, ret, isReference, functionThrows != 0); + constructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); + return constructor; + } + + SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor (node, isReference, name, false); + } + + SwiftType ConvertToDeallocator (Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor (node, isReference, name, true); + } + + SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name, bool isDeallocating) + { + var instanceType = ConvertToSwiftType (node.Children [0], false, null); + var sct = instanceType as SwiftClassType; + if (sct == null) + throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType ().Name}."); + var destructor = new SwiftDestructorType (isDeallocating, sct, isReference, false); + destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); + return destructor; + } + + SwiftType ConvertToStruct (Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName (node); + var bit = TryAsBuiltInType (node, className, isReference, name); + return (SwiftType)bit ?? new SwiftClassType (className, isReference, name); + } + + SwiftType ConvertToClass (Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName (node); + return new SwiftClassType (className, isReference, name); + } + + SwiftClassName ToSwiftClassName (Node node) + { + var memberNesting = new List (); + var nestingNames = new List (); + var moduleName = BuildMemberNesting (node, memberNesting, nestingNames); + + moduleName = PatchClassName (moduleName, nestingNames); + return new SwiftClassName (moduleName, memberNesting, nestingNames); + } + + SwiftType ConvertToGenericFunction (Node node, bool isReference, SwiftName name) + { + List args = GetGenericArguments (node); + var theFunction = ConvertToSwiftType (node.Children [1], isReference, name) as SwiftBaseFunctionType; + theFunction.GenericArguments.AddRange (args); + return theFunction; + } + + List GetGenericArguments(Node node) + { + var paramCountNode = node.Children [0].Children [0]; + if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) + throw new NotSupportedException ($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString ()}"); + + var paramCount = (int)paramCountNode.Index; + List args = new List (paramCount); + for (int i = 0; i < paramCount; i++) { + args.Add (new GenericArgument (0, i)); + } + if (node.Children [0].Children.Count > 1) { + var dependentGenericSignature = node.Children [0]; + // the 0th child is the number of generic parameters (see above) + for (int i = 1; i < dependentGenericSignature.Children.Count; i++) { + var genericParamReference = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [0], false, null) as SwiftGenericArgReferenceType; + var genericConstraintType = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [1], false, null) as SwiftClassType; + MarkGenericConstraint (args, genericParamReference, genericConstraintType); + } + } + return args; + } + + static void MarkGenericConstraint (List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) + { + foreach (var genArg in args) { + if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) { + genArg.Constraints.Add (constraintType); + return; + } + } + } + + static SwiftBuiltInType TryAsBuiltInType (Node node, SwiftClassName className, bool isReference, SwiftName name) + { + switch (className.ToFullyQualifiedName ()) { + case "Swift.Int": + return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); + case "Swift.Float": + return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); + case "Swift.Bool": + return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); + case "Swift.UInt": + return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); + case "Swift.Double": + return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); + default: + return null; + } + } + + static SwiftName BuildMemberNesting (Node node, List nestings, List names) + { + var nesting = MemberNesting.Class; + switch (node.Kind) { + case NodeKind.Class: + break; + case NodeKind.Structure: + nesting = MemberNesting.Struct; + break; + case NodeKind.Enum: + nesting = MemberNesting.Enum; + break; + case NodeKind.Protocol: + nesting = MemberNesting.Protocol; + break; + default: + throw new ArgumentOutOfRangeException (nameof (node), $"Expected a nominal type node kind but got {node.Kind.ToString ()}"); + } + + var privatePublicName = PrivateNamePublicName (node.Children [1]); + var className = new SwiftName (privatePublicName.Item2, false); + SwiftName moduleName = null; + if (node.Children [0].Kind == NodeKind.Identifier || node.Children [0].Kind == NodeKind.Module) { + moduleName = new SwiftName (node.Children [0].Text, false); + } else { + // recurse before adding names. + moduleName = BuildMemberNesting (node.Children [0], nestings, names); + } + names.Add (className); + nestings.Add (nesting); + return moduleName; + } + + static Node ExtractFunctionType (Node n) + { + if (n.Kind == NodeKind.Type && n.Children.Count == 1 && n.Children [0].Kind == NodeKind.FunctionType) { + return n.Children [0]; + } + return null; + } + + + static Tuple PrivateNamePublicName (Node node) + { + if (node.Kind == NodeKind.Identifier) + return new Tuple (null, node.Text); + if (node.Kind == NodeKind.PrivateDeclName) + return new Tuple (node.Children [1].Text, node.Children [0].Text); + throw new ArgumentOutOfRangeException (nameof (node)); + } + + + + // Swift does...weird...things with some of the core types from C. + // The mangler doesn't put in the appropriate swift module, but instead lumps them all + // together into the module __C. + // The mangler also puts a number of Foundation types into the namespace __ObjC. + // Why? No idea. + // I determined this list of __ObjC types by running the following command on all the Apple built libraries: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq + // which also includes a number of inner types which we don't care about (yet). + + // The command to do this for the __C namespace is: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq + + static Dictionary classNameOntoModule = new Dictionary { + { "AVError", "AVFoundation" }, + { "AudioBuffer", "AudioToolbox" }, + { "AudioBufferList", "AudioToolbox" }, + { "CATransform3D", "CoreAnimation" }, + { "CGAffineTransform", "CoreGraphics" }, + { "CGColorSapceModel", "CoreGraphics" }, + { "CGPoint", "CoreGraphics" }, + { "CGRect", "CoreGraphics" }, + { "CGSize", "CoreGraphics" }, + { "CGVector", "CoreGraphics" }, + { "CLError", "CoreLocation" }, + { "CMTime", "CoreMedia" }, + { "CMTimeFlags", "CoreMedia" }, + { "CMTimeMapping", "CoreMedia" }, + { "CMTimeRange", "CoreMedia" }, + { "NSComparisonResult", "Foundation" }, + { "NSDecimal", "Foundation" }, + { "NSEnumerationOptions", "Foundation" }, + { "NSKeyValueChange", "Foundation" }, + { "NSKeyValueObservingOptions", "Foundation" }, + { "NSFastEnumerationState", "Foundation" }, + { "NSKeyValueChangeKey", "Foundation" }, + { "StringTransform", "Foundation" }, + { "URLFileResourceType", "Foundation" }, + { "URLResourceKey", "Foundation" }, + { "URLThumbnailDictionaryItem", "Foundation" }, + { "URLUbiquitousItemDownloadingStatus", "Foundation" }, + { "URLUbiquitousSharedItemPermissions", "Foundation" }, + { "URLUbiquitousSharedItemRole", "Foundation" }, + { "MKCoordinateSpan", "MapKit" }, + { "NSAnimationEffect", "AppKit" }, + { "SCNGeometryPrimitiveType", "SceneKit" }, + { "SCNVector3", "SceneKit" }, + { "SCNVector4", "SceneKit" }, + { "UIContentSizeCategory", "UIKit" }, + { "UIDeviceOrientation", "UIKit" }, + { "UIEdgeInsets", "UIKit" }, + { "UIInterfaceOrientation", "UIKit" }, + { "UIOffset", "UIKit" }, + { "CKError", "CloudKit" }, + { "CNError", "Contacts" }, + { "MTLSamplePosition", "Metal" }, + { "XCUIKeyboardKey", "XCTest" }, + { "BNNSActivationFunction", "Accelerate" }, + { "BNNSDataType", "Accelerate" }, + { "simd_double2x2", "Accelerate" }, + { "simd_double2x3", "Accelerate" }, + { "simd_double2x4", "Accelerate" }, + { "simd_double3x2", "Accelerate" }, + { "simd_double3x3", "Accelerate" }, + { "simd_double3x4", "Accelerate" }, + { "simd_double4x2", "Accelerate" }, + { "simd_double4x3", "Accelerate" }, + { "simd_double4x4", "Accelerate" }, + { "simd_float2x2", "Accelerate" }, + { "simd_float2x3", "Accelerate" }, + { "simd_float2x4", "Accelerate" }, + { "simd_float3x2", "Accelerate" }, + { "simd_float3x3", "Accelerate" }, + { "simd_float3x4", "Accelerate" }, + { "simd_float4x2", "Accelerate" }, + { "simd_float4x3", "Accelerate" }, + { "simd_float4x4", "Accelerate" }, + { "simd_quatd", "Accelerate" }, + { "simd_quatf", "Accelerate" } + }; + + + static SwiftName PatchClassName (SwiftName moduleName, List nestingNames) + { + // surprise! + // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version + // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough + // bottleneck to alias it. + if (moduleName.Name == "__ObjC") + moduleName = new SwiftName ("Foundation", false); + if (moduleName.Name != "__C") + return moduleName; + if (nestingNames.Count != 1) + return moduleName; + string result = null; + if (classNameOntoModule.TryGetValue (nestingNames [0].Name, out result)) + return new SwiftName (result, false); + return moduleName; + } + } +} diff --git a/src/SwiftReflector/Demangling/Swift5Demangler.cs b/src/SwiftReflector/Demangling/Swift5Demangler.cs new file mode 100644 index 000000000000..b52aa4bce2f2 --- /dev/null +++ b/src/SwiftReflector/Demangling/Swift5Demangler.cs @@ -0,0 +1,2960 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; + + + +// This is a port of the Apple Swift 5 demangler +namespace SwiftReflector.Demangling { + public class Swift5Demangler { + ulong offset; + string originalIdentifier; + Stack nodeStack = new Stack (); + List substitutions = new List (); + string text; + List words = new List (); + StringSlice slice; + bool isOldFunctionTypeMangling = false; + + public Func SymbolicReferenceResolver { get; set; } + + static string [] prefixes = { + /*Swift 4*/ "_T0", + /*Swift 4.x*/ "$S", "_$S", + /*Swift 5+*/ "$s", "_$s" + }; + + Swift5Demangler () + { + } + + + public Swift5Demangler (string mangledName, ulong offset = 0) + { + originalIdentifier = mangledName; + this.offset = offset; + slice = new StringSlice (originalIdentifier); + slice.Advance (GetManglingPrefixLength (originalIdentifier)); + } + + public TLDefinition Run () + { + Node topLevelNode = DemangleType (null); + if (topLevelNode != null && topLevelNode.IsAttribute () && nodeStack.Count >= 1) { + var attribute = topLevelNode.ExtractAttribute (); + var tld = Run (); + if (tld != null && tld is TLFunction tlf) { + tlf.Signature.Attributes.Add (attribute); + } + return tld; + } else { + Swift5NodeToTLDefinition converter = new Swift5NodeToTLDefinition (originalIdentifier, offset); + return converter.Convert (topLevelNode); + } + } + + bool NextIf (string str) + { + if (slice.StartsWith (str)) { + slice.Advance (str.Length); + return true; + } + return false; + + } + + char PeekChar () + { + if (slice.IsAtEnd) + return (char)0; + return slice.Current; + } + + char NextChar () + { + return slice.Advance (); + } + + bool NextIf (char c) + { + return slice.AdvanceIfEquals (c); + } + + void PushBack () + { + slice.Rewind (); + } + + string ConsumeAll () + { + return slice.ConsumeRemaining (); + } + + void PushNode (Node node) + { + nodeStack.Push (node); + } + + Node PopNode () + { + if (nodeStack.Count == 0) + return null; + return nodeStack.Pop (); + } + + Node PopNode (NodeKind kind) + { + if (nodeStack.Count == 0) + return null; + if (kind != nodeStack.Peek ().Kind) + return null; + return PopNode (); + } + + Node PopNode (Predicate pred) + { + if (nodeStack.Count == 0) + return null; + if (!pred (nodeStack.Peek ().Kind)) + return null; + return PopNode (); + } + + void AddSubstitution (Node nd) + { + if (nd != null) + substitutions.Add (nd); + } + + Node CreateWithPoppedType (NodeKind kind) + { + return CreateWithChild (kind, PopNode (NodeKind.Type)); + } + + + // beginning of swift 5 demangler port + + static bool IsDeclName (NodeKind kind) + { + switch (kind) { + case NodeKind.Identifier: + case NodeKind.LocalDeclName: + case NodeKind.PrivateDeclName: + case NodeKind.RelatedEntityDeclName: + case NodeKind.PrefixOperator: + case NodeKind.PostfixOperator: + case NodeKind.InfixOperator: + case NodeKind.TypeSymbolicReference: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsContext (NodeKind node) + { + var type = typeof (NodeKind); + var memInfo = type.GetMember (node.ToString ()); + return memInfo [0].GetCustomAttributes (typeof (ContextAttribute), false).Length > 0; + } + + static bool IsAnyGeneric (NodeKind kind) + { + switch (kind) { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + case NodeKind.OtherNominalType: + case NodeKind.TypeAlias: + case NodeKind.TypeSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsEntity (NodeKind kind) + { + if (kind == NodeKind.Type) + return true; + return IsContext (kind); + } + + static bool IsRequirement (NodeKind kind) + { + switch (kind) { + case NodeKind.DependentGenericSameTypeRequirement: + case NodeKind.DependentGenericLayoutRequirement: + case NodeKind.DependentGenericConformanceRequirement: + return true; + default: + return false; + } + } + + static bool IsFunctionAttr (NodeKind kind) + { + switch (kind) { + case NodeKind.FunctionSignatureSpecialization: + case NodeKind.GenericSpecialization: + case NodeKind.InlinedGenericFunction: + case NodeKind.GenericSpecializationNotReAbstracted: + case NodeKind.GenericPartialSpecialization: + case NodeKind.GenericPartialSpecializationNotReAbstracted: + case NodeKind.ObjCAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.DirectMethodReferenceAttribute: + case NodeKind.VTableAttribute: + case NodeKind.PartialApplyForwarder: + case NodeKind.PartialApplyObjCForwarder: + case NodeKind.OutlinedVariable: + case NodeKind.OutlinedBridgedMethod: + case NodeKind.MergedFunction: + case NodeKind.DynamicallyReplaceableFunctionImpl: + case NodeKind.DynamicallyReplaceableFunctionKey: + case NodeKind.DynamicallyReplaceableFunctionVar: + return true; + default: + return false; + } + } + + int GetManglingPrefixLength (string mangledName) + { + if (string.IsNullOrEmpty (mangledName)) + return 0; + foreach (var prefix in prefixes) { + mangledName.StartsWith (prefix, StringComparison.Ordinal); + return prefix.Length; + } + return 0; + } + + bool IsSwiftSymbol (string mangledName) + { + if (IsOldFunctionTypeMangling (mangledName)) + return true; + return GetManglingPrefixLength (mangledName) != 0; + } + + bool IsObjCSymbol (string mangledName) + { + var nameWithoutPrefix = DropSwiftManglingPrefix (mangledName); + return nameWithoutPrefix.StartsWith ("So", StringComparison.Ordinal) || nameWithoutPrefix.StartsWith ("Sc", StringComparison.Ordinal); + } + + bool IsOldFunctionTypeMangling (string mangledName) + { + return mangledName.StartsWith ("_T", StringComparison.Ordinal); + } + + string DropSwiftManglingPrefix (string mangledName) + { + return mangledName.Substring (GetManglingPrefixLength (mangledName)); + } + + static bool IsAliasNode (Node node) + { + switch (node.Kind) { + case NodeKind.Type: + return IsAliasNode (node.Children [0]); + case NodeKind.TypeAlias: + return true; + default: + return false; + } + } + + static bool IsAlias (string mangledName) + { + return IsAliasNode (new Swift5Demangler ().DemangleType (mangledName)); + } + + static bool IsClassNode (Node node) + { + switch (node.Kind) { + case NodeKind.Type: + return IsClassNode (node.Children [0]); + case NodeKind.Class: + case NodeKind.BoundGenericClass: + return true; + default: + return false; + } + } + + static bool IsClass (string mangledName) + { + return IsClassNode (new Swift5Demangler ().DemangleType (mangledName)); + } + + static bool IsEnumNode (Node node) + { + switch (node.Kind) { + case NodeKind.Type: + return IsEnumNode (node.Children [0]); + case NodeKind.Enum: + case NodeKind.BoundGenericEnum: + return true; + default: + return false; + } + } + + static bool IsEnum (string mangledName) + { + return IsEnumNode (new Swift5Demangler ().DemangleType (mangledName)); + } + + static bool IsProtocolNode (Node node) + { + switch (node.Kind) { + case NodeKind.Type: + return IsProtocolNode (node.Children [0]); + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsProtocol (string mangledName) + { + return IsProtocolNode (new Swift5Demangler ().DemangleType (mangledName)); + } + + static bool IsStructNode (Node node) + { + switch (node.Kind) { + case NodeKind.Type: + return IsStructNode (node.Children [0]); + case NodeKind.Structure: + case NodeKind.BoundGenericStructure: + return true; + default: + return false; + } + } + + static bool IsStruct (string mangledName) + { + return IsStructNode (new Swift5Demangler ().DemangleType (mangledName)); + } + + + + + void Clear () + { + nodeStack.Clear (); + substitutions.Clear (); + } + + void Init (string mangledName) + { + nodeStack = new Stack (); + substitutions = new List (); + words = new List (); + if (mangledName != null) { + text = mangledName; + slice = new StringSlice (mangledName); + } + } + + public Node DemangleSymbol (string mangledName) + { + Init (mangledName); + + if (NextIf ("_Tt")) + return DemangleObjCTypeName (); + + var prefixLength = GetManglingPrefixLength (mangledName); + if (prefixLength == 0) + return null; + isOldFunctionTypeMangling = IsOldFunctionTypeMangling (mangledName); + slice.Advance (prefixLength); + + if (!ParseAndPushNodes ()) + return null; + + var topLevel = new Node (NodeKind.Global); + var parent = topLevel; + Node funcAttr = null; + while ((funcAttr = PopNode (IsFunctionAttr)) != null) { + parent.AddChild (funcAttr); + if (funcAttr.Kind == NodeKind.PartialApplyForwarder || funcAttr.Kind == NodeKind.PartialApplyObjCForwarder) + parent = funcAttr; + foreach (var nd in nodeStack) { + switch (nd.Kind) { + case NodeKind.Type: + parent.AddChild (nd.Children [0]); + break; + default: + parent.AddChild (nd); + break; + } + } + } + if (topLevel.Children.Count == 0) + return null; + + return topLevel; + } + + Node DemangleType (string mangledName) + { + Init (mangledName); + + ParseAndPushNodes (); + + var result = PopNode (); + if (result != null) + return result; + + return new Node (NodeKind.Suffix, text); + } + + bool ParseAndPushNodes () + { + var idx = 0; + while (!slice.IsAtEnd) { + var node = DemangleOperator (); + if (node == null) + return false; + PushNode (node); + idx++; + } + return true; + } + + Node AddChild (Node parent, Node child) + { + if (parent == null || child == null) + return null; + parent.Children.Add (child); + return parent; + } + + Node CreateWithChild (NodeKind kind, Node child) + { + if (child == null) + return null; + var node = new Node (kind); + node.Children.Add (child); + return node; + } + + Node CreateType (Node child) + { + return CreateWithChild (NodeKind.Type, child); + } + + Node CreateWithChildren (NodeKind kind, params Node [] children) + { + foreach (var nd in children) + if (nd == null) + throw new ArgumentOutOfRangeException (nameof (children)); + var node = new Node (kind); + node.Children.AddRange (children); + return node; + } + + Node ChangeKind (Node node, NodeKind newKind) + { + Node newNode = null; + if (node.HasText) { + newNode = new Node (newKind, node.Text); + } else if (node.HasIndex) { + newNode = new Node (newKind, node.Index); + } else { + newNode = new Node (newKind); + } + newNode.Children.AddRange (node.Children); + return newNode; + } + + Node DemangleTypeMangling () + { + var type = PopNode (NodeKind.Type); + var labelList = PopFunctionParamLabels (type); + var typeMangling = new Node (NodeKind.TypeMangling); + + AddChild (typeMangling, labelList); + typeMangling = AddChild (typeMangling, type); + return typeMangling; + } + + Node DemangleSymbolicReference (int rawKind) + { + var data = new byte [4]; + for (int i = 0; i < 4; i++) { + data [i] = (byte)NextChar (); + } + var value = BitConverter.ToInt32 (data, 0); + + SymbolicReferenceKind kind; + Directness direct; + switch (rawKind) { + case 1: + kind = SymbolicReferenceKind.Context; + direct = Directness.Direct; + break; + case 2: + kind = SymbolicReferenceKind.Context; + direct = Directness.Indirect; + break; + default: + return null; + } + + Node resolved = null; + if (SymbolicReferenceResolver != null) { + resolved = SymbolicReferenceResolver (kind, direct, value, data); + } + if (resolved == null) + return null; + + if (kind == SymbolicReferenceKind.Context) + AddSubstitution (resolved); + return resolved; + } + + Node DemangleOperator () + { + var c = NextChar (); + switch (c) { + case '\x01': + case '\x02': + case '\x03': + case '\x04': + return DemangleSymbolicReference (c); + case 'A': return DemangleMultiSubstitutions (); + case 'B': return DemangleBuiltinType (); + case 'C': return DemangleAnyGenericType (NodeKind.Class); + case 'D': return DemangleTypeMangling (); + case 'E': return DemangleExtensionContext (); + case 'F': return DemanglePlainFunction (); + case 'G': return DemangleBoundGenericType (); + case 'H': + var c2 = NextChar (); + switch (c2) { + case 'A': return DemangleDependentProtocolConformanceAssociated (); + case 'C': return DemangleConcreteProtocolConformance (); + case 'D': return DemangleDependentProtocolConformanceRoot (); + case 'I': return DemangleDependentProtocolConformanceInherited (); + case 'P': + return CreateWithChild (NodeKind.ProtocolConformanceRefInTypeModule, PopProtocol ()); + case 'p': + return CreateWithChild (NodeKind.ProtocolConformanceRefInProtocolModule, PopProtocol ()); + default: + PushBack (); + PushBack (); + return DemangleIdentifier (); + } + case 'I': return DemangleImplFunctionType (); + case 'K': return new Node (NodeKind.ThrowsAnnotation); + case 'L': return DemangleLocalIdentifier (); + case 'M': return DemangleMetatype (); + case 'N': return CreateWithChild (NodeKind.TypeMetadata, PopNode (NodeKind.Type)); + case 'O': return DemangleAnyGenericType (NodeKind.Enum); + case 'P': return DemangleAnyGenericType (NodeKind.Protocol); + case 'Q': return DemangleArchetype (); + case 'R': return DemangleGenericRequirement (); + case 'S': return DemangleStandardSubstitution (); + case 'T': return DemangleThunkOrSpecialization (); + case 'V': return DemangleAnyGenericType (NodeKind.Structure); + case 'W': return DemangleWitness (); + case 'X': return DemangleSpecialType (); + case 'Z': return CreateWithChild (NodeKind.Static, PopNode (IsEntity)); + case 'a': return DemangleAnyGenericType (NodeKind.TypeAlias); + case 'c': return PopFunctionType (NodeKind.FunctionType); + case 'd': return new Node (NodeKind.VariadicMarker); + case 'f': return DemangleFunctionEntity (); + case 'g': return DemangleRetroactiveConformance (); + case 'h': return CreateType (CreateWithChild (NodeKind.Shared, PopTypeAndGetChild ())); + case 'i': return DemangleSubscript (); + case 'l': return DemangleGenericSignature (false); + case 'm': return CreateType (CreateWithChild (NodeKind.Metatype, PopNode (NodeKind.Type))); + case 'n': return CreateType (CreateWithChild (NodeKind.Owned, PopTypeAndGetChild ())); + case 'o': return DemangleOperatorIdentifier (); + case 'p': return DemangleProtocolListType (); + case 'q': return CreateType (DemangleGenericParamIndex ()); + case 'r': return DemangleGenericSignature (true); + case 's': return new Node (NodeKind.Module, "Swift"); + case 't': return PopTuple (); + case 'u': return DemangleGenericType (); + case 'v': return DemangleVariable (); + case 'w': return DemangleValueWitness (); + case 'x': return CreateType (GetDependentGenericParamType (0, 0)); + case 'y': return new Node (NodeKind.EmptyList); + case 'z': return CreateType (CreateWithChild (NodeKind.InOut, PopTypeAndGetChild ())); + case '_': return new Node (NodeKind.FirstElementMarker); + case '.': + PushBack (); + return new Node (NodeKind.Suffix, slice.ConsumeRemaining ()); + default: + PushBack (); + return DemangleIdentifier (); + } + } + + int DemangleNatural () + { + if (!Char.IsDigit (slice.Current)) + return -1000; + var num = 0; + while (true) { + var c = slice.Current; + if (!Char.IsDigit (c)) + return num; + var newNum = (10 * num) + (c - '0'); + if (newNum < num) + return -1000; + num = newNum; + NextChar (); + } + } + + int DemangleIndex () + { + if (NextIf ('_')) + return 0; + var num = DemangleNatural (); + if (num >= 0 && NextIf ('_')) + return num + 1; + return -1000; + } + + + Node DemangleIndexAsNode () + { + var idx = DemangleIndex (); + if (idx >= 0) + return new Node (NodeKind.Number, idx); + return null; + } + + Node DemangleMultiSubstitutions () + { + var repeatCount = 1; + while (true) { + if (slice.IsAtEnd) + return null; + var c = NextChar (); + if (Char.IsLower (c)) { + var nd = PushMultiSubstitutions (repeatCount, c - 'a'); + if (nd == null) + return null; + PushNode (nd); + repeatCount = -1; + continue; + } + if (Char.IsUpper (c)) { + return PushMultiSubstitutions (repeatCount, c - 'A'); + } + if (c == '_') { + var idx = repeatCount + 27; + if (idx >= substitutions.Count) + return null; + return substitutions [idx]; + } + PushBack (); + repeatCount = DemangleNatural (); + if (repeatCount < 0) + return null; + } + } + + Node PushMultiSubstitutions (int repeatCount, int substIdx) + { + if (substIdx >= substitutions.Count) + return null; + if (repeatCount > Swift4Demangler.kMaxRepeatCount) + return null; + var nd = substitutions [substIdx]; + while (repeatCount-- > 1) { + PushNode (nd); + } + return nd; + } + + Node CreateSwiftType (NodeKind typeKind, string name) + { + return CreateType (CreateWithChildren (typeKind, new Node (NodeKind.Module, "Swift"), new Node (NodeKind.Identifier, name))); + } + + Node DemangleStandardSubstitution () + { + var c = NextChar (); + switch (c) { + case 'o': + return new Node (NodeKind.Module, "__C"); + case 'C': + return new Node (NodeKind.Module, "__C_Synthesized"); + case 'g': { + var optionalTy = CreateType (CreateWithChildren (NodeKind.BoundGenericEnum, + CreateSwiftType (NodeKind.Enum, "Optional"), + CreateWithChild (NodeKind.TypeList, PopNode (NodeKind.Type)))); + AddSubstitution (optionalTy); + return optionalTy; + } + default: + PushBack (); + var repeatCount = DemangleNatural (); + if (repeatCount > Swift4Demangler.kMaxRepeatCount) + return null; + Node nd; + if ((nd = CreateStandardSubstitution (NextChar ())) != null) { + while (repeatCount-- > 1) { + PushNode (nd); + } + return nd; + } + return null; + } + } + + Node CreateStandardSubstitution (char subst) + { + var kind = NodeKind.Structure; + string name = null; + switch (subst) { + case 'A': name = "AutoreleasingUnsafeMutablePointer"; break; + case 'a': name = "Array"; break; + case 'b': name = "Bool"; break; + case 'c': name = "UnicodeScalar"; break; + case 'D': name = "Dictionary"; break; + case 'd': name = "Double"; break; + case 'f': name = "Float"; break; + case 'h': name = "Set"; break; + case 'I': name = "DefaultIndicies"; break; + case 'i': name = "Int"; break; + case 'J': name = "Character"; break; + case 'N': name = "ClosedRange"; break; + case 'n': name = "Range"; break; + case 'O': name = "ObjectIdentifier"; break; + case 'P': name = "UnsafePointer"; break; + case 'p': name = "UnsafeMutablePointer"; break; + case 'R': name = "UnsafeBufferPointer"; break; + case 'r': name = "UnsafeMutableBufferPointer"; break; + case 'S': name = "String"; break; + case 's': name = "Substring"; break; + case 'u': name = "UInt"; break; + case 'V': name = "UnsafeRawPointer"; break; + case 'v': name = "UnsafeMutableRawPointer"; break; + case 'W': name = "UnsafeRawBufferPointer"; break; + case 'w': name = "UnsafeMutableRawBufferPointer"; break; + + case 'q': name = "Optional"; kind = NodeKind.Enum; break; + + case 'B': name = "BinaryFloatingPoint"; kind = NodeKind.Protocol; break; + case 'E': name = "Encodable"; kind = NodeKind.Protocol; break; + case 'e': name = "Decodable"; kind = NodeKind.Protocol; break; + case 'F': name = "FloatingPoint"; kind = NodeKind.Protocol; break; + case 'G': name = "RandomNumberGenerator"; kind = NodeKind.Protocol; break; + case 'H': name = "Hashable"; kind = NodeKind.Protocol; break; + case 'j': name = "Numeric"; kind = NodeKind.Protocol; break; + case 'K': name = "BidirectionalCollection"; kind = NodeKind.Protocol; break; + case 'k': name = "RandomAccessCollection"; kind = NodeKind.Protocol; break; + case 'L': name = "Comparable"; kind = NodeKind.Protocol; break; + case 'l': name = "Collection"; kind = NodeKind.Protocol; break; + case 'M': name = "MutableCollection"; kind = NodeKind.Protocol; break; + case 'm': name = "RangeReplaceableCollection"; kind = NodeKind.Protocol; break; + case 'Q': name = "Equatable"; kind = NodeKind.Protocol; break; + case 'T': name = "Sequence"; kind = NodeKind.Protocol; break; + case 't': name = "IteratorProtocol"; kind = NodeKind.Protocol; break; + case 'U': name = "UnsignedInteger"; kind = NodeKind.Protocol; break; + case 'X': name = "RangeExpression"; kind = NodeKind.Protocol; break; + case 'x': name = "Strideable"; kind = NodeKind.Protocol; break; + case 'Y': name = "RawRepresentable"; kind = NodeKind.Protocol; break; + case 'y': name = "StringProtocol"; kind = NodeKind.Protocol; break; + case 'Z': name = "SignedInteger"; kind = NodeKind.Protocol; break; + case 'z': name = "BinaryInteger"; kind = NodeKind.Protocol; break; + default: + return null; + } + + return CreateSwiftType (kind, name); + } + + Node DemangleIdentifier () + { + var hasWordSubsts = false; + var isPunycoded = false; + var c = PeekChar (); + if (!Char.IsDigit (c)) + return null; + if (c == '0') { + NextChar (); + if (PeekChar () == '0') { + NextChar (); + isPunycoded = true; + } else { + hasWordSubsts = true; + } + } + var identifier = new StringBuilder (); + do { + while (hasWordSubsts && Char.IsLetter (PeekChar ())) { + var cc = NextChar (); + var wordIdx = 0; + if (Char.IsLower (cc)) { + wordIdx = cc - 'a'; + } else { + wordIdx = cc - 'A'; + hasWordSubsts = false; + } + if (wordIdx >= words.Count) + return null; + string piece0 = words [wordIdx]; + identifier.Append (piece0); + } + if (NextIf ('0')) + break; + var numChars = DemangleNatural (); + if (numChars <= 0) + return null; + if (isPunycoded) + NextIf ('_'); + if (numChars > slice.Length) + return null; + string piece = slice.Substring (slice.Position, numChars); + if (isPunycoded) { + PunyCode puny = new PunyCode (); + string punyCodedString = puny.Decode (piece); + identifier.Append (punyCodedString); + } else { + identifier.Append (piece); + var wordStartPos = -1; + for (int idx = 0; idx <= piece.Length; idx++) { + char ccc = idx < piece.Length ? piece [idx] : (char)0; + if (wordStartPos >= 0 && IsWordEnd (ccc, piece [idx - 1])) { + if (idx - wordStartPos >= 2 && words.Count < 26) { + var word = piece.Substring (wordStartPos, idx - wordStartPos); + words.Add (word); + } + wordStartPos = -1; + } + if (wordStartPos < 0 && IsWordStart (ccc)) { + wordStartPos = idx; + } + } + } + slice.Advance (numChars); + } while (hasWordSubsts); + if (identifier.Length == 0) + return null; + var ident = new Node (NodeKind.Identifier, identifier.ToString ()); + AddSubstitution (ident); + return ident; + } + + bool IsWordStart (char ch) + { + return !Char.IsDigit (ch) && ch != '_' && ch != (char)0; + } + + bool IsWordEnd (char ch, char prevCh) + { + if (ch == '_' || ch == (char)0) + return true; + if (!Char.IsUpper (prevCh) && Char.IsUpper (ch)) + return true; + return false; + } + + + Node DemangleOperatorIdentifier () + { + var ident = PopNode (NodeKind.Identifier); + if (ident == null) + return null; + var op_char_table = "& @/= > <*!|+?%-~ ^ ."; + StringBuilder opStr = new StringBuilder (); + foreach (var c in ident.Text) { + if (c > 0x7f) { + opStr.Append (c); + continue; + } + if (!Char.IsLower (c)) + return null; + char o = op_char_table [c - 'a']; + if (o == ' ') + return null; + opStr.Append (o); + } + switch (NextChar ()) { + case 'i': return new Node (NodeKind.InfixOperator, opStr.ToString ()); + case 'p': return new Node (NodeKind.PrefixOperator, opStr.ToString ()); + case 'P': return new Node (NodeKind.PostfixOperator, opStr.ToString ()); + default: return null; + } + } + + + Node DemangleLocalIdentifier () + { + if (NextIf ('L')) { + var discriminator = PopNode (NodeKind.Identifier); + var name = PopNode (IsDeclName); + return CreateWithChildren (NodeKind.PrivateDeclName, discriminator, name); + } + if (NextIf ('l')) { + var discriminator = PopNode (NodeKind.Identifier); + return CreateWithChild (NodeKind.PrivateDeclName, discriminator); + } + if ((PeekChar () >= 'a' && PeekChar () <= 'j') || + (PeekChar () >= 'A' && PeekChar () <= 'J')) { + var relatedEntityKind = NextChar (); + var name = PopNode (); + var result = new Node (NodeKind.RelatedEntityDeclName, relatedEntityKind.ToString ()); + return AddChild (result, name); + } + var discriminatorx = DemangleIndexAsNode (); + var namex = PopNode (IsDeclName); + return CreateWithChildren (NodeKind.LocalDeclName, discriminatorx, namex); + } + + Node PopModule () + { + var ident = PopNode (NodeKind.Identifier); + if (ident != null) + return ChangeKind (ident, NodeKind.Module); + return PopNode (NodeKind.Module); + } + + Node PopContext () + { + var mod = PopModule (); + if (mod != null) + return mod; + + var ty = PopNode (NodeKind.Type); + if (ty != null) { + if (ty.Children.Count != 1) + return null; + var child = ty.Children [0]; + if (!IsContext (child.Kind)) + return null; + return child; + } + return PopNode (IsContext); + } + + Node PopTypeAndGetChild () + { + var ty = PopNode (NodeKind.Type); + if (ty == null || ty.Children.Count != 1) + return null; + return ty.Children [0]; + } + + + Node PopTypeAndGetAnyGeneric () + { + var child = PopTypeAndGetChild (); + if (child != null && IsAnyGeneric (child.Kind)) + return child; + return null; + } + + Node DemangleBuiltinType () + { + Node ty = null; + const int maxTypeSize = 4096; + switch (NextChar ()) { + case 'b': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); + break; + case 'B': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); + break; + case 'f': { + var size = DemangleIndex () - 1; + if (size <= 0 || size > maxTypeSize) + return null; + var floatName = $"Builtin.FPIEEE{size}"; + ty = new Node (NodeKind.BuiltinTypeName, floatName); + break; + } + case 'i': { + var size = DemangleIndex () - 1; + if (size < 0 || size > maxTypeSize) + return null; + var intName = $"Builtin.Int{size}"; + ty = new Node (NodeKind.BuiltinTypeName, intName); + break; + } + case 'I': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.IntLiteral"); + break; + case 'v': + var elts = DemangleIndex () - 1; + if (elts <= 0 || elts > maxTypeSize) + return null; + var eltType = PopTypeAndGetChild (); + if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || + !eltType.Text.StartsWith ("Builtin.", StringComparison.Ordinal)) + return null; + var name = $"Builtin.Vec{elts}x{eltType.Text.Substring ("Builtin.".Length)}"; + ty = new Node (NodeKind.BuiltinTypeName, name); + break; + case 'O': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); + break; + case 'o': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.NativeObject"); + break; + case 'p': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.RawPointer"); + break; + case 't': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.SILToken"); + break; + case 'w': + ty = new Node (NodeKind.BuiltinTypeName, "Builtin.Word"); + break; + default: + return null; + } + return CreateType (ty); + } + + Node DemangleAnyGenericType (NodeKind kind) + { + var name = PopNode (IsDeclName); + var ctx = PopContext (); + var nty = CreateType (CreateWithChildren (kind, ctx, name)); + AddSubstitution (nty); + return nty; + } + + Node DemangleExtensionContext () + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var module = PopModule (); + var type = PopTypeAndGetAnyGeneric (); + var ext = CreateWithChildren (NodeKind.Extension, module, type); + if (genSig != null) + ext = AddChild (ext, genSig); + return ext; + } + + Node DemanglePlainFunction () + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var type = PopFunctionType (NodeKind.FunctionType); + var labelList = PopFunctionParamLabels (type); + + if (genSig != null) { + type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); + } + + var name = PopNode (IsDeclName); + var ctx = PopContext (); + + if (labelList != null) + return CreateWithChildren (NodeKind.Function, ctx, name, labelList, type); + return CreateWithChildren (NodeKind.Function, ctx, name, type); + } + + + Node PopFunctionType (NodeKind kind) + { + var funcType = new Node (kind); + AddChild (funcType, PopNode (NodeKind.ThrowsAnnotation)); + funcType = AddChild (funcType, PopFunctionParams (NodeKind.ArgumentTuple)); + funcType = AddChild (funcType, PopFunctionParams (NodeKind.ReturnType)); + return CreateType (funcType); + } + + Node PopFunctionParams (NodeKind kind) + { + Node paramsType = null; + if (PopNode (NodeKind.EmptyList) != null) { + paramsType = CreateType (new Node (NodeKind.Tuple)); + } else { + paramsType = PopNode (NodeKind.Type); + } + Node node = null; + + if (paramsType != null && kind == NodeKind.ArgumentTuple) { + var @params = paramsType.Children [0]; + var numParams = @params.Kind == NodeKind.Tuple ? @params.Children.Count : 1; + node = new Node (kind, numParams); + } else { + node = new Node (kind); + } + + return AddChild (node, paramsType); + } + + Node PopFunctionParamLabels (Node type) + { + if (!isOldFunctionTypeMangling && PopNode (NodeKind.EmptyList) != null) + return new Node (NodeKind.LabelList); + + if (type == null || type.Kind != NodeKind.Type) + return null; + + var funcType = type.Children [0]; + if (funcType.Kind == NodeKind.DependentGenericType) + funcType = funcType.Children [1].Children [0]; + + if (funcType.Kind != NodeKind.FunctionType && funcType.Kind != NodeKind.NoEscapeFunctionType) + return null; + + var parameterType = funcType.Children [0]; + if (parameterType.Kind == NodeKind.ThrowsAnnotation) + parameterType = funcType.Children [1]; + + + if (parameterType.Index == 0) + return null; + + Func> getChildIf = (node, filterBy) => { + for (int i = 0, n = node.Children.Count; i != n; ++i) { + var child = node.Children [i]; + if (child.Kind == filterBy) + return new KeyValuePair (child, i); + } + return new KeyValuePair (null, 0); + }; + + Func getLabel = (@params, idx) => { + if (isOldFunctionTypeMangling) { + var param = @params.Children [idx]; + var label = getChildIf (param, NodeKind.TupleElementName); + + if (label.Key != null) { + param.RemoveChildAt (label.Value); + return new Node (NodeKind.Identifier, label.Key.Text); + } + return new Node (NodeKind.FirstElementMarker); + } + return PopNode (); + }; + + var labelList = new Node (NodeKind.LabelList); + var tuple = parameterType.Children [0].Children [0]; + + if (isOldFunctionTypeMangling && (tuple != null || tuple.Kind != NodeKind.Tuple)) + return labelList; + + var hasLabels = false; + for (int i = 0; i != parameterType.Index; ++i) { + var label = getLabel (tuple, i); + if (label == null) + return null; + + if (label.Kind != NodeKind.Identifier && label.Kind != NodeKind.FirstElementMarker) + return null; + + labelList.AddChild (label); + hasLabels |= label.Kind != NodeKind.FirstElementMarker; + } + + if (!hasLabels) + return new Node (NodeKind.LabelList); + + if (!isOldFunctionTypeMangling) + labelList.ReverseChildren (); + + return labelList; + } + + Node PopTuple () + { + var root = new Node (NodeKind.Tuple); + + if (PopNode (NodeKind.EmptyList) == null) { + var firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker)) != null; + var tupleElmt = new Node (NodeKind.TupleElement); + AddChild (tupleElmt, PopNode (NodeKind.VariadicMarker)); + Node ident; + if ((ident = PopNode (NodeKind.Identifier)) != null) { + tupleElmt.AddChild (new Node (NodeKind.TupleElementName, ident.Text)); + } + var ty = PopNode (NodeKind.Type); + if (ty == null) + return null; + tupleElmt.AddChild (ty); + root.AddChild (tupleElmt); + } while (!firstElem); + + root.ReverseChildren (); + } + return CreateType (root); + } + + Node PopTypeList () + { + var root = new Node (NodeKind.TypeList); + + if (PopNode (NodeKind.EmptyList) == null) { + var firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker) != null); + var ty = PopNode (NodeKind.Type); + if (ty == null) + return ty; + root.AddChild (ty); + } while (!firstElem); + root.ReverseChildren (); + } + return root; + } + + Node PopProtocol () + { + Node type; + if ((type = PopNode (NodeKind.Type)) != null) { + if (type.Children.Count < 1) + return null; + + if (!IsProtocolNode (type)) + return null; + return type; + } + + Node symbolicRef; + if ((symbolicRef = PopNode (NodeKind.ProtocolSymbolicReference)) != null) { + return symbolicRef; + } + + var name = PopNode (IsDeclName); + var ctx = PopContext (); + var proto = CreateWithChildren (NodeKind.Protocol, ctx, name); + return CreateType (proto); + } + + Node PopAnyProtocolConformanceList () + { + var conformanceList = new Node (NodeKind.AnyProtocolConformanceList); + if (PopNode (NodeKind.EmptyList) == null) { + var firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker) != null); + var anyConformance = PopAnyProtocolConformance (); + if (anyConformance == null) + return null; + conformanceList.AddChild (anyConformance); + } while (!firstElem); + conformanceList.ReverseChildren (); + } + return conformanceList; + } + + Node PopAnyProtocolConformance () + { + return PopNode ((kind) => { + switch (kind) { + case NodeKind.ConcreteProtocolConformance: + case NodeKind.DependentProtocolConformanceRoot: + case NodeKind.DependentProtocolConformanceInherited: + case NodeKind.DependentProtocolConformanceAssociated: + return true; + default: + return false; + } + }); + } + + Node DemangleRetroactiveProtocolConformanceRef () + { + var module = PopModule (); + var proto = PopProtocol (); + var protocolConformanceRef = CreateWithChildren (NodeKind.ProtocolConformanceRefInOtherModule, proto, module); + return protocolConformanceRef; + } + + Node DemangleConcreteProtocolConformance () + { + var conditionalConformanceList = PopAnyProtocolConformanceList (); + + var conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInTypeModule); + if (conformanceRef == null) { + conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInProtocolModule); + } + if (conformanceRef == null) + conformanceRef = DemangleRetroactiveProtocolConformanceRef (); + + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.ConcreteProtocolConformance, + type, conformanceRef, conditionalConformanceList); + } + + + Node DemangleProtocolConformance () + { + var conditionalConformanceList = PopAnyProtocolConformanceList (); + + var conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInTypeModule); + if (conformanceRef == null) { + conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInProtocolModule); + } + + if (conformanceRef == null) + conformanceRef = DemangleRetroactiveProtocolConformanceRef (); + + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.ConcreteProtocolConformance, type, conformanceRef, conditionalConformanceList); + } + + Node PopDependentProtocolConformance () + { + return PopNode ((kind) => { + switch (kind) { + case NodeKind.DependentProtocolConformanceRoot: + case NodeKind.DependentProtocolConformanceInherited: + case NodeKind.DependentProtocolConformanceAssociated: + return true; + default: + return false; + } + }); + } + + Node DemangleDependentProtocolConformanceRoot () + { + var index = DemangleIndex (); + var conformance = + index > 0 ? new Node (NodeKind.DependentProtocolConformanceRoot, index - 1) + : new Node (NodeKind.DependentProtocolConformanceRoot); + Node protocol = null; + if ((protocol = PopProtocol ()) != null) + conformance.AddChild (protocol); + else + return null; + + Node dependentType; + if ((dependentType = PopNode (NodeKind.Type)) != null) + conformance.AddChild (dependentType); + else + return null; + + return conformance; + } + + Node DemangleDependentProtocolConformanceInherited () + { + var index = DemangleIndex (); + var conformance = + index > 0 ? new Node (NodeKind.DependentProtocolConformanceInherited, index - 1) + : new Node (NodeKind.DependentProtocolConformanceInherited); + Node protocol; + if ((protocol = PopProtocol ()) != null) + conformance.AddChild (protocol); + else + return null; + + Node nested; + + if ((nested = PopDependentProtocolConformance ()) != null) + conformance.AddChild (nested); + else + return null; + + conformance.ReverseChildren (); + return conformance; + } + + Node PopDependentAssociatedConformance () + { + var protocol = PopProtocol (); + var dependentType = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.DependentAssociatedConformance, dependentType, protocol); + } + + Node DemangleDependentProtocolConformanceAssociated () + { + var index = DemangleIndex (); + var conformance = index > 0 ? new Node (NodeKind.DependentProtocolConformanceRoot, index - 1) + : new Node (NodeKind.DependentProtocolConformanceRoot); + + Node associatedConformance; + if ((associatedConformance = PopDependentAssociatedConformance ()) != null) + conformance.AddChild (associatedConformance); + else + return null; + + Node nested; + if ((nested = PopDependentProtocolConformance ()) != null) + conformance.AddChild (nested); + else + return null; + + conformance.ReverseChildren (); + + return conformance; + } + + Node DemangleRetroactiveConformance () + { + var index = DemangleIndex (); + if (index < 0) + return null; + + var conformance = PopAnyProtocolConformance (); + if (conformance == null) + return null; + + var retroactiveConformance = new Node (NodeKind.RetroactiveConformance, index); + retroactiveConformance.AddChild (conformance); + return retroactiveConformance; + } + + Node DemangleBoundGenericType () + { + Node retroactiveConformances = null; + Node retroactiveConformance; + while ((retroactiveConformance = PopNode (NodeKind.RetroactiveConformance)) != null) { + if (retroactiveConformances == null) + retroactiveConformances = new Node (NodeKind.TypeList); + retroactiveConformances.AddChild (retroactiveConformance); + } + if (retroactiveConformances != null) + retroactiveConformances.ReverseChildren (); + + var typeListList = new List (); + for (; ; ) { + var tlist = new Node (NodeKind.TypeList); + typeListList.Add (tlist); + Node ty; + while ((ty = PopNode (NodeKind.Type)) != null) { + tlist.AddChild (ty); + } + tlist.ReverseChildren (); + if (PopNode (NodeKind.EmptyList) != null) + break; + if (PopNode (NodeKind.FirstElementMarker) == null) + return null; + } + var nominal = PopTypeAndGetAnyGeneric (); + var boundNode = DemangleBoundGenericArgs (nominal, typeListList, 0); + AddChild (boundNode, retroactiveConformances); + var nty = CreateType (boundNode); + AddSubstitution (nty); + return nty; + } + + Node DemangleBoundGenericArgs (Node nominal, List typeLists, int typeListIdx) + { + if (nominal == null) + return null; + + if (typeListIdx >= typeLists.Count) + return null; + + if (nominal.Kind == NodeKind.TypeSymbolicReference || nominal.Kind == NodeKind.ProtocolSymbolicReference) { + var remainingTypeList = new Node (NodeKind.TypeList); + for (int i = typeLists.Count - 1; i >= typeListIdx && i < typeLists.Count; --i) { + var list = typeLists [i]; + foreach (var child in list.Children) { + remainingTypeList.AddChild (child); + } + } + return CreateWithChildren (NodeKind.BoundGenericOtherNominalType, CreateType (nominal), remainingTypeList); + } + + if (nominal.Children.Count == 0) + return null; + var context = nominal.Children [0]; + + var consumesGenericArgs = true; + switch (nominal.Kind) { + case NodeKind.Variable: + case NodeKind.ExplicitClosure: + case NodeKind.Subscript: + consumesGenericArgs = false; + break; + default: + break; + } + + var args = typeLists [typeListIdx]; + if (consumesGenericArgs) + ++typeListIdx; + + if (typeListIdx < typeLists.Count) { + Node boundParent = null; + if (context.Kind == NodeKind.Extension) { + boundParent = DemangleBoundGenericArgs (context.Children [1], typeLists, typeListIdx); + boundParent = CreateWithChildren (NodeKind.Extension, context.Children [0], boundParent); + if (context.Children.Count == 3) { + AddChild (boundParent, context.Children [2]); + } + } else { + boundParent = DemangleBoundGenericArgs (context, typeLists, typeListIdx); + } + + var newNominal = CreateWithChild (nominal.Kind, boundParent); + if (newNominal == null) + return null; + + for (int idx = 1; idx < nominal.Children.Count; ++idx) { + AddChild (newNominal, nominal.Children [idx]); + } + nominal = newNominal; + } + if (!consumesGenericArgs) + return nominal; + + if (args.Children.Count == 0) + return nominal; + + NodeKind kind; + switch (nominal.Kind) { + case NodeKind.Class: + kind = NodeKind.BoundGenericClass; + break; + case NodeKind.Structure: + kind = NodeKind.BoundGenericStructure; + break; + case NodeKind.Enum: + kind = NodeKind.BoundGenericEnum; + break; + case NodeKind.Protocol: + kind = NodeKind.BoundGenericProtocol; + break; + case NodeKind.OtherNominalType: + kind = NodeKind.BoundGenericOtherNominalType; + break; + case NodeKind.TypeAlias: + kind = NodeKind.BoundGenericTypeAlias; + break; + case NodeKind.Function: + case NodeKind.Constructor: + return CreateWithChildren (NodeKind.BoundGenericFunction, nominal, args); + default: + return null; + } + return CreateWithChildren (kind, CreateType (nominal), args); + } + + Node DemangleImpleParamConvention () + { + string attr = null; + switch (NextChar ()) { + case 'i': attr = "@in"; break; + case 'c': attr = "@in_constant"; break; + case 'l': attr = "@inout"; break; + case 'b': attr = "@inout_aliasable"; break; + case 'n': attr = "@in_guaranteed"; break; + case 'x': attr = "@owned"; break; + case 'g': attr = "@guaranteed"; break; + case 'e': attr = "@deallocating"; break; + case 'y': attr = "@unowned"; break; + default: + PushBack (); + return null; + } + return CreateWithChild (NodeKind.ImplParameter, new Node (NodeKind.ImplConvention, attr)); + } + + Node DemangleImplResultConvention (NodeKind convKind) + { + string attr = null; + switch (NextChar ()) { + case 'r': attr = "@out"; break; + case 'o': attr = "@owned"; break; + case 'd': attr = "@unowned"; break; + case 'u': attr = "@unowned_inner_pointer"; break; + case 'a': attr = "@autoreleased"; break; + default: + PushBack (); + return null; + } + return CreateWithChild (convKind, new Node (NodeKind.ImplConvention, attr)); + } + + Node DemangleImplFunctionType () + { + var type = new Node (NodeKind.ImplFunctionType); + + var genSig = PopNode (NodeKind.DependentGenericSignature); + if (genSig != null && NextIf ('P')) + genSig = ChangeKind (genSig, NodeKind.DependentPseudogenericSignature); + + if (NextIf ('e')) + type.AddChild (new Node (NodeKind.ImplEscaping)); + + string cattr = null; + switch (NextChar ()) { + case 'y': cattr = "@callee_unowned"; break; + case 'g': cattr = "@callee_guaranteed"; break; + case 'x': cattr = "@callee_owned"; break; + case 't': cattr = "@convention(thin)"; break; + default: + return null; + } + type.AddChild (new Node (NodeKind.ImplConvention, cattr)); + + string fattr = null; + switch (NextChar ()) { + case 'B': fattr = "@convention(block)"; break; + case 'C': fattr = "@convention(c)"; break; + case 'M': fattr = "@convention(method)"; break; + case 'O': fattr = "@convention(objc_method)"; break; + case 'K': fattr = "@convention(closure)"; break; + case 'W': fattr = "@convention(witness_method)"; break; + default: + PushBack (); + break; + } + if (fattr != null) + type.AddChild (new Node (NodeKind.ImplFunctionAttribute, fattr)); + + AddChild (type, genSig); + + var numTypesToAdd = 0; + Node param; + while ((param = DemangleImpleParamConvention ()) != null) { + type = AddChild (type, param); + numTypesToAdd++; + } + Node result; + while ((result = DemangleImplResultConvention (NodeKind.ImplResult)) != null) { + type = AddChild (type, result); + numTypesToAdd++; + } + if (NextIf ('z')) { + var errorResult = DemangleImplResultConvention (NodeKind.ImplErrorResult); + if (errorResult == null) + return null; + type = AddChild (type, errorResult); + numTypesToAdd++; + } + if (!NextIf ('_')) + return null; + + for (int idx = 0; idx < numTypesToAdd; ++idx) { + var convTy = PopNode (NodeKind.Type); + if (convTy == null) + return null; + type.Children [type.Children.Count - idx - 1].AddChild (convTy); + } + + return CreateType (type); + } + + Node DemangleMetatype () + { + switch (NextChar ()) { + case 'c': + return CreateWithChild (NodeKind.ProtocolConformanceDescriptor, PopProtocolConformance ()); + case 'f': + return CreateWithPoppedType (NodeKind.FullTypeMetadata); + case 'P': + return CreateWithPoppedType (NodeKind.GenericTypeMetadataPattern); + case 'a': + return CreateWithPoppedType (NodeKind.TypeMetadataAccessFunction); + case 'I': + return CreateWithPoppedType (NodeKind.TypeMetadataInstantiationCache); + case 'i': + return CreateWithPoppedType (NodeKind.TypeMetadataInstantiationFunction); + case 'r': + return CreateWithPoppedType (NodeKind.TypeMetadataCompletionFunction); + case 'l': + return CreateWithPoppedType ( + NodeKind.TypeMetadataSingletonInitializationCache); + case 'L': + return CreateWithPoppedType (NodeKind.TypeMetadataLazyCache); + case 'm': + return CreateWithPoppedType (NodeKind.Metaclass); + case 'n': + return CreateWithPoppedType (NodeKind.NominalTypeDescriptor); + case 'o': + return CreateWithPoppedType (NodeKind.ClassMetadataBaseOffset); + case 'p': + return CreateWithChild (NodeKind.ProtocolDescriptor, PopProtocol ()); + case 'S': + return CreateWithChild (NodeKind.ProtocolSelfConformanceDescriptor, + PopProtocol ()); + case 'u': + return CreateWithPoppedType (NodeKind.MethodLookupFunction); + case 'U': + return CreateWithPoppedType (NodeKind.ObjCMetadataUpdateFunction); + case 'B': + return CreateWithChild (NodeKind.ReflectionMetadataBuiltinDescriptor, + PopNode (NodeKind.Type)); + case 'F': + return CreateWithChild (NodeKind.ReflectionMetadataFieldDescriptor, + PopNode (NodeKind.Type)); + case 'A': + return CreateWithChild (NodeKind.ReflectionMetadataAssocTypeDescriptor, + PopProtocolConformance ()); + case 'C': { + Node Ty = PopNode (NodeKind.Type); + if (Ty == null || !IsAnyGeneric (Ty.Children [0].Kind)) + return null; + return CreateWithChild (NodeKind.ReflectionMetadataSuperclassDescriptor, + Ty.Children [0]); + } + case 'V': + return CreateWithChild (NodeKind.PropertyDescriptor, + PopNode (IsEntity)); + case 'X': + return DemanglePrivateContextDescriptor (); + default: + return null; + } + } + + Node DemanglePrivateContextDescriptor () + { + switch (NextChar ()) { + case 'E': { + var extension = PopContext (); + if (extension == null) + return null; + return CreateWithChild (NodeKind.ExtensionDescriptor, extension); + } + case 'M': { + var module = PopModule (); + if (module == null) + return null; + return CreateWithChild (NodeKind.ModuleDescriptor, module); + } + case 'Y': { + var discriminator = PopNode (); + if (discriminator == null) + return null; + var context = PopContext (); + if (context == null) + return null; + + var node = new Node (NodeKind.AnonymousDescriptor); + node.AddChild (context); + node.AddChild (discriminator); + return node; + } + case 'X': { + var context = PopContext (); + if (context == null) + return null; + return CreateWithChild (NodeKind.AnonymousDescriptor, context); + } + case 'A': { + var path = PopAssocTypePath (); + if (path == null) + return null; + var @base = PopNode (NodeKind.Type); + if (@base == null) + return null; + return CreateWithChildren (NodeKind.AssociatedTypeGenericParamRef, + @base, path); + } + default: + return null; + } + } + + Node DemangleArchetype () + { + switch (NextChar ()) { + case 'a': { + var ident = PopNode (NodeKind.Identifier); + var archeTy = PopTypeAndGetChild (); + var assocTy = CreateType (CreateWithChildren (NodeKind.AssociatedTypeRef, archeTy, ident)); + AddSubstitution (assocTy); + return assocTy; + } + case 'y': { + var t = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); + AddSubstitution (t); + return t; + } + case 'z': { + var t = DemangleAssociatedTypeSimple (GetDependentGenericParamType (0, 0)); + AddSubstitution (t); + return t; + } + case 'Y': { + var t = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); + AddSubstitution (t); + return t; + } + case 'Z': { + var t = DemangleAssociatedTypeCompound (GetDependentGenericParamType (0, 0)); + AddSubstitution (t); + return t; + } + default: + return null; + } + } + + Node DemangleAssociatedTypeSimple (Node genericParamIdx) + { + var GPI = CreateType (genericParamIdx); + var ATName = PopAssocTypeName (); + return CreateType (CreateWithChildren (NodeKind.DependentMemberType, GPI, ATName)); + } + + Node DemangleAssociatedTypeCompound (Node genericParamIdx) + { + var assocTyNames = new List (); + bool firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker) != null); + var assocTyName = PopAssocTypeName (); + if (assocTyName == null) + return null; + assocTyNames.Add (assocTyName); + } while (!firstElem); + + var @base = genericParamIdx; + + + for (int i = assocTyNames.Count - 1; i >= 0; --i) { + var assocTy = assocTyNames [i]; + var depTy = new Node (NodeKind.DependentMemberType); + depTy = AddChild (depTy, CreateType (@base)); + @base = AddChild (depTy, assocTy); + } + return CreateType (@base); + } + + Node PopAssocTypeName () + { + var proto = PopNode (NodeKind.Type); + if (proto != null && !IsProtocolNode (proto)) + return null; + + // If we haven't seen a protocol, check for a symbolic reference. + if (proto == null) + proto = PopNode (NodeKind.ProtocolSymbolicReference); + + var id = PopNode (NodeKind.Identifier); + var assocTy = ChangeKind (id, NodeKind.DependentAssociatedTypeRef); + AddChild (assocTy, proto); + return assocTy; + } + + Node PopAssocTypePath () + { + var assocTypePath = new Node (NodeKind.AssocTypePath); + bool firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker) != null); + var assocTy = PopAssocTypeName (); + if (assocTy == null) + return null; + assocTypePath.AddChild (assocTy); + } while (!firstElem); + assocTypePath.ReverseChildren (); + return assocTypePath; + } + + Node GetDependentGenericParamType (int depth, int index) + { + if (depth < 0 || index < 0) + return null; + + StringBuilder name = new StringBuilder (); + int idxChar = index; + do { + name.Append ((char)('A' + (idxChar % 26))); + idxChar /= 26; + } while (idxChar > 0); + if (depth != 0) + name.Append (depth); + + var paramTy = new Node (NodeKind.DependentGenericParamType, name.ToString ()); + paramTy.AddChild (new Node (NodeKind.Index, depth)); + paramTy.AddChild (new Node (NodeKind.Index, index)); + return paramTy; + } + + Node DemangleGenericParamIndex () + { + if (NextIf ('d')) { + int depth = DemangleIndex () + 1; + int index = DemangleIndex (); + return GetDependentGenericParamType (depth, index); + } + if (NextIf ('z')) { + return GetDependentGenericParamType (0, 0); + } + return GetDependentGenericParamType (0, DemangleIndex () + 1); + } + + Node PopProtocolConformance () + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var module = PopModule (); + var proto = PopProtocol (); + var type = PopNode (NodeKind.Type); + Node Ident = null; + if (type == null) { + // Property behavior conformance + Ident = PopNode (NodeKind.Identifier); + type = PopNode (NodeKind.Type); + } + if (genSig != null) { + type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); + } + var Conf = CreateWithChildren (NodeKind.ProtocolConformance, type, proto, module); + AddChild (Conf, Ident); + return Conf; + } + + Node DemangleThunkOrSpecialization () + { + var c = NextChar (); + switch (c) { + case 'c': return CreateWithChild (NodeKind.CurryThunk, PopNode (IsEntity)); + case 'j': return CreateWithChild (NodeKind.DispatchThunk, PopNode (IsEntity)); + case 'q': return CreateWithChild (NodeKind.MethodDescriptor, PopNode (IsEntity)); + case 'o': return new Node (NodeKind.ObjCAttribute); + case 'O': return new Node (NodeKind.NonObjCAttribute); + case 'D': return new Node (NodeKind.DynamicAttribute); + case 'd': return new Node (NodeKind.DirectMethodReferenceAttribute); + case 'a': return new Node (NodeKind.PartialApplyObjCForwarder); + case 'A': return new Node (NodeKind.PartialApplyForwarder); + case 'm': return new Node (NodeKind.MergedFunction); + case 'X': return new Node (NodeKind.DynamicallyReplaceableFunctionVar); + case 'x': return new Node (NodeKind.DynamicallyReplaceableFunctionKey); + case 'I': return new Node (NodeKind.DynamicallyReplaceableFunctionImpl); + case 'C': { + var type = PopNode (NodeKind.Type); + return CreateWithChild (NodeKind.CoroutineContinuationPrototype, type); + } + case 'V': { + var @base = PopNode (IsEntity); + var derived = PopNode (IsEntity); + return CreateWithChildren (NodeKind.VTableThunk, derived, @base); + } + case 'W': { + var entity = PopNode (IsEntity); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.ProtocolWitness, conf, entity); + } + case 'S': + return CreateWithChild (NodeKind.ProtocolSelfConformanceWitness, + PopNode (IsEntity)); + case 'R': + case 'r': { + var thunk = new Node (c == 'R' ? + NodeKind.ReabstractionThunkHelper : + NodeKind.ReabstractionThunk); + Node genSig; + if ((genSig = PopNode (NodeKind.DependentGenericSignature)) != null) + AddChild (thunk, genSig); + var Ty2 = PopNode (NodeKind.Type); + thunk = AddChild (thunk, PopNode (NodeKind.Type)); + return AddChild (thunk, Ty2); + } + case 'g': + return DemangleGenericSpecialization (NodeKind.GenericSpecialization); + case 'G': + return DemangleGenericSpecialization (NodeKind.GenericSpecializationNotReAbstracted); + case 'i': + return DemangleGenericSpecialization (NodeKind.InlinedGenericFunction); + case 'p': { + var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecialization); + var param = CreateWithChild (NodeKind.GenericSpecializationParam, PopNode (NodeKind.Type)); + return AddChild (spec, param); + } + case 'P': { + var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecializationNotReAbstracted); + var param = CreateWithChild (NodeKind.GenericSpecializationParam, PopNode (NodeKind.Type)); + return AddChild (spec, param); + } + case 'f': + return DemangleFunctionSpecialization (); + case 'K': + case 'k': { + var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper + : NodeKind.KeyPathSetterThunkHelper; + var types = new List (); + var node = PopNode (); + if (node == null || node.Kind != NodeKind.Type) + return null; + do { + types.Add (node); + node = PopNode (); + } while (node != null && node.Kind == NodeKind.Type); + + Node result; + if (node != null) { + if (node.Kind == NodeKind.DependentGenericSignature) { + var decl = PopNode (); + if (decl == null) + return null; + result = CreateWithChildren (nodeKind, decl, /*sig*/ node); + } else { + result = CreateWithChild (nodeKind, /*decl*/ node); + } + } else { + return null; + } + foreach (var i in types) { + result.AddChild (i); + } + return result; + } + case 'l': { + var assocTypeName = PopAssocTypeName (); + if (assocTypeName == null) + return null; + + return CreateWithChild (NodeKind.AssociatedTypeDescriptor, + assocTypeName); + } + case 'L': + return CreateWithChild (NodeKind.ProtocolRequirementsBaseDescriptor, + PopProtocol ()); + case 'M': + return CreateWithChild (NodeKind.DefaultAssociatedTypeMetadataAccessor, + PopAssocTypeName ()); + + case 'n': { + var requirementTy = PopProtocol (); + var conformingType = PopAssocTypePath (); + var protoTy = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.AssociatedConformanceDescriptor, + protoTy, conformingType, requirementTy); + } + + case 'N': { + var requirementTy = PopProtocol (); + var assocTypePath = PopAssocTypePath (); + var protoTy = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.DefaultAssociatedConformanceAccessor, + protoTy, assocTypePath, requirementTy); + } + + case 'b': { + var requirementTy = PopProtocol (); + var protoTy = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.BaseConformanceDescriptor, + protoTy, requirementTy); + } + + case 'H': + case 'h': { + var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper + : NodeKind.KeyPathHashThunkHelper; + Node genericSig = null; + var types = new List (); + + var node = PopNode (); + if (node != null) { + if (node.Kind == NodeKind.DependentGenericSignature) { + genericSig = node; + } else if (node.Kind == NodeKind.Type) { + types.Add (node); + } else { + return null; + } + } else { + return null; + } + + Node node1; + while ((node1 = PopNode ()) != null) { + if (node1.Kind != NodeKind.Type) { + return null; + } + types.Add (node); + } + + var result = new Node (nodeKind); + foreach (var i in types) { + result.AddChild (i); + } + if (genericSig != null) + result.AddChild (genericSig); + return result; + } + case 'v': { + int idx = DemangleIndex (); + if (idx < 0) + return null; + return new Node (NodeKind.OutlinedVariable, idx); + } + case 'e': { + string @params = DemangleBridgedMethodParams (); + if (string.IsNullOrEmpty (@params)) + return null; + return new Node (NodeKind.OutlinedBridgedMethod, @params); + } + default: + return null; + } + } + + string DemangleBridgedMethodParams () + { + if (NextIf ('_')) + return ""; + + StringBuilder Str = new StringBuilder (); + + var kind = NextChar (); + switch (kind) { + default: + return ""; + case 'p': + case 'a': + case 'm': + Str.Append (kind); + break; + } + + while (!NextIf ('_')) { + var c = NextChar (); + if (c != 0 && c != 'n' && c != 'b') + return ""; + Str.Append (c); + } + return Str.ToString (); + } + + Node DemangleGenericSpecialization (NodeKind SpecKind) + { + var Spec = DemangleSpecAttributes (SpecKind); + if (Spec == null) + return null; + var TyList = PopTypeList (); + if (TyList == null) + return null; + foreach (var Ty in TyList.Children) { + Spec.AddChild (CreateWithChild (NodeKind.GenericSpecializationParam, Ty)); + } + return Spec; + } + + + Node DemangleFunctionSpecialization () + { + var spec = DemangleSpecAttributes (NodeKind.FunctionSignatureSpecialization); + ulong paramIdx = 0; + while (spec != null && !NextIf ('_')) { + spec = AddChild (spec, DemangleFuncSpecParam (paramIdx)); + paramIdx++; + } + if (!NextIf ('n')) + spec = AddChild (spec, DemangleFuncSpecParam ((~(ulong)0))); + + if (spec == null) + return null; + + // Add the required parameters in reverse order. + for (int idx = 0, num = spec.Children.Count; idx < num; ++idx) { + var param = spec.Children [num - idx - 1]; + if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) + continue; + + if (param.Children.Count == 0) + continue; + var kindNd = param.Children [0]; + var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; + switch (paramKind) { + case FunctionSigSpecializationParamKind.ConstantPropFunction: + case FunctionSigSpecializationParamKind.ConstantPropGlobal: + case FunctionSigSpecializationParamKind.ConstantPropString: + case FunctionSigSpecializationParamKind.ClosureProp: { + var fixedChildren = param.Children.Count; + Node ty; + while ((ty = PopNode (NodeKind.Type)) != null) { + if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) + return null; + param = AddChild (param, ty); + } + var name = PopNode (NodeKind.Identifier); + if (name == null) + return null; + string nameText = name.Text; + if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && !String.IsNullOrEmpty (nameText) + && nameText [0] == '_') { + // A '_' escapes a leading digit or '_' of a string constant. + nameText = nameText.Substring (1); + } + AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, nameText)); + param.ReverseChildren (fixedChildren); + break; + } + default: + break; + } + } + return spec; + } + + Node DemangleFuncSpecParam (ulong paramIdx) + { + var param = new Node (NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); + switch (NextChar ()) { + case 'n': + return param; + case 'c': + // Consumes an identifier and multiple type parameters. + // The parameters will be added later. + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ClosureProp)); + case 'p': { + switch (NextChar ()) { + case 'f': + // Consumes an identifier parameter, which will be added later. + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)(FunctionSigSpecializationParamKind.ConstantPropFunction))); + case 'g': + // Consumes an identifier parameter, which will be added later. + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); + case 'i': + return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropInteger); + case 'd': + return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropFloat); + case 's': { + // Consumes an identifier parameter (the string constant), + // which will be added later. + string encoding = null; + switch (NextChar ()) { + case 'b': encoding = "u8"; break; + case 'w': encoding = "u16"; break; + case 'c': encoding = "objc"; break; + default: return null; + } + AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropString)); + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); + } + default: + return null; + } + } + case 'e': { + uint value = (uint)FunctionSigSpecializationParamKind.ExistentialToGeneric; + if (NextIf ('D')) + value |= (uint)FunctionSigSpecializationParamKind.Dead; + if (NextIf ('G')) + value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf ('O')) + value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'd': { + uint value = (uint)FunctionSigSpecializationParamKind.Dead; + if (NextIf ('G')) + value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf ('O')) + value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'g': { + uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'o': { + uint value = (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf ('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'x': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.SROA)); + case 'i': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.BoxToValue)); + case 's': + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.BoxToStack)); + default: + return null; + } + } + + Node AddFuncSpecParamNumber (Node param, FunctionSigSpecializationParamKind kind) + { + param.AddChild (new Node (NodeKind.FunctionSignatureSpecializationParamKind, (uint)kind)); + var str = new StringBuilder (); + while (Char.IsDigit (PeekChar ())) { + str.Append (NextChar ()); + } + if (str.Length == 0) + return null; + return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString ())); + } + + Node DemangleSpecAttributes (NodeKind SpecKind) + { + bool isFragile = NextIf ('q'); + + int passID = (int)NextChar () - '0'; + if (passID < 0 || passID > 9) + return null; + + var specNd = new Node (SpecKind); + if (isFragile) + specNd.AddChild (new Node (NodeKind.SpecializationIsFragile)); + + specNd.AddChild (new Node (NodeKind.SpecializationPassID, passID)); + return specNd; + } + + Node DemangleWitness () + { + switch (NextChar ()) { + case 'C': + return CreateWithChild (NodeKind.EnumCase, PopNode (IsEntity)); + case 'V': + return CreateWithChild (NodeKind.ValueWitnessTable, PopNode (NodeKind.Type)); + case 'v': { + uint directness; + switch (NextChar ()) { + case 'd': directness = (uint)Directness.Direct; break; + case 'i': directness = (uint)Directness.Indirect; break; + default: return null; + } + return CreateWithChildren (NodeKind.FieldOffset, new Node (NodeKind.Directness, directness), + PopNode (IsEntity)); + } + case 'S': + return CreateWithChild (NodeKind.ProtocolSelfConformanceWitnessTable, PopProtocol ()); + case 'P': + return CreateWithChild (NodeKind.ProtocolWitnessTable, PopProtocolConformance ()); + case 'p': + return CreateWithChild (NodeKind.ProtocolWitnessTablePattern, PopProtocolConformance ()); + case 'G': + return CreateWithChild (NodeKind.GenericProtocolWitnessTable, PopProtocolConformance ()); + case 'I': + return CreateWithChild (NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance ()); + + case 'r': + return CreateWithChild (NodeKind.ResilientProtocolWitnessTable, PopProtocolConformance ()); + + case 'l': { + var conf = PopProtocolConformance (); + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.LazyProtocolWitnessTableAccessor, type, conf); + } + case 'L': { + var conf = PopProtocolConformance (); + var type = PopNode (NodeKind.Type); + return CreateWithChildren (NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); + } + case 'a': + return CreateWithChild (NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance ()); + case 't': { + var name = PopNode (IsDeclName); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name); + } + case 'T': { + var protoTy = PopNode (NodeKind.Type); + var conformingType = PopAssocTypePath (); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.AssociatedTypeWitnessTableAccessor, conf, conformingType, protoTy); + } + case 'b': { + var protoTy = PopNode (NodeKind.Type); + var conf = PopProtocolConformance (); + return CreateWithChildren (NodeKind.BaseWitnessTableAccessor, conf, protoTy); + } + case 'O': { + switch (NextChar ()) { + case 'y': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedCopy, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedCopy, PopNode (NodeKind.Type)); + } + case 'e': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedConsume, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedConsume, PopNode (NodeKind.Type)); + } + case 'r': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedRetain, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedRetain, PopNode (NodeKind.Type)); + } + case 's': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedRelease, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedRelease, PopNode (NodeKind.Type)); + } + case 'b': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedInitializeWithTake, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedInitializeWithTake, PopNode (NodeKind.Type)); + } + case 'c': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedInitializeWithCopy, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedInitializeWithCopy, PopNode (NodeKind.Type)); + } + case 'd': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedAssignWithTake, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedAssignWithTake, PopNode (NodeKind.Type)); + } + case 'f': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedAssignWithCopy, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedAssignWithCopy, PopNode (NodeKind.Type)); + } + case 'h': { + Node sig; + if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren (NodeKind.OutlinedDestroy, PopNode (NodeKind.Type), sig); + return CreateWithChild (NodeKind.OutlinedDestroy, PopNode (NodeKind.Type)); + } + default: + return null; + } + } + default: + return null; + } + } + + Node DemangleSpecialType () + { + char specialChar; + switch (specialChar = NextChar ()) { + case 'E': + return PopFunctionType (NodeKind.NoEscapeFunctionType); + case 'A': + return PopFunctionType (NodeKind.EscapingAutoClosureType); + case 'f': + return PopFunctionType (NodeKind.ThinFunctionType); + case 'K': + return PopFunctionType (NodeKind.AutoClosureType); + case 'U': + return PopFunctionType (NodeKind.UncurriedFunctionType); + case 'B': + return PopFunctionType (NodeKind.ObjCBlock); + case 'C': + return PopFunctionType (NodeKind.CFunctionPointer); + case 'o': + return CreateType (CreateWithChild (NodeKind.Unowned, PopNode (NodeKind.Type))); + case 'u': + return CreateType (CreateWithChild (NodeKind.Unmanaged, PopNode (NodeKind.Type))); + case 'w': + return CreateType (CreateWithChild (NodeKind.Weak, PopNode (NodeKind.Type))); + case 'b': + return CreateType (CreateWithChild (NodeKind.SILBoxType, PopNode (NodeKind.Type))); + case 'D': + return CreateType (CreateWithChild (NodeKind.DynamicSelf, PopNode (NodeKind.Type))); + case 'M': { + var MTR = DemangleMetatypeRepresentation (); + var type = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.Metatype, MTR, type)); + } + case 'm': { + var MTR = DemangleMetatypeRepresentation (); + var type = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.ExistentialMetatype, MTR, type)); + } + case 'p': + return CreateType (CreateWithChild (NodeKind.ExistentialMetatype, PopNode (NodeKind.Type))); + case 'c': { + var Superclass = PopNode (NodeKind.Type); + var Protocols = DemangleProtocolList (); + return CreateType (CreateWithChildren (NodeKind.ProtocolListWithClass, Protocols, Superclass)); + } + case 'l': { + var Protocols = DemangleProtocolList (); + return CreateType (CreateWithChild (NodeKind.ProtocolListWithAnyObject, Protocols)); + } + case 'X': + case 'x': { + // SIL box types. + Node signature = null, genericArgs = null; + if (specialChar == 'X') { + signature = PopNode (NodeKind.DependentGenericSignature); + if (signature == null) + return null; + genericArgs = PopTypeList (); + if (genericArgs == null) + return null; + } + + var fieldTypes = PopTypeList (); + if (fieldTypes == null) + return null; + // Build layout. + var layout = new Node (NodeKind.SILBoxLayout); + for (int i = 0, e = fieldTypes.Children.Count; i < e; ++i) { + var fieldType = fieldTypes.Children [i]; + bool isMutable = false; + // 'inout' typelist mangling is used to represent mutable fields. + if (fieldType.Children [0].Kind == NodeKind.InOut) { + isMutable = true; + fieldType = CreateType (fieldType.Children [0].Children [0]); + } + var field = new Node (isMutable + ? NodeKind.SILBoxMutableField + : NodeKind.SILBoxImmutableField); + field.AddChild (fieldType); + layout.AddChild (field); + } + var boxTy = new Node (NodeKind.SILBoxTypeWithLayout); + boxTy.AddChild (layout); + if (signature != null) { + boxTy.AddChild (signature); + boxTy.AddChild (genericArgs); + } + return CreateType (boxTy); + } + case 'Y': + return DemangleAnyGenericType (NodeKind.OtherNominalType); + case 'Z': { + var types = PopTypeList (); + var name = PopNode (NodeKind.Identifier); + var parent = PopContext (); + var anon = new Node (NodeKind.AnonymousContext); + anon = AddChild (anon, name); + anon = AddChild (anon, parent); + anon = AddChild (anon, types); + return anon; + } + case 'e': + return CreateType (new Node (NodeKind.ErrorType)); + default: + return null; + } + } + + Node DemangleMetatypeRepresentation () + { + switch (NextChar ()) { + case 't': + return new Node (NodeKind.MetatypeRepresentation, "@thin"); + case 'T': + return new Node (NodeKind.MetatypeRepresentation, "@thick"); + case 'o': + return new Node (NodeKind.MetatypeRepresentation, "@objc_metatype"); + default: + return null; + } + } + + Node DemangleAccessor (Node childNode) + { + NodeKind kind; + switch (NextChar ()) { + case 'm': kind = NodeKind.MaterializeForSet; break; + case 's': kind = NodeKind.Setter; break; + case 'g': kind = NodeKind.Getter; break; + case 'G': kind = NodeKind.GlobalGetter; break; + case 'w': kind = NodeKind.WillSet; break; + case 'W': kind = NodeKind.DidSet; break; + case 'r': kind = NodeKind.ReadAccessor; break; + case 'M': kind = NodeKind.ModifyAccessor; break; + case 'a': + switch (NextChar ()) { + case 'O': kind = NodeKind.OwningMutableAddressor; break; + case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; + case 'P': kind = NodeKind.NativePinningMutableAddressor; break; + case 'u': kind = NodeKind.UnsafeMutableAddressor; break; + default: return null; + } + break; + case 'l': + switch (NextChar ()) { + case 'O': kind = NodeKind.OwningAddressor; break; + case 'o': kind = NodeKind.NativeOwningAddressor; break; + case 'p': kind = NodeKind.NativePinningAddressor; break; + case 'u': kind = NodeKind.UnsafeAddressor; break; + default: return null; + } + break; + case 'p': // Pseudo-accessor referring to the variable/subscript itself + return childNode; + default: return null; + } + var entity = CreateWithChild (kind, childNode); + return entity; + } + + enum Args { + None, + TypeAndMaybePrivateName, + TypeAndIndex, + Index + } + + Node DemangleFunctionEntity () + { + var args = Args.None; + NodeKind Kind = NodeKind.EmptyList; + switch (NextChar ()) { + case 'D': args = Args.None; Kind = NodeKind.Deallocator; break; + case 'd': args = Args.None; Kind = NodeKind.Destructor; break; + case 'E': args = Args.None; Kind = NodeKind.IVarDestroyer; break; + case 'e': args = Args.None; Kind = NodeKind.IVarInitializer; break; + case 'i': args = Args.None; Kind = NodeKind.Initializer; break; + case 'C': + args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Allocator; break; + case 'c': + args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Constructor; break; + case 'U': args = Args.TypeAndIndex; Kind = NodeKind.ExplicitClosure; break; + case 'u': args = Args.TypeAndIndex; Kind = NodeKind.ImplicitClosure; break; + case 'A': args = Args.Index; Kind = NodeKind.DefaultArgumentInitializer; break; + case 'p': return DemangleEntity (NodeKind.GenericTypeParamDecl); + default: return null; + } + + Node nameOrIndex = null, paramType = null, labelList = null; + switch (args) { + case Args.None: + break; + case Args.TypeAndMaybePrivateName: + nameOrIndex = PopNode (NodeKind.PrivateDeclName); + paramType = PopNode (NodeKind.Type); + labelList = PopFunctionParamLabels (paramType); + break; + case Args.TypeAndIndex: + nameOrIndex = DemangleIndexAsNode (); + paramType = PopNode (NodeKind.Type); + break; + case Args.Index: + nameOrIndex = DemangleIndexAsNode (); + break; + } + var entity = CreateWithChild (Kind, PopContext ()); + switch (args) { + case Args.None: + break; + case Args.Index: + entity = AddChild (entity, nameOrIndex); + break; + case Args.TypeAndMaybePrivateName: + AddChild (entity, labelList); + entity = AddChild (entity, paramType); + AddChild (entity, nameOrIndex); + break; + case Args.TypeAndIndex: + entity = AddChild (entity, nameOrIndex); + entity = AddChild (entity, paramType); + break; + } + return entity; + } + + Node DemangleEntity (NodeKind Kind) + { + var type = PopNode (NodeKind.Type); + var labelList = PopFunctionParamLabels (type); + var name = PopNode (IsDeclName); + var context = PopContext (); + return labelList != null ? CreateWithChildren (Kind, context, name, labelList, type) + : CreateWithChildren (Kind, context, name, type); + } + + Node DemangleVariable () + { + var variable = DemangleEntity (NodeKind.Variable); + return DemangleAccessor (variable); + } + + Node DemangleSubscript () + { + var privateName = PopNode (NodeKind.PrivateDeclName); + var type = PopNode (NodeKind.Type); + var labelList = PopFunctionParamLabels (type); + var context = PopContext (); + + var subscript = new Node (NodeKind.Subscript); + subscript = AddChild (subscript, context); + AddChild (subscript, labelList); + subscript = AddChild (subscript, type); + AddChild (subscript, privateName); + + return DemangleAccessor (subscript); + } + + Node DemangleProtocolList () + { + var typeList = new Node (NodeKind.TypeList); + var protoList = CreateWithChild (NodeKind.ProtocolList, typeList); + if (PopNode (NodeKind.EmptyList) == null) { + bool firstElem = false; + do { + firstElem = (PopNode (NodeKind.FirstElementMarker) != null); + var proto = PopProtocol (); + if (proto == null) + return null; + typeList.AddChild (proto); + } while (!firstElem); + + typeList.ReverseChildren (); + } + return protoList; + } + + Node DemangleProtocolListType () + { + var protoList = DemangleProtocolList (); + return CreateType (protoList); + } + + Node DemangleGenericSignature (bool hasParamCounts) + { + var Sig = new Node (NodeKind.DependentGenericSignature); + if (hasParamCounts) { + while (!NextIf ('l')) { + int count = 0; + if (!NextIf ('z')) + count = DemangleIndex () + 1; + if (count < 0) + return null; + Sig.AddChild (new Node (NodeKind.DependentGenericParamCount, count)); + } + } else { + Sig.AddChild (new Node (NodeKind.DependentGenericParamCount, 1)); + } + var NumCounts = Sig.Children.Count; + Node Req; + while ((Req = PopNode (IsRequirement)) != null) { + Sig.AddChild (Req); + } + Sig.ReverseChildren (NumCounts); + return Sig; + } + + enum TypeKind { + Generic, + Assoc, + CompoundAssoc, + Substitution + } + + enum ConstraintKind { + Protocol, + BaseClass, + SameType, + Layout + } + + Node DemangleGenericRequirement () + { + TypeKind typeKind; + ConstraintKind constraintKind; + + switch (NextChar ()) { + case 'c': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Assoc; break; + case 'C': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.CompoundAssoc; break; + case 'b': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Generic; break; + case 'B': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Substitution; break; + case 't': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Assoc; break; + case 'T': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.CompoundAssoc; break; + case 's': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Generic; break; + case 'S': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Substitution; break; + case 'm': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Assoc; break; + case 'M': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.CompoundAssoc; break; + case 'l': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Generic; break; + case 'L': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Substitution; break; + case 'p': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Assoc; break; + case 'P': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.CompoundAssoc; break; + case 'Q': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Substitution; break; + default: constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Generic; PushBack (); break; + } + + Node ConstrTy = null; + + switch (typeKind) { + case TypeKind.Generic: + ConstrTy = CreateType (DemangleGenericParamIndex ()); + break; + case TypeKind.Assoc: + ConstrTy = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); + AddSubstitution (ConstrTy); + break; + case TypeKind.CompoundAssoc: + ConstrTy = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); + AddSubstitution (ConstrTy); + break; + case TypeKind.Substitution: + ConstrTy = PopNode (NodeKind.Type); + break; + } + + switch (constraintKind) { + case ConstraintKind.Protocol: + return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopProtocol ()); + case ConstraintKind.BaseClass: + return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopNode (NodeKind.Type)); + case ConstraintKind.SameType: + return CreateWithChildren (NodeKind.DependentGenericSameTypeRequirement, ConstrTy, PopNode (NodeKind.Type)); + case ConstraintKind.Layout: { + var c = NextChar (); + Node size = null; + Node alignment = null; + string name = null; + if (c == 'U') { + name = "U"; + } else if (c == 'R') { + name = "R"; + } else if (c == 'N') { + name = "N"; + } else if (c == 'C') { + name = "C"; + } else if (c == 'D') { + name = "D"; + } else if (c == 'T') { + name = "T"; + } else if (c == 'E') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + alignment = DemangleIndexAsNode (); + name = "E"; + } else if (c == 'e') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + name = "e"; + } else if (c == 'M') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + alignment = DemangleIndexAsNode (); + name = "M"; + } else if (c == 'm') { + size = DemangleIndexAsNode (); + if (size == null) + return null; + name = "m"; + } else { + // Unknown layout constraint. + return null; + } + + var NameNode = new Node (NodeKind.Identifier, name); + var LayoutRequirement = CreateWithChildren (NodeKind.DependentGenericLayoutRequirement, ConstrTy, NameNode); + if (size != null) + AddChild (LayoutRequirement, size); + if (alignment != null) + AddChild (LayoutRequirement, alignment); + return LayoutRequirement; + } + } + return null; + } + + Node DemangleGenericType () + { + var genSig = PopNode (NodeKind.DependentGenericSignature); + var ty = PopNode (NodeKind.Type); + return CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, ty)); + } + + int DecodeValueWitnessKind (string codeStr) + { + switch (codeStr) { + case "al": return (int)ValueWitnessKind.AllocateBuffer; + case "ca": return (int)ValueWitnessKind.AssignWithCopy; + case "ta": return (int)ValueWitnessKind.AssignWithTake; + case "de": return (int)ValueWitnessKind.DeallocateBuffer; + case "xx": return (int)ValueWitnessKind.Destroy; + case "XX": return (int)ValueWitnessKind.DestroyBuffer; + case "Xx": return (int)ValueWitnessKind.DestroyArray; + case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; + case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; + case "cp": return (int)ValueWitnessKind.InitializeWithCopy; + case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; + case "tk": return (int)ValueWitnessKind.InitializeWithTake; + case "pr": return (int)ValueWitnessKind.ProjectBuffer; + case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; + case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; + case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; + case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; + case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; + case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; + case "ug": return (int)ValueWitnessKind.GetEnumTag; + case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; + case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; + case "et": return (int)ValueWitnessKind.GetEnumTagSinglePayload; + case "st": return (int)ValueWitnessKind.StoreEnumTagSinglePayload; + default: + return -1; + } + } + + Node DemangleValueWitness () + { + char [] code = new char [2]; + code [0] = NextChar (); + code [1] = NextChar (); + int kind = DecodeValueWitnessKind (new string (code)); + if (kind < 0) + return null; + var vw = new Node (NodeKind.ValueWitness, (uint)kind); + return AddChild (vw, PopNode (NodeKind.Type)); + } + + Node DemangleObjCTypeName () + { + var ty = new Node (NodeKind.Type); + var global = AddChild (new Node (NodeKind.Global), AddChild (new Node (NodeKind.TypeMangling), ty)); + Node nominal = null; + bool isProto = false; + if (NextIf ('C')) { + nominal = new Node (NodeKind.Class); + AddChild (ty, nominal); + } else if (NextIf ('P')) { + isProto = true; + nominal = new Node (NodeKind.Protocol); + AddChild (ty, AddChild (new Node (NodeKind.ProtocolList), + AddChild (new Node (NodeKind.TypeList), + AddChild (new Node (NodeKind.Type), nominal)))); + } else { + return null; + } + + if (NextIf ('s')) { + nominal.AddChild (new Node (NodeKind.Module, "Swift")); + } else { + var Module = DemangleIdentifier (); + if (Module == null) + return null; + nominal.AddChild (ChangeKind (Module, NodeKind.Module)); + } + + var ident = DemangleIdentifier (); + if (ident == null) + return null; + nominal.AddChild (ident); + + if (isProto && !NextIf ('_')) + return null; + + if (!slice.IsAtEnd) + return null; + + return global; + } + + } +} diff --git a/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs b/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs new file mode 100644 index 000000000000..45b26be66384 --- /dev/null +++ b/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs @@ -0,0 +1,2065 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Demangling { + public class Swift5NodeToTLDefinition { + static List nominalNodeKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol + }; + + static List nominalNodeAndModuleKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol, NodeKind.Module + }; + + static List identifierOrOperatorOrPrivateDecl = new List { + NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator, NodeKind.PrivateDeclName + }; + + static List boundGenericNominalNodeKinds = new List { + NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure + }; + + string mangledName; + ulong offset; + + RuleRunner ruleRunner; + List rules; + + public Swift5NodeToTLDefinition (string mangledName, ulong offset = 0) + { + this.mangledName = mangledName; + this.offset = offset; + rules = BuildMatchRules (); + ruleRunner = new RuleRunner (rules); + } + + List BuildMatchRules () + { + return new List () { + new MatchRule { + Name = "TypeAlias", + NodeKind = NodeKind.TypeAlias, + Reducer = ConvertToTypeAlias + }, + new MatchRule { + Name = "ReturnType", + NodeKind = NodeKind.ReturnType, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "ArgumentTuple", + NodeKind = NodeKind.ArgumentTuple, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "AutoClosure", + NodeKind = NodeKind.AutoClosureType, + Reducer = ConvertToFunctionType + }, + new MatchRule { + Name = "Tuple", + NodeKind = NodeKind.Tuple, + Reducer = ConvertToTuple + }, + new MatchRule { + Name = "Structure", + NodeKind = NodeKind.Structure, + Reducer = ConvertToStruct + }, + new MatchRule { + Name = "ClassEnum", + NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "Getter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToGetter, + ChildRules = new List () { + new MatchRule () { + Name = "GetterChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "Setter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSetter, + ChildRules = new List () { + new MatchRule () { + Name = "SetterChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "DispatchThunk", + NodeKind = NodeKind.DispatchThunk, + Reducer = ConvertToDispatchThunk, + ChildRules = new List () { } + }, + new MatchRule { + Name = "DynamicSelf", + NodeKind = NodeKind.DynamicSelf, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "SubscriptModifier", + NodeKind = NodeKind.ModifyAccessor, + Reducer = ConvertToSubscriptModifier, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptModifierChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "SubscriptGetter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToSubscriptGetter, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptSetterChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "SubscriptSetter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSubscriptSetter, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptSetterChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "DidSet", + NodeKind = NodeKind.DidSet, + Reducer = ConvertToDidSet, + ChildRules = new List { + new MatchRule { + Name = "DidSetChild", + NodeKind = NodeKind.Variable, + }, + } + }, + new MatchRule { + Name = "WillSet", + NodeKind = NodeKind.WillSet, + Reducer = ConvertToWillSet, + ChildRules = new List { + new MatchRule { + Name = "DidSetChild", + NodeKind = NodeKind.Variable, + }, + } + }, + new MatchRule { + Name = "ModifyAccessor", + NodeKind = NodeKind.ModifyAccessor, + Reducer = ConvertToModifyAccessor, + ChildRules = new List () { + new MatchRule () { + Name = "ModifyAccessorChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "CFunctionPointerType", + NodeKind = NodeKind.CFunctionPointer, + Reducer = ConvertToCFunctionPointerType, + ChildRules = new List { + new MatchRule { + Name = "CFunctionPointerChildArgumentTuple", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule { + Name = "CFunctionPointerChildReturnType", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule { + Name = "ProtocolList", + NodeKind = NodeKind.ProtocolList, + Reducer = ConvertToProtocolList, + ChildRules = new List { + new MatchRule { + Name = "TypeList", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "ProtocolListWithAnyObject", + NodeKind = NodeKind.ProtocolListWithAnyObject, + Reducer = ConvertToProtocolListAnyObject, + }, + new MatchRule { + Name = "Protocol", + NodeKind = NodeKind.Protocol, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "TupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToTupleElement, + ChildRules = new List { + new MatchRule { + Name = "TupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "NamedTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToTupleElement, + ChildRules = new List { + new MatchRule { + Name = "TupleElementName", + NodeKind = NodeKind.TupleElementName + }, + new MatchRule { + Name = "TupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "VariadicTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToVariadicTupleElement, + ChildRules = new List { + new MatchRule { + Name = "VariadicElementType", + NodeKind = NodeKind.VariadicMarker, + }, + new MatchRule { + Name = "NamedTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "DependentGenericParameter", + NodeKind = NodeKind.DependentGenericParamType, + Reducer = ConvertToGenericReference, + ChildRules = new List { + new MatchRule { + Name = "Depth", + NodeKind = NodeKind.Index + }, + new MatchRule { + Name = "Index", + NodeKind = NodeKind.Index + } + } + }, + new MatchRule { + Name = "DependentMemberType", + NodeKind = NodeKind.DependentMemberType, + Reducer = ConvertToDependentMember, + ChildRules = new List { + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule { + Name = "Static", + NodeKind = NodeKind.Static, + Reducer = ConvertToStatic, + }, + new MatchRule { + Name = "BoundGenericNominal", + NodeKindList = boundGenericNominalNodeKinds, + Reducer = ConvertToBoundGeneric, + ChildRules = new List { + new MatchRule { + Name = "TypeChild", + NodeKind = NodeKind.Type + }, + new MatchRule { + Name = "TypeListChild", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "ConstructorList", + NodeKind = NodeKind.Constructor, + Reducer = ConvertToNonAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ConstructorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorExtensionLableList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "ConstructorNoTypeList", + NodeKind = NodeKind.Constructor, + Reducer = ConvertToNonAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ConstructorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorExtensionsNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "Destructor", + NodeKind = NodeKind.Destructor, + Reducer = ConvertToDestructor, + ChildRules = new List { + new MatchRule { + Name = "DestructorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "Deallocator", + NodeKind = NodeKind.Deallocator, + Reducer = ConvertToDeallocator, + ChildRules = new List { + new MatchRule { + Name = "DeallocatorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "InOutType", + NodeKind = NodeKind.Type, + Reducer = ConvertToReferenceType, + ChildRules = new List { + new MatchRule { + Name = "InOutChild", + NodeKind = NodeKind.InOut + } + } + }, + new MatchRule { + Name = "ProtocolWitnessTable", + NodeKindList = new List { + NodeKind.ProtocolWitnessTable, + NodeKind.ProtocolWitnessTableAccessor + }, + Reducer = ConvertToProtocolWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChild", + NodeKind = NodeKind.ProtocolConformance, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChildTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildProtocolTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildModuleChild", + NodeKind = NodeKind.Module + } + } + } + } + }, + new MatchRule { + Name = "ValueWitnessTable", + NodeKind = NodeKind.ValueWitnessTable, + Reducer = ConvertToValueWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ValueWitnessTableChild", + NodeKind = NodeKind.Type + } + } + }, + // a Function is: + // Context Identifier [LabelList] Type FunctionType + new MatchRule () { + Name = "FunctionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTLContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "FunctionTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule () { + Name = "FunctionTLType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionExtensionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionExtension", + NodeKind = NodeKind.Extension, + }, + new MatchRule () { + Name = "FunctionExtTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionExtTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule () { + Name = "FunctionExtTLType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule { + Name = "GenericFunctionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule () { + Name = "GenFunctionTLContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "GenFunctionTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.DependentGenericType, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + } + } + }, + } + }, + new MatchRule { + Name = "DependentGenericFunctionType", + NodeKind = NodeKind.DependentGenericType, + Reducer = ConvertToGenericFunction, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + }, + new MatchRule () { + Name = "FunctionNoTypeList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "FunctionName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionExtensionNoTypeList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionExtension", + NodeKind = NodeKind.Extension, + }, + new MatchRule () { + Name = "FunctionName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "FunctionThrows", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeThrows", + NodeKind = NodeKind.ThrowsAnnotation + }, + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "NoEscapeFunctionType", + NodeKind = NodeKind.NoEscapeFunctionType, + Reducer = ConvertToNoEscapeFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "NoEscapeFunctionTypeThrows", + NodeKind = NodeKind.NoEscapeFunctionType, + Reducer = ConvertToNoEscapeFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeThrows", + NodeKind = NodeKind.ThrowsAnnotation + }, + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "Metatype", + NodeKind = NodeKind.Metatype, + Reducer = ConvertToMetatype, + }, + new MatchRule () { + Name = "ExistentialMetatype", + NodeKind = NodeKind.ExistentialMetatype, + Reducer = ConvertToExistentialMetatype, + MatchChildCount = false + }, + // Probably should be last + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type, + Reducer = ConvertFirstChildToSwiftType, + MatchChildCount = false + }, + }; + } + + public TLDefinition Convert (Node node) + { + Exceptions.ThrowOnNull (node, nameof (node)); + + + switch (node.Kind) { + case NodeKind.Type: + return Convert (node.Children [0]); + case NodeKind.Static: + return ConvertStatic (node); + case NodeKind.Function: + return ConvertFunction (node, isMethodDescriptor: false, isEnumCase: false); + case NodeKind.MethodDescriptor: + return ConvertFunction (node.Children [0], isMethodDescriptor: true, isEnumCase: false); + case NodeKind.EnumCase: + return ConvertFunction (node.Children [0], isMethodDescriptor: false, isEnumCase: true); + case NodeKind.Constructor: + case NodeKind.Allocator: + return ConvertFunctionConstructor (node); + case NodeKind.Destructor: + case NodeKind.Deallocator: + return ConvertFunctionDestructor (node); + case NodeKind.Getter: + case NodeKind.Setter: + case NodeKind.DidSet: + case NodeKind.MaterializeForSet: + case NodeKind.WillSet: + case NodeKind.ModifyAccessor: + return ConvertFunctionProp (node); + case NodeKind.DispatchThunk: + return ConvertDispatchThunk (node); + case NodeKind.Variable: + return ConvertVariable (node, false); + case NodeKind.PropertyDescriptor: + return ConvertPropertyDescriptor (node); + case NodeKind.TypeMetadataAccessFunction: + return ConvertCCtor (node); + case NodeKind.TypeMetadata: + return ConvertMetadata (node); + case NodeKind.NominalTypeDescriptor: + return ConvertNominalTypeDescriptor (node); + case NodeKind.ProtocolConformanceDescriptor: + return ConvertProtocolConformanceDescriptor (node); + case NodeKind.ProtocolDescriptor: + return ConvertProtocolDescriptor (node); + case NodeKind.Initializer: + return ConvertInitializer (node); + case NodeKind.TypeMetadataLazyCache: + return ConvertLazyCacheVariable (node); + case NodeKind.ProtocolWitnessTable: + case NodeKind.ProtocolWitnessTableAccessor: + case NodeKind.ValueWitnessTable: + return ConvertProtocolWitnessTable (node); + case NodeKind.FieldOffset: + return ConvertFieldOffset (node); + case NodeKind.DefaultArgumentInitializer: + return ConvertDefaultArgumentInitializer (node); + case NodeKind.Metaclass: + return ConvertMetaclass (node); + case NodeKind.UnsafeMutableAddressor: + return ConvertUnsafeMutableAddressor (node); + case NodeKind.CurryThunk: + return ConvertCurryThunk (node); + case NodeKind.GenericTypeMetadataPattern: + return ConvertTypeMetadataPattern (node); + case NodeKind.Global: + return Convert (node); + case NodeKind.ModuleDescriptor: + return ConvertModuleDescriptor (node); + case NodeKind.ReflectionMetadataFieldDescriptor: + return ConvertMetadataFieldDescriptor (node, false); + case NodeKind.ReflectionMetadataBuiltinDescriptor: + return ConvertMetadataFieldDescriptor (node, true); + case NodeKind.ProtocolRequirementsBaseDescriptor: + return ConvertProtocolRequirementsBaseDescriptor (node); + case NodeKind.BaseConformanceDescriptor: + return ConvertBaseConformanceDescriptor (node); + case NodeKind.AssociatedTypeDescriptor: + return ConvertAssocatedTypeDescriptor (node); + case NodeKind.ClassMetadataBaseOffset: + return ConvertMetadataBaseOffset (node); + case NodeKind.MethodLookupFunction: + return ConvertMethodLookupFunction (node); + default: + return null; + } + } + + + TLDefinition ConvertDispatchThunk (Node node) + { + switch (node.Children [0].Kind) { + case NodeKind.Getter: + case NodeKind.Setter: + case NodeKind.DidSet: + case NodeKind.MaterializeForSet: + case NodeKind.WillSet: + case NodeKind.ModifyAccessor: + return ConvertFunctionProp (node); + case NodeKind.Static: + return ConvertStaticDispatchThunk (node); + case NodeKind.Function: + case NodeKind.Allocator: + return ConvertFunction (node, isMethodDescriptor: false, isEnumCase: false); + default: + return null; + } + } + + TLDefinition ConvertStaticDispatchThunk (Node node) + { + if (node.Children [0].Children [0].Kind == NodeKind.Variable) { + return ConvertStaticDispatchThunkVariable (node); + } + else { + return ConvertStatic (node); + } + } + + TLDefinition ConvertStaticDispatchThunkVariable (Node node) + { + return null; + } + + + TLFunction ConvertFunction (Node node, bool isMethodDescriptor, bool isEnumCase) + { + var swiftType = ConvertToSwiftType (node, false, null); + var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) { + // method + var context = uncurriedFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = new SwiftName (context.Last (), false); + return isMethodDescriptor ? + new TLMethodDescriptor (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset) : + isEnumCase ? + new TLEnumCase (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset) : + new TLFunction (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset); + } + + var plainFunction = swiftType as SwiftFunctionType; + if (plainFunction != null) { + var context = plainFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context [context.Length - 2] [0] == '|') { + Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); + } + var functionName = new SwiftName (context.Last (), false); + return isMethodDescriptor ? + new TLMethodDescriptor (mangledName, module, functionName, null, plainFunction, offset, operatorType) : + new TLFunction (mangledName, module, functionName, null, plainFunction, offset, operatorType); + } + return null; + } + + TLDefinition ConvertStatic (Node node) + { + if (node.Children [0].Kind == NodeKind.Variable) { + return ConvertVariable (node.Children [0], true); + } + var swiftType = ConvertToSwiftType (node, false, null); + var propType = swiftType as SwiftPropertyType; + if (propType != null) { + var context = propType.DiscretionaryString.Split ('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); + } + + var staticFunction = swiftType as SwiftStaticFunctionType; + if (staticFunction != null) { + var context = staticFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context [context.Length - 2] [0] == '|') { + Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); + } + var functionName = new SwiftName (context.Last (), false); + return new TLFunction (mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); + } + return null; + } + + TLFunction ConvertFunctionConstructor (Node node) + { + var swiftType = ConvertToSwiftType (node, false, null); + var constructor = swiftType as SwiftConstructorType; + if (constructor != null) { + var context = constructor.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = constructor.Name; + var metaType = constructor.UncurriedParameter as SwiftMetaClassType; + return new TLFunction (mangledName, module, functionName, metaType.Class, constructor, offset); + } + return null; + } + + TLFunction ConvertFunctionDestructor (Node node) + { + var swiftType = ConvertToSwiftType (node, false, null); + var destructor = swiftType as SwiftDestructorType; + if (destructor != null) { + var context = destructor.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var functionName = destructor.Name; + var className = destructor.Parameters as SwiftClassType; + if (className == null) + throw new NotSupportedException ($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType ().Name}"); + return new TLFunction (mangledName, module, functionName, className, destructor, offset); + } + return null; + } + + TLFunction ConvertFunctionProp (Node node) + { + var propType = ConvertToSwiftType (node, false, null) as SwiftPropertyType; + if (propType == null) + return null; + var context = propType.DiscretionaryString.Split ('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); + } + + TLVariable ConvertVariable (Node node, bool isStatic) + { + // Variable + // + if (node.Children.Count != 3 && node.Children.Count != 4) + throw new ArgumentOutOfRangeException (nameof (node), $"Expected 3 or 4 children in a variable node, but got {node.Children.Count}"); + + if (node.Kind == NodeKind.Subscript) { + var subFunc = ConvertToSubscriptEtter (node, false, null, PropertyType.Getter) as SwiftPropertyType; + var module = subFunc.DiscretionaryString.Split ('.') [0]; + return new TLVariable (mangledName, new SwiftName (module, false), subFunc.UncurriedParameter as SwiftClassType, + new SwiftName ("subscript", false), subFunc.OfType, isStatic, offset); + } + + if (node.Children [2].Kind == NodeKind.LabelList && node.Children [3].Kind == NodeKind.Type && + node.Children [3].Children [0].Kind == NodeKind.FunctionType) { + var functionNode = new Node (NodeKind.Function); + functionNode.Children.AddRange (node.Children); + var function = ConvertFunction (functionNode, isMethodDescriptor: false, isEnumCase: false); + SwiftClassType classOn = null; + if (function.Signature is SwiftUncurriedFunctionType ucf) { + classOn = ucf.UncurriedParameter as SwiftClassType; + } + return new TLVariable (mangledName, function.Module, classOn, function.Name, function.Signature, isStatic, offset); + } else { + var isExtension = node.Children [0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType context = null; + + + if (isExtension) { + module = new SwiftName (node.Children [0].Children [0].Text, false); + extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); + if (extensionOn == null) + return null; + } else { + var nesting = new List (); + var nestingNames = new List (); + module = BuildMemberNesting (node.Children [0], nesting, nestingNames); + context = nesting.Count > 0 ? new SwiftClassType (new SwiftClassName (module, nesting, nestingNames), false) : null; + } + + var name = new SwiftName (node.Children [1].Text, false); + var variableType = ConvertToSwiftType (node.Children [2], false, null); + return new TLVariable (mangledName, module, context, name, variableType, isStatic, offset, extensionOn); + } + } + + TLPropertyDescriptor ConvertPropertyDescriptor (Node node) + { + var tlvar = ConvertVariable (node.Children [0], false); + if (tlvar == null) + return null; + return new TLPropertyDescriptor (tlvar.MangledName, tlvar.Module, tlvar.Class, tlvar.Name, tlvar.OfType, false, tlvar.Offset, tlvar.ExtensionOn); + } + + TLFunction ConvertCCtor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var metaType = new SwiftMetaClassType (classType, false); + var cctor = new SwiftClassConstructorType (metaType, false); + return new TLFunction (mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, + cctor, offset); + } + + TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer (Node node) + { + if (node.Children.Count != 2) + return null; + var baseFunction = ConvertToSwiftType (node.Children [0], false, null) as SwiftBaseFunctionType; + if (baseFunction == null) + return null; + var context = baseFunction.DiscretionaryString.Split ('.'); + var module = new SwiftName (context [0], false); + var argumentIndex = (int)node.Children [1].Index; + return new TLDefaultArgumentInitializer (mangledName, module, baseFunction, argumentIndex, offset); + } + + TLFieldOffset ConvertFieldOffset (Node node) + { + if (node.Children.Count != 2 || node.Children [0].Kind != NodeKind.Directness) + return null; + var variable = ConvertVariable (node.Children [1], false) as TLVariable; + if (variable == null) + return null; + + return new TLFieldOffset (mangledName, variable.Module, variable.Class, node.Children [0].Index == 0, variable.Name, + variable.OfType, offset); + } + + TLDirectMetadata ConvertMetadata (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLDirectMetadata (mangledName, classType.ClassName.Module, classType, offset); + } + + TLNominalTypeDescriptor ConvertNominalTypeDescriptor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLNominalTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); + } + + TLProtocolConformanceDescriptor ConvertProtocolConformanceDescriptor (Node node) + { + node = node.Children [0]; + if (node.Kind != NodeKind.ProtocolConformance) + return null; + if (node.Children.Count != 3) + return null; + var implementingType = ConvertToSwiftType (node.Children [0], false, null); + if (implementingType == null) + return null; + var forProtocol = ConvertToSwiftType (node.Children [1], false, null) as SwiftClassType; + if (forProtocol == null) + return null; + var module = new SwiftName (node.Children [2].Text, false); + return new TLProtocolConformanceDescriptor (mangledName, module, implementingType, forProtocol, offset); + } + + TLProtocolTypeDescriptor ConvertProtocolDescriptor (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLProtocolTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); + } + + TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor (Node node) + { + if (node.Children [0].Kind != NodeKind.Variable) + throw new ArgumentOutOfRangeException ($"Expected a Variable child but got a {node.Children [0].Kind}"); + var variable = ConvertVariable (node.Children [0], false); + return new TLUnsafeMutableAddressor (mangledName, variable.Module, null, variable.Name, variable.OfType, variable.Offset); + } + + TLMetaclass ConvertMetaclass (Node node) + { + if (node.Children [0].Kind != NodeKind.Type) + return null; + var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; + if (classType == null) + return null; + var module = classType.ClassName.Module; + return new TLMetaclass (mangledName, module, classType, offset); + } + + TLGenericMetadataPattern ConvertTypeMetadataPattern (Node node) + { + var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLGenericMetadataPattern (mangledName, type.ClassName.Module, type, offset); + } + + TLFunction ConvertInitializer (Node node) + { + var variable = node.Children [0]; + var context = ConvertToSwiftType (variable.Children [0], false, null) as SwiftClassType; + if (context == null) + return null; + var privatePublicName = PrivateNamePublicName (variable.Children [1]); + var name = new SwiftName (privatePublicName.Item2, false); + var typeIndex = variable.Children [2].Kind == NodeKind.LabelList ? 3 : 2; + var type = ConvertToSwiftType (variable.Children [typeIndex], false, null); + var initializer = new SwiftInitializerType (InitializerType.Variable, type, context, name); + return new TLFunction (mangledName, context.ClassName.Module, name, initializer.Owner, initializer, offset); + } + + TLLazyCacheVariable ConvertLazyCacheVariable (Node node) + { + var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + return new TLLazyCacheVariable (mangledName, classType.ClassName.Module, classType, offset); + } + + TLFunction ConvertProtocolWitnessTable (Node node) + { + var witnessTable = ConvertToSwiftType (node, false, null) as SwiftWitnessTableType; + + var rebuiltWitnessTable = new SwiftWitnessTableType (witnessTable.WitnessType, witnessTable.ProtocolType, witnessTable.UncurriedParameter as SwiftClassType); + + return new TLFunction (mangledName, new SwiftName (witnessTable.DiscretionaryString, false), null, + witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); + } + + TLThunk ConvertCurryThunk (Node node) + { + TLFunction func = ConvertFunction (node.Children [0], isMethodDescriptor: false, isEnumCase: false); + return new TLThunk (ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); + } + + TLModuleDescriptor ConvertModuleDescriptor (Node node) + { + var firstChild = node.Children [0]; + if (firstChild.Kind != NodeKind.Module) + return null; + return new TLModuleDescriptor (mangledName, new SwiftName (firstChild.Text, false), offset); + } + + TLMetadataDescriptor ConvertMetadataFieldDescriptor (Node node, bool isBuiltIn) + { + var ofType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (ofType == null) + return null; + return new TLMetadataDescriptor (ofType, isBuiltIn, mangledName, ofType.ClassName.Module, offset); + } + + TLProtocolRequirementsBaseDescriptor ConvertProtocolRequirementsBaseDescriptor (Node node) + { + var ofType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (ofType == null) + return null; + return new TLProtocolRequirementsBaseDescriptor (mangledName, ofType.ClassName.Module, ofType, offset); + } + + TLBaseConformanceDescriptor ConvertBaseConformanceDescriptor (Node node) + { + var protocol = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (protocol == null) + return null; + var requirement = ConvertToSwiftType (node.Children [1], false, null) as SwiftClassType; + if (requirement == null) + return null; + return new TLBaseConformanceDescriptor (mangledName, protocol.ClassName.Module, protocol, requirement, offset); + } + + TLAssociatedTypeDescriptor ConvertAssocatedTypeDescriptor (Node node) + { + var name = new SwiftName (node.Children [0].Text, false); + var protocol = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; + if (protocol == null) + return null; + return new TLAssociatedTypeDescriptor (mangledName, protocol.ClassName.Module, protocol, name, offset); + } + + TLMetadataBaseOffset ConvertMetadataBaseOffset (Node node) + { + var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLMetadataBaseOffset (mangledName, type.ClassName.Module, type, offset); + } + + TLMethodLookupFunction ConvertMethodLookupFunction (Node node) + { + var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLMethodLookupFunction (mangledName, type.ClassName.Module, type, offset); + } + + + // ConvertToFunctions are usually called from rules. + + SwiftType ConvertToReferenceType (Node node, bool isReference, SwiftName name) + { + return ConvertToSwiftType (node.Children [0].Children [0], true, name); + } + + SwiftType ConvertToSwiftType (Node node, bool isReference, SwiftName name) + { + return ruleRunner.RunRules (node, isReference, name); + } + + SwiftType ConvertFirstChildToSwiftType (Node node, bool isReference, SwiftName name) + { + if (node.Children.Count == 0) + throw new ArgumentOutOfRangeException (nameof (node)); + return ConvertToSwiftType (node.Children [0], isReference, name); + } + + SwiftType ConvertToGeneralFunctionType (Node node, bool isReference, SwiftName name, bool isEscaping) + { + var throws = node.Children [0].Kind == NodeKind.ThrowsAnnotation; + var startIndex = throws ? 1 : 0; + var args = ConvertToSwiftType (node.Children [startIndex + 0], false, null); + var returnType = ConvertToSwiftType (node.Children [startIndex + 1], false, null); + return new SwiftFunctionType (args, returnType, isReference, throws, name, isEscaping: isEscaping); + } + + SwiftType ConvertToFunctionType (Node node, bool isReference, SwiftName name) + { + return ConvertToGeneralFunctionType (node, isReference, name, true); + } + + SwiftType ConvertToNoEscapeFunctionType (Node node, bool isReference, SwiftName name) + { + return ConvertToGeneralFunctionType (node, isReference, name, false); + } + + OperatorType ToOperatorType (NodeKind kind) + { + switch (kind) { + default: + case NodeKind.Identifier: + return OperatorType.None; + case NodeKind.PrefixOperator: + return OperatorType.Prefix; + case NodeKind.InfixOperator: + return OperatorType.Infix; + case NodeKind.PostfixOperator: + return OperatorType.Postfix; + } + } + + SwiftType ConvertToAllocatingConstructor (Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor (node, isReference, name, true); + } + + SwiftType ConvertToNonAllocatingConstructor (Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor (node, isReference, name, false); + } + + SwiftType ConvertToConstructor (Node node, bool isReference, SwiftName name, bool isAllocating) + { + var isExtension = node.Children [0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType instanceType = null; + + if (isExtension) { + module = new SwiftName (node.Children [0].Children [0].Text, false); + extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); + if (extensionOn == null) + return null; + if (extensionOn is SwiftBuiltInType builtIn) { + extensionOn = new SwiftClassType (SwiftClassName.FromFullyQualifiedName ($"Swift.{builtIn.BuiltInType}", OperatorType.None, "V"), false); + } + instanceType = extensionOn as SwiftClassType; + } else { + instanceType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + module = instanceType.ClassName.Module; + } + + var metadata = new SwiftMetaClassType (instanceType, false, null); + var labels = node.Children [1].Kind == NodeKind.LabelList ? ToLabelList (node.Children [1]) : null; + var typeIndex = labels == null ? 1 : 2; + var functionType = node.Children [typeIndex].Children [0]; + var functionThrows = functionType.Children.Count == 3 && functionType.Children [0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; + var args = ConvertToSwiftType (functionType.Children [0 + functionThrows], false, null); + args = labels != null && labels.Count > 0 ? RenameFunctionParameters (args, labels) : args; + var ret = ConvertToSwiftType (functionType.Children [1 + functionThrows], false, null); + var constructor = new SwiftConstructorType (isAllocating, metadata, args, ret, isReference, functionThrows != 0, extensionOn); + + constructor.DiscretionaryString = $"{module.Name}.{instanceType.ClassName.ToFullyQualifiedName (false)}"; + return constructor; + } + + SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor (node, isReference, name, false); + } + + SwiftType ConvertToDeallocator (Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor (node, isReference, name, true); + } + + SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name, bool isDeallocating) + { + var instanceType = ConvertToSwiftType (node.Children [0], false, null); + var sct = instanceType as SwiftClassType; + if (sct == null) + throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType ().Name}."); + var destructor = new SwiftDestructorType (isDeallocating, sct, isReference, false); + destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); + return destructor; + } + SwiftType ConvertToStruct (Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName (node); + var bit = TryAsBuiltInType (node, className, isReference, name); + return (SwiftType)bit ?? new SwiftClassType (className, isReference, name); + } + + SwiftType ConvertToTypeAlias (Node node, bool isReference, SwiftName name) + { + if (node.Children[0].Kind == NodeKind.Module && node.Children [0].Text == "__C") { + var shamNode = new Node (NodeKind.Structure); + shamNode.Children.AddRange (node.Children); + var className = ToSwiftClassName (shamNode); + className = RemapTypeAlias (className); + return new SwiftClassType (className, isReference, name); + } else { + return null; + } + } + + SwiftType ConvertToClass (Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName (node); + return new SwiftClassType (className, isReference, name); + } + + SwiftClassName ToSwiftClassName (Node node) + { + var memberNesting = new List (); + var nestingNames = new List (); + var moduleName = BuildMemberNesting (node, memberNesting, nestingNames); + + return PatchClassName (moduleName, memberNesting, nestingNames); + } + + SwiftType ConvertToDependentMember (Node node, bool isReference, SwiftName name) + { + // format should be + // DependentReferenceType + // Type + // GenericReference (depth, index) + // AssocPathItem (name) + // For multuple path elements, these get nested with the head being deepest. + // Weird flex, but OK. + var genericReference = ConvertFirstChildToSwiftType (node, isReference, name) as SwiftGenericArgReferenceType; + if (genericReference == null) + return null; + if (node.Children.Count < 2) + return genericReference; + var assocChild = node.Children [1]; + genericReference.AssociatedTypePath.Add (assocChild.Text); + return genericReference; + } + + SwiftType ConvertToCFunctionPointerType (Node node, bool isReference, SwiftName name) + { + var args = ConvertToSwiftType (node.Children [0], false, null); + var ret = ConvertToSwiftType (node.Children [1], false, null); + var function = new SwiftCFunctionPointerType (args, ret, isReference, false, name); + return function; + } + + SwiftType ConvertToTuple (Node node, bool isReference, SwiftName name) + { + var types = new List (); + if (node.Children.Count == 0) { + return SwiftTupleType.Empty; + } + if (node.Children.Count == 1) { + var onlyChild = ConvertFirstChildToSwiftType (node, false, null); + return new SwiftTupleType (isReference, name, onlyChild); + } + foreach (var child in node.Children) { + var type = ConvertToSwiftType (child, false, null); + if (type == null) + return null; + types.Add (type); + } + return new SwiftTupleType (types, isReference, name); + } + + SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name) + { + return ConvertToProtocolList (node, isReference, name, NodeKind.Type); + } + + SwiftType ConvertToProtocolListAnyObject (Node node, bool isReference, SwiftName name) + { + return ConvertToProtocolList (node.Children [0], isReference, name, node.Kind); + } + + SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name, NodeKind nodeKind) + { + if (node.Children.Count != 1) + throw new NotSupportedException ("ProtocolList node with more than 1 child not supported"); + if (node.Children [0].Kind != NodeKind.TypeList) + throw new NotSupportedException ($"Given a ProtocolList node with child type {node.Children [0].Kind.ToString ()} and {node.Children [0].Children.Count} children, but expected a TypeList with exactly 1 child."); + // If the number of elements is 0, it means that this is an "Any" type in swift. + // I'm assuming it's lodged here as a protocol list is that an empty protocol list is + // represented by an existential container which is also used to represent a protocol list. + if (node.Children [0].Children.Count == 0) { + var anyName = nodeKind == NodeKind.ProtocolListWithAnyObject ? "Swift.AnyObject" : "Swift.Any"; + var anyProtocolType = nodeKind == NodeKind.ProtocolListWithAnyObject ? 'C' : 'P'; + var className = SwiftClassName.FromFullyQualifiedName (anyName, OperatorType.None, anyProtocolType); + var classType = new SwiftClassType (className, isReference, name); + return classType; + } + var typeList = ConvertTypeList (node.Children [0]).Select (t => t as SwiftClassType); + var protoListType = new SwiftProtocolListType (typeList, isReference, name); + if (protoListType.Protocols.Count == 1) + return protoListType.Protocols [0].RenamedCloneOf (name); + return protoListType; + } + + SwiftType ConvertToProtocolWitnessTable (Node node, bool isReference, SwiftName name) + { + var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? + WitnessType.Protocol : WitnessType.ProtocolAccessor; + var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; + var protoType = ConvertToSwiftType (node.Children [0].Children [1], false, null) as SwiftClassType; + var protoWitness = new SwiftWitnessTableType (witnessType, protoType, classType); + protoWitness.DiscretionaryString = node.Children [0].Children [2].Text; + return protoWitness; + } + + SwiftType ConvertToValueWitnessTable (Node node, bool isReference, SwiftName name) + { + var valueType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; + var valueWitnessTable = new SwiftWitnessTableType (WitnessType.Value, null, valueType); + valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; + return valueWitnessTable; + } + + SwiftType ConvertToEtter (Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + var isExtension = node.Children [0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType context = null; + SwiftClassName className = null; + + if (isExtension) { + module = new SwiftName (node.Children [0].Children [0].Text, false); + extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); + if (extensionOn == null) + return null; + } else { + var nestings = new List (); + var names = new List (); + + module = BuildMemberNesting (node.Children [0], nestings, names); + if (module == null) + return null; + className = nestings.Count > 0 ? new SwiftClassName (module, nestings, names) : null; + context = className != null ? new SwiftClassType (className, false) : null; + } + + + var privatePublicName = PrivateNamePublicName (node.Children [1]); + var propName = new SwiftName (privatePublicName.Item2, false); + var privateName = privatePublicName.Item1 != null ? new SwiftName (privatePublicName.Item1, false) : null; + + var funcChildIndex = node.Children [2].Kind == NodeKind.LabelList ? 3 : 2; + + var getterType = ConvertToSwiftType (node.Children [funcChildIndex], false, propertyType == PropertyType.Setter ? new SwiftName ("newValue", false) : null); + var prop = new SwiftPropertyType (context, propertyType, propName, privateName, + getterType, false, isReference, extensionOn); + prop.DiscretionaryString = context != null ? context.ClassName.ToFullyQualifiedName (true) + : $"{module.Name}.{propName.Name}"; + return prop; + + } + + SwiftType ConvertToGetter (Node node, bool isReference, SwiftName name) + { + // Getter + // Variable + // Context + // Type + return ConvertToEtter (node.Children [0], isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSetter (Node node, bool isReference, SwiftName name) + { + return ConvertToEtter (node.Children [0], isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToWillSet (Node node, bool isReference, SwiftName name) + { + return ConvertToEtter (node.Children [0], isReference, name, PropertyType.WillSet); + } + + SwiftType ConvertToDidSet (Node node, bool isReference, SwiftName name) + { + return ConvertToEtter (node.Children [0], isReference, name, PropertyType.DidSet); + } + + SwiftType ConvertToModifyAccessor (Node node, bool isReference, SwiftName name) + { + return ConvertToEtter (node.Children [0], isReference, name, PropertyType.ModifyAccessor); + } + + SwiftType ConvertToSubscriptEtter (Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + var functionNode = new Node (NodeKind.Function); + functionNode.Children.AddRange (node.Children); + functionNode.Children.Insert (1, new Node (NodeKind.Identifier, "subscript")); + var theFunc = ConvertToFunction (functionNode, isReference, name) as SwiftBaseFunctionType; + if (theFunc == null) + return null; + + var uncurriedFunctionType = theFunc as SwiftUncurriedFunctionType; + + // if this is normal subscript, uncurriedFunctionType will be non-null + // if this is an extension, uncurriedFunctionType will be null. + + SwiftFunctionType accessor = null; + switch (propertyType) { + case PropertyType.Setter: + // oh hooray! + // If I define an indexer in swift like this: + // public subscript(T index) -> U { + // get { return getSomeUValue(index); } + // set (someUValue) { setSomeUValue(index, someUValue); } + // } + // This signature of the function attached to both properties is: + // T -> U + // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but + // the setter is (T, U) -> void + // + // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect + // what's really happening. + + // need to change this so that the tail parameters get names? Maybe just the head? + var newParameters = theFunc.ParameterCount == 1 ? + new SwiftTupleType (false, null, theFunc.ReturnType, + theFunc.Parameters.RenamedCloneOf (new SwiftName (theFunc.ReturnType.Name == null || + theFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) + : new SwiftTupleType (Enumerable.Concat (theFunc.ReturnType.Yield (), theFunc.EachParameter), false, null); + accessor = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, theFunc.CanThrow, theFunc.Name, theFunc.ExtensionOn); + break; + default: + // Because I decided to get clever and reuse existing code to demangle the underlying function, + // I get back either a SwiftFunctionType for an extension for a SwiftUncurriedFunctionType for + // an instance subscript. These types share a common base class, but are otherwise unrelated. + // I need a SwiftFunctionType, so here we are. + accessor = new SwiftFunctionType (theFunc.Parameters, theFunc.ReturnType, false, theFunc.IsReference, theFunc.Name, theFunc.ExtensionOn); + break; + } + + + var propType = theFunc.ReturnType; + var propName = theFunc.Name; + var prop = new SwiftPropertyType (uncurriedFunctionType?.UncurriedParameter, propertyType, propName, null, accessor, false, isReference); + prop.ExtensionOn = accessor.ExtensionOn; + prop.DiscretionaryString = theFunc.DiscretionaryString; + return prop; + } + + SwiftType ConvertToSubscriptGetter (Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSubscriptSetter (Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToSubscriptModifier (Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.ModifyAccessor); + } + + SwiftType ConvertToDispatchThunk (Node node, bool isReference, SwiftName name) + { + var thunkType = ConvertFirstChildToSwiftType (node, isReference, name); + if (thunkType == null) + return null; + if (thunkType is SwiftBaseFunctionType funcType) + return funcType.AsThunk (); + return null; + } + + SwiftType ConvertToTupleElement (Node node, bool isReference, SwiftName name) + { + name = node.Children [0].Kind == NodeKind.TupleElementName ? new SwiftName (node.Children [0].Text, false) : name; + var index = node.Children [0].Kind == NodeKind.TupleElementName ? 1 : 0; + return ConvertToSwiftType (node.Children [index], isReference, name); + } + + SwiftType ConvertToVariadicTupleElement (Node node, bool isReference, SwiftName name) + { + var type = ConvertToSwiftType (node.Children [1], false, null); + if (type == null) + return null; + + // in the past, this came through as an array with the variadic marker set. + // no longer is the case, so we synthesize the array and set the variadic marker. + var nesting = new List () { MemberNesting.Struct }; + var names = new List () { new SwiftName ("Array", false) }; + var arrayName = new SwiftClassName (new SwiftName ("Swift", false), nesting, names); + var container = new SwiftBoundGenericType (new SwiftClassType (arrayName, false), new List () { type }, isReference, name); + container.IsVariadic = true; + return container; + } + + SwiftType ConvertToGenericReference (Node node, bool isReference, SwiftName name) + { + long depth = node.Children [0].Index; + long index = node.Children [1].Index; + return new SwiftGenericArgReferenceType ((int)depth, (int)index, isReference, name); + } + + SwiftType ConvertToBoundGeneric (Node node, bool isReference, SwiftName name) + { + var baseType = ConvertToSwiftType (node.Children [0], false, null); + var boundTypes = ConvertTypeList (node.Children [1]); + return new SwiftBoundGenericType (baseType, boundTypes, isReference, name); + } + + List ConvertTypeList (Node node) + { + var typeList = new List (node.Children.Count); + foreach (var childNode in node.Children) { + typeList.Add (ConvertToSwiftType (childNode, false, null)); + } + return typeList; + } + + SwiftType ConvertToFunction (Node node, bool isReference, SwiftName name) + { + var isExtension = node.Children [0].Kind == NodeKind.Extension; + SwiftType extensionOn = null; + SwiftName module = null; + var nesting = new List (); + var names = new List (); + + if (isExtension) { + module = new SwiftName (node.Children [0].Children [0].Text, false); + extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); + } else { + module = BuildMemberNesting (node.Children [0], nesting, names); + } + + var operatorType = ToOperatorType (node.Children [1].Kind); + var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; + var labelsList = node.Children [2].Kind == NodeKind.LabelList ? ToLabelList (node.Children [2]) : new List (); + var typeIndex = node.Children [2].Kind == NodeKind.LabelList ? 3 : 2; + var functionType = ConvertToSwiftType (node.Children [typeIndex], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; + if (functionType == null) + return null; + + var args = labelsList.Count > 0 ? RenameFunctionParameters (functionType.Parameters, labelsList) : functionType.Parameters; + if (nesting.Count > 0) { + var classType = new SwiftClassType (new SwiftClassName (module, nesting, names), false); + var methodName = classType.ClassName.ToFullyQualifiedName (true) + + (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + + "." + funcName; + var uncurried = new SwiftUncurriedFunctionType (classType, args, functionType.ReturnType, + functionType.IsReference, functionType.CanThrow, new SwiftName (funcName, false)); + uncurried.DiscretionaryString = methodName; + uncurried.GenericArguments.AddRange (functionType.GenericArguments); + return uncurried; + } + var functionName = module + + (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + + "." + funcName; + var generics = functionType.GenericArguments; + functionType = new SwiftFunctionType (args, functionType.ReturnType, functionType.IsReference, functionType.CanThrow, new SwiftName (funcName, false), extensionOn); + functionType.GenericArguments.AddRange (generics); + functionType.DiscretionaryString = functionName; + return functionType; + } + + SwiftType ConvertToStatic (Node node, bool isReference, SwiftName name) + { + var functionType = ConvertToSwiftType (node.Children [0], isReference, name); + if (functionType == null) + return null; + var propType = functionType as SwiftPropertyType; + if (propType != null) { + return propType.RecastAsStatic (); + } + var uncurriedFunction = functionType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) { + var staticFunction = new SwiftStaticFunctionType (uncurriedFunction.Parameters, uncurriedFunction.ReturnType, + uncurriedFunction.IsReference, uncurriedFunction.CanThrow, + uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); + staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; + return staticFunction; + } + var baseFunctionType = functionType as SwiftBaseFunctionType; + if (baseFunctionType != null) { + var staticFunction = new SwiftStaticFunctionType (baseFunctionType.Parameters, baseFunctionType.ReturnType, + baseFunctionType.IsReference, baseFunctionType.CanThrow, + null, baseFunctionType.Name); + staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; + staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; + return staticFunction; + } + var initializerType = functionType as SwiftInitializerType; + if (initializerType != null) { + return initializerType; // this doesn't need a static recast? + } + throw new ArgumentOutOfRangeException ($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType ().Name}"); + } + + List ToLabelList(Node node) + { + var result = new List (); + foreach (var child in node.Children) { + if (child.Kind == NodeKind.Identifier) { + result.Add (new SwiftName (child.Text, false)); + } else { + result.Add (new SwiftName ("_", false)); + } + } + return result; + } + + SwiftType ConvertToExistentialMetatype (Node node, bool isReference, SwiftName name) + { + var child = ConvertFirstChildToSwiftType (node, false, name); + var childType = child as SwiftProtocolListType; + if (child is SwiftClassType classType) { + childType = new SwiftProtocolListType (classType, classType.IsReference, classType.Name); + } + if (childType == null) + return null; + return new SwiftExistentialMetaType (childType, isReference, null); + } + + SwiftType ConvertToMetatype (Node node, bool isReference, SwiftName name) + { + var child = ConvertFirstChildToSwiftType (node, false, name); + if (child is SwiftClassType cl) { + return new SwiftMetaClassType (cl, isReference, name); + } else if (child is SwiftGenericArgReferenceType classReference) { + return new SwiftMetaClassType (classReference, isReference, name); + } else { + return null; + } + } + + SwiftType ConvertToGenericFunction (Node node, bool isReference, SwiftName name) + { + List args = GetGenericArguments (node); + var theFunction = ConvertToSwiftType (node.Children [1], isReference, name) as SwiftBaseFunctionType; + theFunction.GenericArguments.AddRange (args); + return theFunction; + } + + List GetGenericArguments (Node node) + { + var paramCountNode = node.Children [0].Children [0]; + if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) + throw new NotSupportedException ($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString ()}"); + + var paramCount = (int)paramCountNode.Index; + List args = new List (paramCount); + for (int i = 0; i < paramCount; i++) { + args.Add (new GenericArgument (0, i)); + } + if (node.Children [0].Children.Count > 1) { + var dependentGenericSignature = node.Children [0]; + // the 0th child is the number of generic parameters (see above) + for (int i = 1; i < dependentGenericSignature.Children.Count; i++) { + var genericParamReference = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [0], false, null) as SwiftGenericArgReferenceType; + var genericConstraintType = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [1], false, null) as SwiftClassType; + MarkGenericConstraint (args, genericParamReference, genericConstraintType); + } + } + return args; + } + + static void MarkGenericConstraint (List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) + { + foreach (var genArg in args) { + if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) { + genArg.Constraints.Add (constraintType); + return; + } + } + } + + static SwiftBuiltInType TryAsBuiltInType (Node node, SwiftClassName className, bool isReference, SwiftName name) + { + switch (className.ToFullyQualifiedName ()) { + case "Swift.Int": + return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); + case "Swift.Float": + return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); + case "Swift.Bool": + return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); + case "Swift.UInt": + return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); + case "Swift.Double": + return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); + default: + return null; + } + } + + static SwiftName BuildMemberNesting (Node node, List nestings, List names) + { + if (node.Children.Count > 0 && node.Children [0].Kind == NodeKind.Extension) + node = node.Children [0].Children [1]; + var nesting = MemberNesting.Class; + switch (node.Kind) { + case NodeKind.Class: + break; + case NodeKind.Structure: + nesting = MemberNesting.Struct; + break; + case NodeKind.Enum: + nesting = MemberNesting.Enum; + break; + case NodeKind.Protocol: + nesting = MemberNesting.Protocol; + break; + case NodeKind.Module: + return new SwiftName (node.Text, false); + default: + throw new ArgumentOutOfRangeException (nameof (node), $"Expected a nominal type node kind but got {node.Kind.ToString ()}"); + } + + var privatePublicName = PrivateNamePublicName (node.Children [1]); + var className = new SwiftName (privatePublicName.Item2, false); + SwiftName moduleName = null; + if (node.Children [0].Kind == NodeKind.Identifier || node.Children [0].Kind == NodeKind.Module) { + moduleName = new SwiftName (node.Children [0].Text, false); + } else { + // recurse before adding names. + moduleName = BuildMemberNesting (node.Children [0], nestings, names); + } + names.Add (className); + nestings.Add (nesting); + return moduleName; + } + + + static Tuple PrivateNamePublicName (Node node) + { + if (node.Kind == NodeKind.Identifier) + return new Tuple (null, node.Text); + if (node.Kind == NodeKind.PrivateDeclName) + return new Tuple (node.Children [1].Text, node.Children [0].Text); + throw new ArgumentOutOfRangeException (nameof (node)); + } + + static SwiftType RenameFunctionParameters (SwiftType parameters, List labels) + { + if (labels.Count < 1) + throw new ArgumentOutOfRangeException (nameof (parameters)); + + var oldTuple = parameters as SwiftTupleType; + if (oldTuple == null) + throw new NotSupportedException ($"{parameters} is not a tuple, it's a {parameters.GetType ().Name}"); + + var newTuple = new SwiftTupleType (oldTuple.Contents.Select ((elem, index) => RenamedCloneOf (elem, labels [index])), + oldTuple.IsReference, oldTuple.Name); + return newTuple; + } + + static SwiftType RenamedCloneOf (SwiftType st, SwiftName newName) + { + return st.RenamedCloneOf (newName.Name == "_" ? new SwiftName ("", false) : newName); + } + + + // Swift does...weird...things with some of the core types from C. + // The mangler doesn't put in the appropriate swift module, but instead lumps them all + // together into the module __C. + // The mangler also puts a number of Foundation types into the namespace __ObjC. + // Why? No idea. + // I determined this list of __ObjC types by running the following command on all the Apple built libraries: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq + // which also includes a number of inner types which we don't care about (yet). + + // The command to do this for the __C namespace is: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq + + struct ModuleOrType { + public ModuleOrType (string replacementModule) + { + ReplacementModule = replacementModule; + ReplacementFullClassName = null; + ReplacementNesting = null; + } + + public ModuleOrType (string replacementFullClassName, string replacementNesting) + { + ReplacementFullClassName = replacementFullClassName; + ReplacementNesting = replacementNesting; + ReplacementModule = null; + } + + public string ReplacementModule; + public string ReplacementFullClassName; + public string ReplacementNesting; + } + + + static Dictionary classNameOntoModuleOrType = new Dictionary { + { "AVError", new ModuleOrType ("AVFoundation") }, + { "AudioBuffer", new ModuleOrType ("AudioToolbox") }, + { "AudioBufferList", new ModuleOrType ("AudioToolbox") }, + { "CATransform3D", new ModuleOrType ("CoreAnimation") }, + { "CGAffineTransform", new ModuleOrType ("CoreGraphics") }, + { "CGColorSapceModel", new ModuleOrType ("CoreGraphics") }, + { "CGPoint", new ModuleOrType ("CoreGraphics") }, + { "CGRect", new ModuleOrType ("CoreGraphics") }, + { "CGSize", new ModuleOrType ("CoreGraphics") }, + { "CGVector", new ModuleOrType ("CoreGraphics") }, + { "CLError", new ModuleOrType ("CoreLocation") }, + { "CMTime", new ModuleOrType ("CoreMedia") }, + { "CMTimeFlags", new ModuleOrType ("CoreMedia") }, + { "CMTimeMapping", new ModuleOrType ("CoreMedia") }, + { "CMTimeRange", new ModuleOrType ("CoreMedia") }, + { "NSComparisonResult", new ModuleOrType ("Foundation") }, + { "NSDecimal", new ModuleOrType ("Foundation") }, + { "NSEnumerationOptions", new ModuleOrType ("Foundation") }, + { "NSKeyValueChange", new ModuleOrType ("Foundation") }, + { "NSKeyValueObservingOptions", new ModuleOrType ("Foundation") }, + { "NSFastEnumerationState", new ModuleOrType ("Foundation") }, + { "NSKeyValueChangeKey", new ModuleOrType ("Foundation") }, + { "NSBundle", new ModuleOrType ("Foundation.Bundle", "C") }, + { "NSURL", new ModuleOrType ("Foundation") }, + { "StringTransform", new ModuleOrType ("Foundation") }, + { "URLFileResourceType", new ModuleOrType ("Foundation") }, + { "URLResourceKey", new ModuleOrType ("Foundation") }, + { "URLThumbnailDictionaryItem", new ModuleOrType ("Foundation") }, + { "URLUbiquitousItemDownloadingStatus", new ModuleOrType ("Foundation") }, + { "URLUbiquitousSharedItemPermissions", new ModuleOrType ("Foundation") }, + { "URLUbiquitousSharedItemRole", new ModuleOrType ("Foundation") }, + { "MKCoordinateSpan", new ModuleOrType ("MapKit") }, + { "NSAnimationEffect", new ModuleOrType ("AppKit") }, + { "SCNGeometryPrimitiveType", new ModuleOrType ("SceneKit") }, + { "SCNVector3", new ModuleOrType ("SceneKit") }, + { "SCNVector4", new ModuleOrType ("SceneKit") }, + { "UIContentSizeCategory", new ModuleOrType ("UIKit") }, + { "UIControlState", new ModuleOrType ("UIKit.UIControl.State", "CV") }, + { "UIDeviceOrientation", new ModuleOrType ("UIKit") }, + { "UIEdgeInsets", new ModuleOrType ("UIKit") }, + { "UIInterfaceOrientation", new ModuleOrType ("UIKit") }, + { "UIControlEvents", new ModuleOrType ("UIKit.UIControl.Event", "CV") }, + { "UIViewAnimationOptions", new ModuleOrType ("UIKit.UIView.AnimationOptions", "CV") }, + { "UIOffset", new ModuleOrType ("UIKit") }, + { "UIBlurEffectStyle", new ModuleOrType ("UIKit.UIBlurEffect.Style","CV") }, + { "UIColor", new ModuleOrType ("UIKit")}, + { "UIImage", new ModuleOrType ("UIImage") }, + { "UITableViewStyle", new ModuleOrType ("UIKit.UITableView.Style", "CV") }, + { "UIView", new ModuleOrType ("UIKit") }, + { "UIViewControllerConditioning", new ModuleOrType ("UIKit") }, + { "UIVisualEffectView", new ModuleOrType ("UIKit") }, + { "CKError", new ModuleOrType ("CloudKit") }, + { "CNError", new ModuleOrType ("Contacts") }, + { "MTLSamplePosition", new ModuleOrType ("Metal") }, + { "XCUIKeyboardKey", new ModuleOrType ("XCTest") }, + { "BNNSActivationFunction", new ModuleOrType ("Accelerate") }, + { "BNNSDataType", new ModuleOrType ("Accelerate") }, + { "simd_double2x2", new ModuleOrType ("Accelerate") }, + { "simd_double2x3", new ModuleOrType ("Accelerate") }, + { "simd_double2x4", new ModuleOrType ("Accelerate") }, + { "simd_double3x2", new ModuleOrType ("Accelerate") }, + { "simd_double3x3", new ModuleOrType ("Accelerate") }, + { "simd_double3x4", new ModuleOrType ("Accelerate") }, + { "simd_double4x2", new ModuleOrType ("Accelerate") }, + { "simd_double4x3", new ModuleOrType ("Accelerate") }, + { "simd_double4x4", new ModuleOrType ("Accelerate") }, + { "simd_float2x2", new ModuleOrType ("Accelerate") }, + { "simd_float2x3", new ModuleOrType ("Accelerate") }, + { "simd_float2x4", new ModuleOrType ("Accelerate") }, + { "simd_float3x2", new ModuleOrType ("Accelerate") }, + { "simd_float3x3", new ModuleOrType ("Accelerate") }, + { "simd_float3x4", new ModuleOrType ("Accelerate") }, + { "simd_float4x2", new ModuleOrType ("Accelerate") }, + { "simd_float4x3", new ModuleOrType ("Accelerate") }, + { "simd_float4x4", new ModuleOrType ("Accelerate") }, + { "simd_quatd", new ModuleOrType ("Accelerate") }, + { "simd_quatf", new ModuleOrType ("Accelerate") }, + }; + + static SwiftClassName PatchClassName (SwiftName moduleName, List nesting, List nestingNames) + { + // surprise! + // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version + // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough + // bottleneck to alias it. + if (moduleName.Name == "__ObjC") + moduleName = new SwiftName ("Foundation", false); + if (moduleName.Name != "__C" || nestingNames.Count != 1) + return new SwiftClassName (moduleName, nesting, nestingNames); + if (classNameOntoModuleOrType.ContainsKey (nestingNames[0].Name)) { + var moduleOrType = classNameOntoModuleOrType [nestingNames [0].Name]; + if (moduleOrType.ReplacementModule == null) { + return SwiftClassName.FromFullyQualifiedName (moduleOrType.ReplacementFullClassName, OperatorType.None, moduleOrType.ReplacementNesting); + } else { + moduleName = new SwiftName (moduleOrType.ReplacementModule, false); + } + } + return new SwiftClassName (moduleName, nesting, nestingNames); + } + + static Dictionary aliasNameOntoClassName = new Dictionary { + { "__C.NSOperatingSystemVersion", SwiftClassName.FromFullyQualifiedName ("Foundation.OperatingSystemVersion", OperatorType.None, 'V') }, + }; + + static SwiftClassName RemapTypeAlias (SwiftClassName className) + { + SwiftClassName newName = null; + return aliasNameOntoClassName.TryGetValue (className.ToFullyQualifiedName (true), out newName) ? newName : className; + } + } +} diff --git a/src/SwiftReflector/Demangling/TLDefinition.cs b/src/SwiftReflector/Demangling/TLDefinition.cs new file mode 100644 index 000000000000..a1df9c656eca --- /dev/null +++ b/src/SwiftReflector/Demangling/TLDefinition.cs @@ -0,0 +1,269 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Demangling { + public class TLDefinition { + protected TLDefinition (CoreCompoundType type, string mangledName, SwiftName module, ulong offset) + { + if (module == null) + throw new ArgumentNullException (nameof(module)); + Type = type; + Module = module; + MangledName = Exceptions.ThrowOnNull (mangledName, nameof(mangledName)); + Offset = offset; + } + + public CoreCompoundType Type { get; private set; } + public SwiftName Module { get; private set; } + public string MangledName { get; private set; } + public ulong Offset { get; private set; } + } + + public class TLModuleDescriptor : TLDefinition { + public TLModuleDescriptor (string mangledName, SwiftName module, ulong offset) + : base (CoreCompoundType.ModuleDescriptor, mangledName, module, offset) + { + } + } + + public class TLMetadataDescriptor : TLDefinition { + public TLMetadataDescriptor (SwiftType ofType, bool isBuiltIn, string mangledName, SwiftName module, ulong offset) + : base (CoreCompoundType.MetadataDescriptor, mangledName, module, offset) + { + OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); + IsBuiltIn = isBuiltIn; + } + public SwiftType OfType { get; private set; } + public bool IsBuiltIn { get; private set; } + } + + public class TLClassElem : TLDefinition { + protected TLClassElem (CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base (type, mangledName, module, offset) + { + Class = classType; + } + public SwiftClassType Class { get; private set; } + } + + public class TLThunk : TLClassElem { + public TLThunk (ThunkType thunkType, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base (CoreCompoundType.Thunk, mangledName, module, classType, offset) + { + Thunk = thunkType; + } + + public ThunkType Thunk { get; private set; } + } + + public class TLVariable : TLClassElem { + public TLVariable (string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn = null) + : this (CoreCompoundType.Variable, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) + { + } + + protected TLVariable (CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn) + : base (type, mangledName, module, classType, offset) + { + Name = Exceptions.ThrowOnNull (ident, nameof (ident)); + OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); + IsStatic = isStatic; + ExtensionOn = extensionOn; + } + public SwiftType OfType { get; private set; } + public SwiftType ExtensionOn { get; private set; } + public SwiftName Name { get; private set; } + public bool IsStatic { get; private set; } + } + + public class TLPropertyDescriptor : TLVariable { + public TLPropertyDescriptor (string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn = null) + : base (CoreCompoundType.PropertyDescriptor, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) + { + } + } + + public class TLUnsafeMutableAddressor : TLClassElem { + public TLUnsafeMutableAddressor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, ulong offset) + : base (CoreCompoundType.UnsafeMutableAddressor, mangledName, module, classType, offset) + { + Name = Exceptions.ThrowOnNull (ident, nameof (ident)); + OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); + } + public SwiftType OfType { get; private set; } + public SwiftName Name { get; private set; } + } + + public class TLFieldOffset : TLClassElem { + + public TLFieldOffset (string mangledName, SwiftName module, SwiftClassType classType, bool direct, SwiftName ident, SwiftType type, ulong offset) + : base (CoreCompoundType.FieldOffset, mangledName, module, classType, offset) + { + IsDirect = direct; + Identifier = ident; + FieldType = type; + } + + public bool IsDirect { get; private set; } + + public SwiftName Identifier { get; private set; } + public SwiftType FieldType { get; private set; } + } + + public class TLFunction : TLClassElem { + public TLFunction (string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : this (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.Function) + { + } + + protected TLFunction (string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None, + CoreCompoundType type = CoreCompoundType.Function) + : base (type, mangledName, module, classType, offset) + { + Name = functionName; + Signature = signature; + Operator = oper; + } + + public SwiftName Name { get; private set; } + public SwiftBaseFunctionType Signature { get; private set; } + public OperatorType Operator { get; private set; } + + public bool IsTopLevelFunction { get { return Class == null || Class.ClassName.Nesting.Count == 0; } } + } + + public class TLMethodDescriptor : TLFunction { + public TLMethodDescriptor (string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : base (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) + { + } + } + + public class TLEnumCase : TLFunction { + public TLEnumCase (string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : base (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) + { + } + } + + public class TLDefaultArgumentInitializer : TLDefinition { + public TLDefaultArgumentInitializer(string mangledName, SwiftName module, SwiftBaseFunctionType function, int index, ulong offset) + : base(CoreCompoundType.ArgumentInitializer, mangledName, module, offset) + { + Signature = Exceptions.ThrowOnNull (function, nameof (function)); + ArgumentIndex = index; + } + public SwiftBaseFunctionType Signature { get; private set; } + public int ArgumentIndex { get; private set; } + } + + public class TLLazyCacheVariable : TLClassElem { + public TLLazyCacheVariable (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.LazyCache, mangledName, module, cl, offset) + { + } + } + + public class TLDirectMetadata : TLClassElem { + public TLDirectMetadata (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) + { + } + } + + public class TLGenericMetadataPattern : TLClassElem { + public TLGenericMetadataPattern (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) + { + } + } + + public class TLMetaclass : TLClassElem { + public TLMetaclass (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.MetaClass, mangledName, module, cl, offset) + { + } + } + + public class TLNominalTypeDescriptor : TLClassElem { + public TLNominalTypeDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.NominalTypeDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLProtocolTypeDescriptor : TLClassElem { + public TLProtocolTypeDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.ProtocolTypeDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLProtocolConformanceDescriptor : TLDefinition { + public TLProtocolConformanceDescriptor (string mangledName, SwiftName module, SwiftType implementingType, + SwiftClassType forProtocol, ulong offset) + : base (CoreCompoundType.ProtocolConformanceDescriptor, mangledName, module, offset) + { + ImplementingType = Exceptions.ThrowOnNull (implementingType, nameof (implementingType)); + Protocol = forProtocol; + } + + public SwiftType ImplementingType { get; private set; } + public SwiftClassType Protocol { get; private set; } + } + + public class TLProtocolRequirementsBaseDescriptor : TLClassElem { + public TLProtocolRequirementsBaseDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base (CoreCompoundType.ProtocolRequirementsBaseDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLBaseConformanceDescriptor : TLClassElem { + public TLBaseConformanceDescriptor (string mangledName, SwiftName module, SwiftClassType protocol, SwiftClassType requirement, ulong offset) + : base (CoreCompoundType.BaseConformanceDescriptor, mangledName, module, protocol, offset) + { + ProtocolRequirement = Exceptions.ThrowOnNull (requirement, nameof (requirement)); + } + public SwiftClassType ProtocolRequirement { get; private set; } + } + + public class TLAssociatedTypeDescriptor : TLClassElem { + public TLAssociatedTypeDescriptor (string mangledName, SwiftName module, SwiftClassType protocol, SwiftName associatedTypeName, ulong offset) + : base (CoreCompoundType.AssociatedTypeDescriptor, mangledName, module, protocol, offset) + { + AssociatedTypeName = associatedTypeName; + } + + public SwiftName AssociatedTypeName { get; private set; } + } + + public class TLMetadataBaseOffset : TLClassElem { + public TLMetadataBaseOffset (string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base (CoreCompoundType.MetadataOffset, mangledName, module, classType, offset) + { + } + } + + public class TLMethodLookupFunction : TLClassElem { + public TLMethodLookupFunction (string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base (CoreCompoundType.MethodLookupFunction, mangledName, module, classType, offset) + { + + } + } +} + diff --git a/src/SwiftReflector/Enums.cs b/src/SwiftReflector/Enums.cs new file mode 100644 index 000000000000..092e314194e0 --- /dev/null +++ b/src/SwiftReflector/Enums.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SwiftReflector { + public enum CoreCompoundType { + ModuleName, + Function, + Class, + Struct, + Array, + Scalar, + Tuple, + BoundGeneric, + MetaClass, + LazyCache, + DirectMetadata, + NominalTypeDescriptor, + Variable, + Thunk, + ProtocolList, + ProtocolTypeDescriptor, + UnboundGeneric, + GenericReference, + FieldOffset, + ArgumentInitializer, + UnsafeMutableAddressor, + ProtocolConformanceDescriptor, + MethodDescriptor, + ModuleDescriptor, + PropertyDescriptor, + MetadataDescriptor, + ProtocolRequirementsBaseDescriptor, + BaseConformanceDescriptor, + AssociatedTypeDescriptor, + MetadataOffset, + MethodLookupFunction, + } + + public enum CoreBuiltInType { + Int, + UInt, + Double, + Float, + Bool, + } + + public enum EntityType { + None, + Class, + Struct, + Enum, + TrivialEnum, + Scalar, + Protocol, + Tuple, + Closure, + ProtocolList, + DynamicSelf, + } + + public enum MemberNesting { + Class, + Struct, + Enum, + Protocol, + } + + public enum MemberType { + Function, + UncurriedFunction, + Allocator, + Constructor, + Destructor, + Deallocator, + Getter, + Setter, + Materializer, + ExplicitClosure, + Addressor, + CFunction, + Initializer, + } + + public enum PropertyType { + Getter, + Setter, + Materializer, + DidSet, + WillSet, + ModifyAccessor, + } + + public enum AddressorType { + OwningMutable, + NativeOwningMutable, + NativePinningMutable, + UnsafeMutable, + Owning, + NativeOwning, + NativePinning, + Unsafe, + } + + public enum InitializerType { + Variable, + } + + public enum ThunkType { + Reabstraction, + ReabstractionHelper, + ProtocolWitness, + Curry, + } + + public enum OperatorType { + None, + Prefix, + Postfix, + Infix, + Unknown, + } + + public enum WitnessType { + Class, + Value, + Protocol, + ProtocolAccessor, + } + + public enum PlatformName { + None, // desktop managed executable + macOS, // Xamarin.Mac app + iOS, + watchOS, + tvOS, + } + + public enum SwiftTypeAttribute { + ObjC, + NonObjC, + Dynamic, + ImplFunction, + DirectMethodReference, + } + + public enum ReflectionStrategy { + None, + [Obsolete ("Compiler reflection is no longer supported.", true)] + Compiler, + Parser, + } + + public enum TargetCpu { + Arm64, + Armv7, + Armv7s, + Arm7vk, + Arm64e, + Arm64_32, + I386, + X86_64, + } + + public enum TargetManufacturer { + Apple, + } + + public enum TargetEnvironment { + Device, + Simulator, + } + + public enum TargetRepresentationKind { + None, + Library, + Framework, + XCFramework, + } +} + diff --git a/src/SwiftReflector/ErrorHandling.cs b/src/SwiftReflector/ErrorHandling.cs new file mode 100644 index 000000000000..88869faf5692 --- /dev/null +++ b/src/SwiftReflector/ErrorHandling.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//#define CRASH_ON_EXCEPTION + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.ExceptionServices; + +namespace SwiftReflector { + public class ErrorHandling { + object messagesLock = new object (); + List messages; + + public ErrorHandling () + { + messages = new List (); + SkippedTypes = new List (); + SkippedFunctions = new List (); + } + + public IEnumerable Messages { + get { return messages; } + } + + public IEnumerable Errors { + get { return messages.Where ((v) => !v.IsWarning); } + } + + public IEnumerable Warnings { + get { return messages.Where ((v) => v.IsWarning); } + } + + public List SkippedTypes { get; private set; } + public List SkippedFunctions { get; private set; } + + public void Add (ErrorHandling eh) + { + lock (messagesLock) { + lock (eh.messagesLock) { + messages.AddRange (eh.messages); + } + } + } + + public void Add (params ReflectorError [] errors) + { + lock (messagesLock) { + messages.AddRange (errors); + } + } + + public void Add (Exception exception) + { + lock (messagesLock) { +#if CRASH_ON_EXCEPTION + ExceptionDispatchInfo.Capture (exception).Throw (); +#else + messages.Add (new ReflectorError (exception)); +#endif + } + } + + public bool AnyMessages { + get { + lock (messagesLock) { + return messages.Count > 0; + } + } + } + + public bool AnyErrors { + get { + lock (messagesLock) { + return messages.Any ((v) => !v.IsWarning); + } + } + } + + public int WarningCount { + get { + lock (messagesLock) { + return messages.Count ((v) => v.IsWarning); + } + } + } + + public int ErrorCount { + get { + lock (messagesLock) { + return messages.Count ((v) => !v.IsWarning); + } + } + } + + public int Show (int verbosity) + { + // ErrorHelper.Verbosity = verbosity; + // return ErrorHelper.Show (messages.Select ((v) => v.Exception)); + return verbosity; + } + } +} diff --git a/src/SwiftReflector/ExceptionTools/ErrorHelper.cs b/src/SwiftReflector/ExceptionTools/ErrorHelper.cs new file mode 100644 index 000000000000..de1637ae3844 --- /dev/null +++ b/src/SwiftReflector/ExceptionTools/ErrorHelper.cs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using ProductException = SwiftReflector.ExceptionTools.RuntimeException; + +namespace SwiftReflector.ExceptionTools { + static class ErrorHelper { + public enum WarningLevel + { + Error = -1, + Warning = 0, + Disable = 1, + } + public const string Prefix = "BT"; + static Dictionary warning_levels; + public static int Verbosity { get; set; } + + public static WarningLevel GetWarningLevel (int code) + { + WarningLevel level; + + if (warning_levels == null) + return WarningLevel.Warning; + + // code -1: all codes + if (warning_levels.TryGetValue (-1, out level)) + return level; + + if (warning_levels.TryGetValue (code, out level)) + return level; + + return WarningLevel.Warning; + } + + public static void SetWarningLevel (WarningLevel level, int? code = null /* if null, apply to all warnings */) + { + if (warning_levels == null) + warning_levels = new Dictionary (); + if (code.HasValue) { + warning_levels [code.Value] = level; + } else { + warning_levels [-1] = level; // code -1: all codes. + } + } + + public static ProductException CreateError (int code, string message, params object[] args) + { + return new ProductException (code, true, message, args); + } + + public static ProductException CreateError (int code, Exception innerException, string message, params object[] args) + { + return new ProductException (code, true, innerException, message, args); + } + + public static ProductException CreateWarning (int code, string message, params object[] args) + { + return new ProductException (code, false, message, args); + } + + public static ProductException CreateWarning (int code, Exception innerException, string message, params object [] args) + { + return new ProductException (code, false, innerException, message, args); + } + + public static void Error (int code, Exception innerException, string message, params object[] args) + { + throw new ProductException (code, true, innerException, message, args); + } + + public static void Error (int code, string message, params object[] args) + { + throw new ProductException (code, true, message, args); + } + + public static void Warning (int code, string message, params object[] args) + { + Show (new ProductException (code, false, message, args)); + } + + public static void Warning (int code, Exception innerException, string message, params object[] args) + { + Show (new ProductException (code, false, innerException, message, args)); + } + + public static int Show (IEnumerable list) + { + List exceptions = new List (); + bool error = false; + + foreach (var e in list) + CollectExceptions (e, exceptions); + + foreach (var ex in exceptions) + error |= ShowInternal (ex); + + return error ? 1 : 0; + } + + static public int Show (Exception e) + { + List exceptions = new List (); + bool error = false; + + CollectExceptions (e, exceptions); + + foreach (var ex in exceptions) + error |= ShowInternal (ex); + + return error ? 1 : 0; + } + + static void Exit (int exitCode) + { + Environment.Exit (exitCode); + } + + static void CollectExceptions (Exception ex, List exceptions) + { + AggregateException ae = ex as AggregateException; + + if (ae != null && ae.InnerExceptions.Count > 0) { + foreach (var ie in ae.InnerExceptions) + CollectExceptions (ie, exceptions); + } else { + exceptions.Add (ex); + } + } + + static bool ShowInternal (Exception e) + { + ProductException mte = (e as ProductException); + bool error = true; + + if (mte != null) { + error = mte.Error; + + if (!error && GetWarningLevel (mte.Code) == WarningLevel.Disable) + return false; // This is an ignored warning. + + Console.Error.WriteLine (mte.ToString ()); + + if (Verbosity > 1) + ShowInner (e); + + if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) + Console.Error.WriteLine (e.StackTrace); + } else { + Console.Error.WriteLine (e.ToString ()); + if (Verbosity > 1) + ShowInner (e); + if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) + Console.Error.WriteLine (e.StackTrace); + } + + return error; + } + + static void ShowInner (Exception e) + { + Exception ie = e.InnerException; + if (ie == null) + return; + + if (Verbosity > 3) { + Console.Error.WriteLine ("--- inner exception"); + Console.Error.WriteLine (ie); + Console.Error.WriteLine ("---"); + } else { + Console.Error.WriteLine ("\t{0}", ie.Message); + } + ShowInner (ie); + } + } +} diff --git a/src/SwiftReflector/ExceptionTools/RuntimeException.cs b/src/SwiftReflector/ExceptionTools/RuntimeException.cs new file mode 100644 index 000000000000..6b9a62e31f3b --- /dev/null +++ b/src/SwiftReflector/ExceptionTools/RuntimeException.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace SwiftReflector.ExceptionTools { + + public class RuntimeException : Exception { + // Store the stack trace when this exception was created, and return + // it if the base class doesn't have a stack trace (which would happen + // if this exception was never thrown). + string stack_trace; + + public RuntimeException (string message, params object [] args) + : base (string.Format (message, args)) + { + stack_trace = new System.Diagnostics.StackTrace (true).ToString (); + } + + public RuntimeException (int code, string message, params object [] args) : + this (code, false, message, args) + { + } + + public RuntimeException (int code, bool error, string message, params object [] args) : + this (code, error, null, message, args) + { + } + + public RuntimeException (int code, bool error, Exception innerException, string message, params object [] args) : + base (String.Format (message, args), innerException) + { + stack_trace = new System.Diagnostics.StackTrace (true).ToString (); + Code = code; + Error = error; + } + + public int Code { get; private set; } + + public bool Error { get; private set; } + + // http://blogs.msdn.com/b/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx + public override string ToString () + { + return String.Format ("{0} {1:0000}: {2}", Error ? "error" : "warning", Code, Message); + } + + public override string StackTrace { + get { + var thrownTrace = base.StackTrace; + if (string.IsNullOrEmpty (thrownTrace)) + return stack_trace; + return thrownTrace; + } + } + } +} diff --git a/src/SwiftReflector/Extensions.cs b/src/SwiftReflector/Extensions.cs new file mode 100644 index 000000000000..efa659614982 --- /dev/null +++ b/src/SwiftReflector/Extensions.cs @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using Xamarin; +using System.Text; +using SyntaxDynamo; +using System.Collections; + +namespace SwiftReflector { + public static class Extensions { + public static IEnumerable Yield (this T elem) + { + yield return elem; + } + + public static bool IsSwiftEntryPoint (this NListEntry entry) + { + return !String.IsNullOrEmpty (entry.str) && (entry.str.StartsWith ("__T", StringComparison.Ordinal) || + entry.str.StartsWith ("_$s", StringComparison.Ordinal) || entry.str.StartsWith ("_$S", StringComparison.Ordinal)); + } + + public static IEnumerable SwiftEntryPoints (this IEnumerable entries) + { + return entries.Where (IsSwiftEntryPoint); + } + + public static IEnumerable SwiftEntryPointNames (this IEnumerable entries) + { + return entries.SwiftEntryPoints ().Select (nle => nle.str); + } + + public static string DePunyCode (this string s) + { + return PunyCode.PunySingleton.Decode (s); + } + + public static Tuple SplitModuleFromName (this string s) + { + int dotIndex = s.IndexOf ('.'); + if (dotIndex < 0) + return new Tuple (null, s); + if (dotIndex == 0) + return new Tuple (null, s.Substring (1)); + return new Tuple (s.Substring (0, dotIndex), s.Substring (dotIndex + 1)); + } + + public static string ModuleFromName (this string s) + { + return s.SplitModuleFromName ().Item1; + } + + public static string NameWithoutModule (this string s) + { + return s.SplitModuleFromName ().Item2; + } + + public static string [] DecomposeClangTarget (this string s) + { + if (String.IsNullOrEmpty (s)) + throw new ArgumentNullException (nameof (s)); + string [] parts = s.Split ('-'); + // catalyst adds cpu-platform-ios-macabi + if (parts.Length != 3 && parts.Length != 4) + throw new ArgumentOutOfRangeException (nameof (s), s, "target should be in the form cpu-platform-os"); + + var shortestIndex = parts.Length == 3 ? + IndexOfMin (parts [0].Length, parts [1].Length, parts [2].Length) : + IndexOfMin (parts [0].Length, parts [1].Length, parts [2].Length, parts [3].Length); + + if (parts [shortestIndex].Length == 0) { + var missingPart = new string [] { "cpu", "platform", "os", "os" } [shortestIndex]; + throw new ArgumentException ($"target (cpu-platform-os) has an empty {missingPart} component."); + } + + return parts; + } + + static int IndexOfMin (params int [] values) + { + var min = values.Min (); + return Array.IndexOf (values, min); + } + + public static string ClangTargetCpu (this string s) + { + return s.DecomposeClangTarget () [0]; + } + + public static string ClangTargetPlatform (this string s) + { + return s.DecomposeClangTarget () [1]; + } + + public static string ClangTargetOS (this string s) + { + var clangTarget = s.DecomposeClangTarget (); + if (clangTarget.Length == 3) + return clangTarget [2]; + if (clangTarget.Length == 4) + return $"{clangTarget [2]}-{clangTarget [3]}"; + throw new ArgumentException ($"Clang target {s} should have 3 or 4 parts", nameof (s)); + } + + static int IndexOfFirstDigit (string s) + { + int index = 0; + foreach (char c in s) { + if (Char.IsDigit (c)) + return index; + index++; + } + return -1; + } + + public static string ClangOSNoVersion (this string s) + { + var clangTarget = s.DecomposeClangTarget (); + var os = clangTarget [2]; + return OSNoVersion (os); + } + + static string OSNoVersion (string s) + { + var firstNumber = IndexOfFirstDigit (s); + return firstNumber < 0 ? s : s.Substring (0, firstNumber); + } + + public static string ClangOSVersion (this string s) + { + var clangTarget = s.DecomposeClangTarget (); + var os = clangTarget [2]; + var firstNumber = IndexOfFirstDigit (os); + return os.Substring (firstNumber); + } + + public static string MinimumClangVersion (IEnumerable targets) + { + var osVersion = targets.Select (t => new Version (ClangOSVersion (t))).Min (); + return osVersion.ToString (); + } + + public static string ClangSubstituteOSVersion (this string s, string replacementVersion) + { + var clangTarget = s.DecomposeClangTarget (); + var os = OSNoVersion (clangTarget [2]) + replacementVersion; + clangTarget [2] = os; + return clangTarget.InterleaveStrings ("-"); + } + + public static bool ClangTargetIsSimulator (this string s) + { + var parts = s.DecomposeClangTarget (); + if (parts.Length == 4 && parts [3] == "simulator") + return true; + var osNoVersion = OSNoVersion (parts [2]); + if (osNoVersion == "macosx") + return false; + var cpu = parts [0]; + return cpu == "i386" || cpu == "x86-64"; + } + + public static void Merge (this HashSet to, IEnumerable from) + { + Exceptions.ThrowOnNull (from, nameof (from)); + foreach (T val in from) + to.Add (val); + } + + public static void DisposeAll (this IEnumerable coll) where T : IDisposable + { + Exceptions.ThrowOnNull (coll, nameof (coll)); + foreach (T obj in coll) { + if ((IDisposable)obj != null) + obj.Dispose (); + } + } + + public static string InterleaveStrings (this IEnumerable elements, string separator, bool includeSepFirst = false) + { + StringBuilder sb = new StringBuilder (); + foreach (string s in elements.Interleave (separator, includeSepFirst)) + sb.Append (s); + return sb.ToString (); + } + + public static string InterleaveCommas (this IEnumerable elements) + { + return elements.InterleaveStrings (", "); + } + + public static bool IsSwift3(this Version vers) + { + return vers.Major == 3; + } + + public static bool IsSwift4 (this Version vers) + { + return vers.Major == 4; + } + + public static int ErrorCount(this List errors) + { + var count = 0; + foreach (var error in errors) { + if (!error.IsWarning) + ++count; + } + return count; + } + + public static int WarningCount(this List errors) + { + return errors.Count - errors.ErrorCount (); + } + + public static List CloneAndPrepend(this List source, T item) + { + var result = new List (source.Count + 1); + result.Add (item); + result.AddRange (source); + return result; + } + + public static T[] And (this T[] first, T[] second) + { + Exceptions.ThrowOnNull (first, nameof (first)); + Exceptions.ThrowOnNull (second, nameof (second)); + var result = new T [first.Length + second.Length]; + Array.Copy (first, result, first.Length); + Array.Copy (second, 0, result, first.Length, second.Length); + return result; + } + } +} + diff --git a/src/SwiftReflector/IOUtils/ExecAndCollect.cs b/src/SwiftReflector/IOUtils/ExecAndCollect.cs new file mode 100644 index 000000000000..37469c532375 --- /dev/null +++ b/src/SwiftReflector/IOUtils/ExecAndCollect.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; + +namespace SwiftReflector.IOUtils { + public class ExecAndCollect { + public static string Run (string path, string args, string workingDirectory = null, bool verbose = false) + { + var output = new StringBuilder (); + var exitCode = RunCommand (path, args, output: output, verbose: verbose, workingDirectory: workingDirectory); + if (exitCode != 0) + throw new Exception ($"Failed to execute (exit code {exitCode}): {path} {string.Join (" ", args)}\n{output.ToString ()}"); + return output.ToString (); + } + + static void ReadStream (Stream stream, StringBuilder sb, ManualResetEvent completed) + { + var encoding = Encoding.UTF8; + var decoder = encoding.GetDecoder (); + var buffer = new byte [1024]; + var characters = new char [encoding.GetMaxCharCount (buffer.Length)]; + + AsyncCallback callback = null; + callback = new AsyncCallback ((IAsyncResult ar) => { + var read = stream.EndRead (ar); + + var chars = decoder.GetChars (buffer, 0, read, characters, 0); + lock (sb) + sb.Append (characters, 0, chars); + + if (read > 0) { + stream.BeginRead (buffer, 0, buffer.Length, callback, null); + } else { + completed.Set (); + } + }); + stream.BeginRead (buffer, 0, buffer.Length, callback, null); + } + + public static int RunCommand (string path, string args, IDictionary env = null, StringBuilder output = null, bool verbose = false, string workingDirectory = null) + { + var info = new ProcessStartInfo (path, args); + info.UseShellExecute = false; + info.RedirectStandardInput = false; + info.RedirectStandardOutput = true; + info.RedirectStandardError = true; + if (workingDirectory != null) + info.WorkingDirectory = workingDirectory; + + if (output == null) + output = new StringBuilder (); + + if (env != null) { + foreach (var kvp in env) { + if (kvp.Value == null) { + if (info.EnvironmentVariables.ContainsKey (kvp.Key)) + info.EnvironmentVariables.Remove (kvp.Key); + } else { + info.EnvironmentVariables [kvp.Key] = kvp.Value; + } + } + } + + if (info.EnvironmentVariables.ContainsKey ("XCODE_DEVELOPER_DIR_PATH")) { + // VSfM adds this key, which confuses Xcode mightily if it doesn't match the value of xcode-select. + // So just remove it, we don't need it for anything. + info.EnvironmentVariables.Remove ("XCODE_DEVELOPER_DIR_PATH"); + } + + + if (verbose) { + var envOut = new StringBuilder (); + foreach (var key in info.EnvironmentVariables.Keys) { + var value = info.EnvironmentVariables [key as string]; + envOut.AppendLine ($"export {key}={value}"); + } + envOut.AppendLine ($"{path} {args}"); + Console.Write (envOut.ToString ()); + Console.WriteLine ("{0} {1}", path, args); + } + + using (var p = Process.Start (info)) { + var error_output = new StringBuilder (); + var stdout_completed = new ManualResetEvent (false); + var stderr_completed = new ManualResetEvent (false); + + ReadStream (p.StandardOutput.BaseStream, output, stdout_completed); + ReadStream (p.StandardError.BaseStream, error_output, stderr_completed); + + p.WaitForExit (); + + stderr_completed.WaitOne (TimeSpan.FromMinutes (1)); + stdout_completed.WaitOne (TimeSpan.FromMinutes (1)); + + if (verbose) { + if (output.Length > 0) + Console.WriteLine (output); + if (error_output.Length > 0) + Console.WriteLine (error_output); + if (p.ExitCode != 0) + Console.Error.WriteLine ($"Process exited with code {p.ExitCode}"); + } + if (p.ExitCode != 0 && error_output.Length > 0) + output.Append (error_output); + return p.ExitCode; + } + } + } +} diff --git a/src/SwiftReflector/IOUtils/IFileProvider.cs b/src/SwiftReflector/IOUtils/IFileProvider.cs new file mode 100644 index 000000000000..41036297bbc2 --- /dev/null +++ b/src/SwiftReflector/IOUtils/IFileProvider.cs @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SwiftReflector.IOUtils { + public interface IFileProvider { + string ProvideFileFor (T thing); + void NotifyFileDone (T thing, string stm); + } +} + diff --git a/src/SwiftReflector/IOUtils/IXElementConvertible.cs b/src/SwiftReflector/IOUtils/IXElementConvertible.cs new file mode 100644 index 000000000000..d179c3181b6e --- /dev/null +++ b/src/SwiftReflector/IOUtils/IXElementConvertible.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Xml.Linq; + +namespace SwiftReflector.IOUtils { + public interface IXElementConvertible { + XElement ToXElement (); + } +} + diff --git a/src/SwiftReflector/IOUtils/OffsetStream.cs b/src/SwiftReflector/IOUtils/OffsetStream.cs new file mode 100644 index 000000000000..f7479e4c79d4 --- /dev/null +++ b/src/SwiftReflector/IOUtils/OffsetStream.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; + +namespace SwiftReflector.IOUtils { + public class OffsetStream : Stream { + Stream stm; + long offset; + public OffsetStream (Stream stm, long offset) + { + this.stm = stm; + this.offset = offset; + stm.Seek (offset, SeekOrigin.Begin); + } + + public override bool CanRead { + get { + return stm.CanRead; + } + } + + public override bool CanSeek { + get { + return stm.CanSeek; + } + } + + public override bool CanTimeout { + get { + return stm.CanTimeout; + } + } + + public override bool CanWrite { + get { + return stm.CanWrite; + } + } + + public override void Close () + { + stm.Close (); + base.Close (); + } + + public override IAsyncResult BeginRead (byte [] buffer, int offset, int count, AsyncCallback callback, object state) + { + return stm.BeginRead (buffer, offset, count, callback, state); + } + + public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count, AsyncCallback callback, object state) + { + return stm.BeginWrite (buffer, offset, count, callback, state); + } + + public override System.Threading.Tasks.Task CopyToAsync (Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) + { + return stm.CopyToAsync (destination, bufferSize, cancellationToken); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + stm.Dispose (); + base.Dispose (); + } + + public override int EndRead (IAsyncResult asyncResult) + { + return stm.EndRead (asyncResult); + } + + public override void EndWrite (IAsyncResult asyncResult) + { + stm.EndWrite (asyncResult); + } + + public override void Flush () + { + stm.Flush (); + } + + public override System.Threading.Tasks.Task FlushAsync (System.Threading.CancellationToken cancellationToken) + { + return stm.FlushAsync (cancellationToken); + } + + public override long Length { + get { + return stm.Length - offset; + } + } + + public override long Position { + get { + return stm.Position - offset; + } + set { + stm.Position = value + offset; + } + } + + public override int Read (byte [] buffer, int offset, int count) + { + return stm.Read (buffer, offset, count); + } + + public override System.Threading.Tasks.Task ReadAsync (byte [] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + { + return stm.ReadAsync (buffer, offset, count, cancellationToken); + } + + public override int ReadByte () + { + return stm.ReadByte (); + } + + public override int ReadTimeout { + get { + return stm.ReadTimeout; + } + set { + stm.ReadTimeout = value; + } + } + + public override long Seek (long offset, SeekOrigin origin) + { + switch (origin) { + case SeekOrigin.Begin: + return stm.Seek (offset + this.offset, origin) - this.offset; + case SeekOrigin.Current: + return stm.Seek (offset, origin) - this.offset; + case SeekOrigin.End: + return stm.Seek (offset, origin) - this.offset; + default: + return 0; + } + } + + public override void SetLength (long value) + { + stm.SetLength (value); + } + + public override void Write (byte [] buffer, int offset, int count) + { + stm.Write (buffer, offset, count); + } + } +} + diff --git a/src/SwiftReflector/Inventory/ClassContents.cs b/src/SwiftReflector/Inventory/ClassContents.cs new file mode 100644 index 000000000000..ded6505dbcab --- /dev/null +++ b/src/SwiftReflector/Inventory/ClassContents.cs @@ -0,0 +1,307 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.Linq; +using System.Collections.Generic; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class ClassContents { + int sizeofMachinePointer; + public ClassContents (SwiftClassName className, int sizeofMachiinePointer) + { + this.sizeofMachinePointer = sizeofMachiinePointer; + Constructors = new FunctionInventory (sizeofMachinePointer); + ClassConstructor = new FunctionInventory (sizeofMachinePointer); + Methods = new FunctionInventory (sizeofMachinePointer); + Properties = new PropertyInventory (sizeofMachinePointer); + StaticProperties = new PropertyInventory (sizeofMachiinePointer); + PrivateProperties = new PropertyInventory (sizeofMachinePointer); + StaticPrivateProperties = new PropertyInventory (sizeofMachinePointer); + Subscripts = new List (sizeofMachinePointer); + PrivateSubscripts = new List (sizeofMachinePointer); + StaticFunctions = new FunctionInventory (sizeofMachinePointer); + Destructors = new FunctionInventory (sizeofMachinePointer); + EnumCases = new FunctionInventory (sizeofMachiinePointer); + WitnessTable = new WitnessInventory (sizeofMachinePointer); + FunctionsOfUnknownDestination = new List (); + DefinitionsOfUnknownDestination = new List (); + Variables = new VariableInventory (sizeofMachinePointer); + Initializers = new FunctionInventory (sizeofMachinePointer); + Name = className; + ProtocolConformanceDescriptors = new List (); + MethodDescriptors = new FunctionInventory (sizeofMachinePointer); + PropertyDescriptors = new List (); + } + + public void Add (TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) { + if (IsConstructor (tlf.Signature, tlf.Class)) { + AddOrChainInNewThunk (Constructors, tlf, srcStm); + } else if (tlf.Signature is SwiftClassConstructorType) { + if (ClassConstructor.Values.Count () == 0) + AddOrChainInNewThunk (ClassConstructor, tlf, srcStm); + else + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 12, $"multiple type metadata accessors for {tlf.Class.ClassName.ToFullyQualifiedName ()}"); + } else if (IsDestructor (tlf.Signature, tlf.Class)) { + AddOrChainInNewThunk (Destructors, tlf, srcStm); + } else if (tlf is TLEnumCase) { + AddOrChainInNewThunk (EnumCases, tlf, srcStm); + } else if (IsProperty (tlf.Signature, tlf.Class)) { + if (IsSubscript (tlf.Signature, tlf.Class)) { + if (IsPrivateProperty (tlf.Signature, tlf.Class)) + PrivateSubscripts.Add (tlf); + else + Subscripts.Add (tlf); + } else { + if (IsStaticProperty (tlf.Signature, tlf.Class)) { + if (IsPrivateProperty (tlf.Signature, tlf.Class)) + StaticPrivateProperties.Add (tlf, srcStm); + else + StaticProperties.Add (tlf, srcStm); + } else { + if (IsPrivateProperty (tlf.Signature, tlf.Class)) + PrivateProperties.Add (tlf, srcStm); + else + Properties.Add (tlf, srcStm); + } + } + } else if (IsMethodOnClass (tlf.Signature, tlf.Class)) { + if (tlf is TLMethodDescriptor) + MethodDescriptors.Add (tlf, srcStm); + else { + AddOrChainInNewThunk (Methods, tlf, srcStm); + } + } else if (IsStaticMethod (tlf.Signature, tlf.Class)) { + AddOrChainInNewThunk (StaticFunctions, tlf, srcStm); + } else if (IsWitnessTable (tlf.Signature, tlf.Class)) { + WitnessTable.Add (tlf, srcStm); + } else if (IsInitializer (tlf.Signature, tlf.Class)) { + AddOrChainInNewThunk (Initializers, tlf, srcStm); + } else { + FunctionsOfUnknownDestination.Add (tlf); + } + return; + } + var meta = tld as TLDirectMetadata; + if (meta != null) { + if (DirectMetadata != null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 13, $"duplicate direct metadata in class {DirectMetadata.Class.ClassName.ToFullyQualifiedName ()}"); + DirectMetadata = meta; + return; + } + var lazy = tld as TLLazyCacheVariable; + if (lazy != null) { + if (LazyCacheVariable != null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 14, $"duplicate lazy cache variable in class {LazyCacheVariable.Class.ClassName.ToFullyQualifiedName ()}"); + LazyCacheVariable = lazy; + return; + } + var mc = tld as TLMetaclass; + if (mc != null) { + if (Metaclass != null) { + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 15, $"duplicate type meta data descriptor in class {Metaclass.Class.ClassName.ToFullyQualifiedName ()}"); + } + Metaclass = mc; + return; + } + var nom = tld as TLNominalTypeDescriptor; + if (nom != null) { + if (TypeDescriptor != null) { + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 16, $"duplicate nominal type descriptor in class {TypeDescriptor.Class.ClassName.ToFullyQualifiedName ()}"); + } + TypeDescriptor = nom; + return; + } + var tlvar = tld as TLVariable; + if (tlvar != null) { + if (tlvar is TLPropertyDescriptor tlpropDesc) + PropertyDescriptors.Add (tlpropDesc); + else + Variables.Add (tlvar, srcStm); + return; + } + var tlprot = tld as TLProtocolConformanceDescriptor; + if (tlprot != null) { + ProtocolConformanceDescriptors.Add (tlprot); + return; + } + DefinitionsOfUnknownDestination.Add (tld); + } + + static void AddOrChainInNewThunk (FunctionInventory inventory, TLFunction newTLF, Stream sourceStream) + { + var oldTLF = inventory.ContainsEquivalentFunction (newTLF); + if (oldTLF == null) + inventory.Add (newTLF, sourceStream); + else { + var newSig = newTLF.Signature; + var oldSig = oldTLF.Signature; + if (oldSig.IsThunk) { + newSig.Thunk = oldSig; + inventory.ReplaceFunction (oldTLF, newTLF); + } else { + oldSig.Thunk = newSig; + } + } + } + + public bool IsFinal (TLFunction func) + { + string funcMangledSuffix = func.MangledName.Substring (3); // drop the __T + + foreach (string mangledWitnessEntry in WitnessTable.MangledNames) { + if (mangledWitnessEntry.EndsWith (funcMangledSuffix)) + return false; + } + return true; + } + + static bool IsConstructor (SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + SwiftConstructorType des = signature as SwiftConstructorType; + if (des == null) + return false; + return des.Name.Equals (Decomposer.kSwiftAllocatingConstructorName) + || des.Name.Equals (Decomposer.kSwiftNonAllocatingConstructorName); + } + + static bool IsDestructor (SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + SwiftDestructorType des = signature as SwiftDestructorType; + if (des == null) + return false; + return des.Name.Equals (Decomposer.kSwiftDeallocatingDestructorName) + || des.Name.Equals (Decomposer.kSwiftNonDeallocatingDestructorName); + } + + public static bool IsWitnessTable (SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + return signature is SwiftWitnessTableType; + } + + public static bool IsInitializer (SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + return signature is SwiftInitializerType; + } + + static bool IsProperty (SwiftType signature, SwiftClassType cl) + { + return signature is SwiftPropertyType; + } + + static bool IsSubscript (SwiftType signature, SwiftClassType cl) + { + SwiftPropertyType prop = signature as SwiftPropertyType; + return prop != null && prop.IsSubscript; + } + + static bool IsPrivateProperty (SwiftType signature, SwiftClassType cl) + { + SwiftPropertyType pt = signature as SwiftPropertyType; + return pt != null && pt.IsPrivate; + } + + static bool IsStaticProperty(SwiftType signature, SwiftClassType classType) + { + SwiftPropertyType pt = signature as SwiftPropertyType; + return pt != null && pt.IsStatic; + } + + static bool IsMethodOnClass (SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + if (signature is SwiftWitnessTableType) + return false; + SwiftUncurriedFunctionType ucf = signature as SwiftUncurriedFunctionType; + if (ucf == null) + return false; + return ucf.UncurriedParameter is SwiftClassType && ucf.UncurriedParameter.Equals (cl); + } + + static bool IsStaticMethod (SwiftType signature, SwiftClassType cl) + { + return signature is SwiftStaticFunctionType; + } + + public IEnumerable AllPropertiesWithName(string name) + { + PropertyContents prop = null; + if (Properties.TryGetValue (name, out prop)) + yield return prop; + if (PrivateProperties.TryGetValue (name, out prop)) + yield return prop; + if (StaticProperties.TryGetValue (name, out prop)) + yield return prop; + if (StaticPrivateProperties.TryGetValue (name, out prop)) + yield return prop; + } + + public TLFunction SoleMetadataAccessor { + get { + if (ClassConstructor == null || ClassConstructor.Values.Count () == 0) + return null; + var elem = ClassConstructor.Values.ElementAt (0); + if (elem.Functions.Count == 0) + return null; + return elem.Functions [0]; + } + } + + + public SwiftClassName Name { get; private set; } + public FunctionInventory Constructors { get; private set; } + public FunctionInventory ClassConstructor { get; private set; } + public FunctionInventory Destructors { get; private set; } + public FunctionInventory EnumCases { get; private set; } + public PropertyInventory Properties { get; private set; } + public PropertyInventory StaticProperties { get; private set; } + public PropertyInventory PrivateProperties { get; private set; } + public PropertyInventory StaticPrivateProperties { get; private set; } + public List Subscripts { get; private set; } + public List PrivateSubscripts { get; private set; } + public FunctionInventory Methods { get; private set; } + public FunctionInventory StaticFunctions { get; private set; } + public WitnessInventory WitnessTable { get; private set; } + public TLLazyCacheVariable LazyCacheVariable { get; private set; } + public TLDirectMetadata DirectMetadata { get; private set; } + public TLMetaclass Metaclass { get; private set; } + public TLNominalTypeDescriptor TypeDescriptor { get; private set; } + public List FunctionsOfUnknownDestination { get; private set; } + public List DefinitionsOfUnknownDestination { get; private set; } + public VariableInventory Variables { get; private set; } + public List PropertyDescriptors { get; private set; } + public FunctionInventory Initializers { get; private set; } + public List ProtocolConformanceDescriptors { get; private set; } + public FunctionInventory MethodDescriptors { get; private set; } + + public int SizeInBytes { + get { + ValueWitnessTable vat = WitnessTable.ValueWitnessTable; + return vat != null ? (int)vat.Size : 0; + } + } + public int StrideInBytes { + get { + ValueWitnessTable vat = WitnessTable.ValueWitnessTable; + return vat != null ? (int)vat.Stride : 0; + } + } + } + +} + diff --git a/src/SwiftReflector/Inventory/ClassInventory.cs b/src/SwiftReflector/Inventory/ClassInventory.cs new file mode 100644 index 000000000000..588ce06260b3 --- /dev/null +++ b/src/SwiftReflector/Inventory/ClassInventory.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class ClassInventory : Inventory { + int sizeofMachinePointer; + public ClassInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public override void Add (TLDefinition tld, Stream srcStm) + { + // ignoring these - we don't/can't use them + if (tld is TLDefaultArgumentInitializer) + return; + SwiftName className = ToClassName (tld); + SwiftClassName formalName = ToFormalClassName (tld); + lock (valuesLock) { + ClassContents contents = null; + if (!values.TryGetValue (className, out contents)) { + contents = new ClassContents (formalName, sizeofMachinePointer); + values.Add (className, contents); + } + contents.Add (tld, srcStm); + } + } + + public static SwiftClassName ToFormalClassName (TLDefinition tld) + { + TLClassElem elem = tld as TLClassElem; + if (elem != null) { + if (elem.Class == null) + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 2, $"Expected a top level definition to have a class name."); + return elem.Class.ClassName; + } + if (tld is TLProtocolConformanceDescriptor protocolDesc) { + if (protocolDesc.ImplementingType is SwiftClassType swiftClass) + return swiftClass.ClassName; + if (protocolDesc.ImplementingType is SwiftBoundGenericType boundGen) { + var baseType = boundGen.BaseType as SwiftClassType; + if (baseType != null) + return baseType.ClassName; + } else if (protocolDesc.ImplementingType is SwiftBuiltInType builtInType) { + return SwiftClassName.FromFullyQualifiedName ($"Swift.{builtInType.BuiltInType}", OperatorType.None, "V"); + } + } + + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 0, $"unknown top level definition {tld.GetType ().Name}"); + } + + public static SwiftName ToClassName (TLDefinition tld) + { + SwiftClassName cln = ToFormalClassName (tld); + return new SwiftName (cln.ToFullyQualifiedName (), false); + } + } + +} + diff --git a/src/SwiftReflector/Inventory/FunctionInventory.cs b/src/SwiftReflector/Inventory/FunctionInventory.cs new file mode 100644 index 000000000000..129d57f6a087 --- /dev/null +++ b/src/SwiftReflector/Inventory/FunctionInventory.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class FunctionInventory : Inventory { + int sizeofMachinePointer; + public FunctionInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + public override void Add (TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 10, $"expected a top-level function but got a {tld.GetType ().Name}"); + + lock (valuesLock) { + OverloadInventory overloads = null; + if (!values.TryGetValue (tlf.Name, out overloads)) { + overloads = new OverloadInventory (tlf.Name, sizeofMachinePointer); + values.Add (tlf.Name, overloads); + } + overloads.Add (tlf, srcStm); + } + } + + public TLFunction ContainsEquivalentFunction (TLFunction func) + { + // for finding a func with the same name and signature which may or may not be a thunk + var nameMatched = MethodsWithName (func.Signature.Name); + if (nameMatched.Count == 0) + return null; + foreach (var candidate in nameMatched) { + if (ArgumentsMatch (candidate, func) && ReturnsMatch (candidate, func) && candidate.Signature.CanThrow == func.Signature.CanThrow) + return candidate; + } + return null; + } + + public void ReplaceFunction (TLFunction original, TLFunction replacement) + { + var overloads = values [original.Name]; + if (overloads == null) + throw new ArgumentException ("original function name must be in the inventory"); + if (!overloads.Functions.Remove (original)) + throw new ArgumentException ("original function not found"); + overloads.Functions.Add (replacement); + } + + static bool ArgumentsMatch (TLFunction candidate, TLFunction func) + { + if (candidate.Signature.ParameterCount != func.Signature.ParameterCount) + return false; + + for (int i = 0; i < candidate.Signature.ParameterCount; i++) { + if (!candidate.Signature.GetParameter (i).Equals (func.Signature.GetParameter (i))) + return false; + } + return true; + } + + static bool ReturnsMatch (TLFunction candidate, TLFunction func) + { + return candidate.Signature.ReturnType.Equals (func.Signature.ReturnType); + } + + public IEnumerable> AllMethodsNoCDTor () + { + foreach (SwiftName key in values.Keys) { + OverloadInventory oi = values [key]; + foreach (TLFunction tlf in oi.Functions) + yield return new Tuple (key, tlf); + } + } + + public List MethodsWithName (SwiftName name) + { + var result = new List (); + foreach (var oi in Values) { + if (oi.Name.Name == name.Name) + result.AddRange (oi.Functions); + } + return result; + } + + public List MethodsWithName (string name) + { + SwiftName sn = new SwiftName (name, false); + return MethodsWithName (sn); + } + + public List AllocatingConstructors () + { + return MethodsWithName (Decomposer.kSwiftAllocatingConstructorName); + } + + public List DeallocatingDestructors () + { + return MethodsWithName (Decomposer.kSwiftDeallocatingDestructorName); + } + } + +} + diff --git a/src/SwiftReflector/Inventory/Inventory.cs b/src/SwiftReflector/Inventory/Inventory.cs new file mode 100644 index 000000000000..cc75f6f82f74 --- /dev/null +++ b/src/SwiftReflector/Inventory/Inventory.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using SwiftReflector.Demangling; + + +namespace SwiftReflector.Inventory { + public abstract class Inventory { + protected object valuesLock = new object (); + protected Dictionary values = new Dictionary (); + + public IEnumerable Names { get { return values.Keys; } } + public IEnumerable Values { get { return values.Values; } } + + public abstract void Add (TLDefinition tlf, Stream srcStm); + + public bool ContainsName (SwiftName name) + { + lock (valuesLock) { + return values.ContainsKey (name); + } + } + public bool ContainsName (string name) + { + return ContainsName (new SwiftName (name, false)); + } + + public bool TryGetValue (SwiftName name, out T value) + { + lock (valuesLock) { + return values.TryGetValue (name, out value); + } + } + + public bool TryGetValue (string name, out T value) + { + return TryGetValue (new SwiftName (name, false), out value); + } + } +} + diff --git a/src/SwiftReflector/Inventory/ModuleContents.cs b/src/SwiftReflector/Inventory/ModuleContents.cs new file mode 100644 index 000000000000..172fb3c7e19b --- /dev/null +++ b/src/SwiftReflector/Inventory/ModuleContents.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using SwiftReflector.Demangling; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Inventory { + public class ModuleContents { + public ModuleContents (SwiftName name, int sizeofMachinePointer) + { + Name = Exceptions.ThrowOnNull (name, nameof(name)); + Classes = new ClassInventory (sizeofMachinePointer); + Functions = new FunctionInventory (sizeofMachinePointer); + Variables = new VariableInventory (sizeofMachinePointer); + WitnessTables = new WitnessInventory (sizeofMachinePointer); + Protocols = new ProtocolInventory (sizeofMachinePointer); + Extensions = new FunctionInventory (sizeofMachinePointer); + MetadataFieldDescriptor = new List (); + MetadataBuiltInDescriptor = new List (); + PropertyDescriptors = new VariableInventory (sizeofMachinePointer); + ExtensionDescriptors = new List (); + } + + public void Add (TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) { + if (tlf.Signature.IsExtension) { + Extensions.Add (tlf, srcStm); + } else if (tlf.IsTopLevelFunction) { + if (tlf.Signature is SwiftAddressorType) { + Variables.Add (tlf, srcStm); + } else if (tlf.Signature is SwiftWitnessTableType) { + WitnessTables.Add (tld, srcStm); + } else { + Functions.Add (tlf, srcStm); + } + } else { + if (tlf.Class.EntityKind == MemberNesting.Protocol) { + Protocols.Add (tlf, srcStm); + } else { + Classes.Add (tld, srcStm); + } + } + } else { + if (tld is TLVariable tlvar && ((TLVariable)tld).Class == null) { + if (tlvar is TLPropertyDescriptor propDesc) { + if (propDesc.ExtensionOn != null) + ExtensionDescriptors.Add (propDesc); + else + PropertyDescriptors.Add (tlvar, srcStm); + } else { + Variables.Add (tld, srcStm); + } + } else if (tld is TLProtocolTypeDescriptor || tld is TLProtocolRequirementsBaseDescriptor) { + Protocols.Add (tld, srcStm); + } else if (tld is TLModuleDescriptor module) { + ModuleDescriptor = module; + } else if (tld is TLMetadataDescriptor metadata) { + if (metadata.IsBuiltIn) + MetadataBuiltInDescriptor.Add (metadata); + else + MetadataFieldDescriptor.Add (metadata); + } else { + // global unsafe mutable addressors get ignored. We don't need/use them. + if (tld is TLUnsafeMutableAddressor addressor && addressor.Class == null) + return; + Classes.Add (tld, srcStm); + } + } + } + + public TLModuleDescriptor ModuleDescriptor { get; private set; } + public SwiftName Name { get; private set; } + + public WitnessInventory WitnessTables { get; private set; } + public ProtocolInventory Protocols { get; private set; } + public ClassInventory Classes { get; private set; } + public FunctionInventory Functions { get; private set; } + public VariableInventory Variables { get; private set; } + public VariableInventory PropertyDescriptors { get; private set; } + public List ExtensionDescriptors { get; private set; } + public FunctionInventory Extensions { get; private set; } + public List MetadataFieldDescriptor { get; private set; } + public List MetadataBuiltInDescriptor { get; private set; } + } + +} + diff --git a/src/SwiftReflector/Inventory/ModuleInventory.cs b/src/SwiftReflector/Inventory/ModuleInventory.cs new file mode 100644 index 000000000000..2362ba80603a --- /dev/null +++ b/src/SwiftReflector/Inventory/ModuleInventory.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; +using System.IO; +using SwiftReflector.ExceptionTools; +using SwiftReflector.IOUtils; +using SwiftReflector.Demangling; +using Xamarin; +using SwiftRuntimeLibrary; +using System.Threading.Tasks; + +namespace SwiftReflector.Inventory { + public class ModuleInventory : Inventory { + public MachO.Architectures Architecture { get; private set; } + public int SizeofMachinePointer { + get { + return Architecture == MachO.Architectures.x86_64 || + Architecture == MachO.Architectures.ARM64 ? 8 : 4; + } + } + + public override void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + ModuleContents module = null; + if (!values.TryGetValue (tld.Module, out module)) { + module = new ModuleContents (tld.Module, SizeofMachinePointer); + values.Add (tld.Module, module); + } + module.Add (tld, srcStm); + } + } + + public static ModuleInventory FromFile (string pathToDynamicLibrary, ErrorHandling errors) + { + Exceptions.ThrowOnNull (pathToDynamicLibrary, nameof(pathToDynamicLibrary)); + FileStream stm = null; + try { + stm = new FileStream (pathToDynamicLibrary, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + } catch (Exception e) { + Console.WriteLine (e.Message); + errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 57, e, "unable to open file {0}: {1}\n", pathToDynamicLibrary, e.Message)); + } + try { + return FromStream (stm, errors, pathToDynamicLibrary); + } finally { + stm.Dispose (); + } + } + + public static async Task FromFilesAsync (IEnumerable pathsToLibraryFiles, ErrorHandling errors) + { + var streams = pathsToLibraryFiles.Select (path => new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)).ToList (); + if (streams.Count == 0) + return null; + var inventory = new ModuleInventory (); + try { + var tasks = streams.Select (stm => FromStreamIntoAsync (stm, inventory, errors, stm.Name)); + await Task.WhenAll (tasks); + } finally { + foreach (var stm in streams) { + stm.Dispose (); + } + } + return inventory; + } + + public static ModuleInventory FromFiles (IEnumerable pathsToLibraryFiles, ErrorHandling errors) + { + ModuleInventory inventory = null; + foreach (string path in pathsToLibraryFiles) { + if (inventory == null) + inventory = new ModuleInventory (); + using (FileStream stm = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)) { + FromStreamInto (stm, inventory, errors, path); + } + } + return inventory; + } + + static async Task FromStreamIntoAsync (Stream stm, ModuleInventory inventory, + ErrorHandling errors, string fileName = null) + { + return await Task.Run (() => { + return FromStreamInto (stm, inventory, errors, fileName); + }); + } + + static ModuleInventory FromStreamInto (Stream stm, ModuleInventory inventory, + ErrorHandling errors, string fileName = null) + { + // Exceptions.ThrowOnNull (errors, "errors"); + Exceptions.ThrowOnNull (stm, "stm"); + OffsetStream osstm = null; + List entries = null; + try { + List macho = MachO.Read (stm, null).ToList (); + MachOFile file = macho [0]; + + List symbols = file.load_commands.OfType ().ToList (); + NListEntryType nlet = symbols [0].nlist [0].EntryType; + entries = symbols [0].nlist. + Where ((nle, i) => nle.IsPublic && nle.EntryType == NListEntryType.InSection).ToList (); + inventory.Architecture = file.Architecture; + osstm = new OffsetStream (stm, file.StartOffset); + } catch (Exception e) { + errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 58, e, "Unable to retrieve functions from {0}: {1}", + fileName ?? "stream", e.Message)); + return inventory; + } + + bool isOldVersion = IsOldVersion (entries); + + foreach (var entry in entries) { + if (!entry.IsSwiftEntryPoint ()) + continue; + TLDefinition def = null; + def = Decomposer.Decompose (entry.str, isOldVersion, Offset (entry)); + if (def != null) { + // this skips over privatized names + var tlf = def as TLFunction; + if (tlf != null && tlf.Name != null && tlf.Name.Name.Contains ("...")) + continue; + try { + inventory.Add (def, osstm); + } catch (RuntimeException e) { + e = new RuntimeException (e.Code, e.Error, $"error dispensing top level definition of type {def.GetType ().Name} decomposed from {entry.str}: {e.Message}"); + errors.Add (e); + } + } else { + var ex = ErrorHelper.CreateWarning (ReflectorError.kInventoryBase + 18, $"entry {entry.str} uses an unsupported swift feature, skipping."); + errors.Add (ex); + } + } + + return inventory; + } + + public static ModuleInventory FromStream (Stream stm, ErrorHandling errors, string fileName = null) + { + ModuleInventory inventory = new ModuleInventory (); + return FromStreamInto (stm, inventory, errors, fileName); + } + + static ulong Offset (NListEntry entry) + { + NListEntry32 nl32 = entry as NListEntry32; + return nl32 != null ? nl32.n_value : ((NListEntry64)entry).n_value; + } + + static bool IsOldVersion (List entries) + { + foreach (NListEntry entry in entries) { + if (entry.str.StartsWith ("__TMd", StringComparison.Ordinal)) + return true; + } + return false; + } + } +} + diff --git a/src/SwiftReflector/Inventory/OverloadInventory.cs b/src/SwiftReflector/Inventory/OverloadInventory.cs new file mode 100644 index 000000000000..addf401bb00e --- /dev/null +++ b/src/SwiftReflector/Inventory/OverloadInventory.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using SwiftReflector.ExceptionTools; +using System.IO; +using SwiftReflector.Demangling; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Inventory { + public class OverloadInventory : Inventory> { + int sizeofMachinePointer; + public OverloadInventory (SwiftName name, int sizeofMachinePointer) + { + Name = Exceptions.ThrowOnNull (name, nameof(name)); + Functions = new List (); + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public override void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 11, $"expected a top-level function but got a {tld.GetType ().Name}"); + if (Functions.Exists (f => tlf.MangledName == f.MangledName)) { + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 12, $"duplicate function found for {tlf.MangledName}"); + } else { + Functions.Add (tlf); + } + } + } + + public List Functions { get; private set; } + + public SwiftName Name { get; private set; } + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } + +} + diff --git a/src/SwiftReflector/Inventory/PropertyContents.cs b/src/SwiftReflector/Inventory/PropertyContents.cs new file mode 100644 index 000000000000..dd5909510655 --- /dev/null +++ b/src/SwiftReflector/Inventory/PropertyContents.cs @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using SwiftReflector.Demangling; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.Inventory { + public class PropertyContents { + int sizeofMachinePointer; + public PropertyContents (SwiftClassType ofClass, SwiftName propName, int sizeofMachinePointer) + { + Class = Exceptions.ThrowOnNull (ofClass, nameof(ofClass)); + Name = Exceptions.ThrowOnNull (propName, nameof(propName)); + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public SwiftClassType Class { get; private set; } + + public SwiftName Name { get; private set; } + + public void Add (TLFunction tlf, SwiftPropertyType prop) + { + var method = tlf as TLMethodDescriptor; + if (method != null) { + switch (prop.PropertyType) { + case PropertyType.Getter: + TLFGetterDescriptor = method; + break; + case PropertyType.Setter: + TLFSetterDescriptor = method; + break; + case PropertyType.Materializer: + TLFMaterializerDescriptor = method; + break; + case PropertyType.DidSet: + TLFDidSetDescriptor = method; + break; + case PropertyType.WillSet: + TLFWillSetDescriptor = method; + break; + case PropertyType.ModifyAccessor: + TLFModifyDescriptor = method; + break; + default: + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 68, $"Unexpected property descriptor {prop.PropertyType.ToString ()}"); + } + } else { + switch (prop.PropertyType) { + case PropertyType.Getter: + var oldget = Getter; + Getter = ConditionalChainThunk (prop, oldget); + TLFGetter = oldget == null || Getter != prop ? tlf : TLFGetter; + break; + case PropertyType.Setter: + var oldset = Setter; + Setter = ConditionalChainThunk (prop, oldset); + TLFSetter = oldset == null || Setter != prop ? tlf : TLFSetter; + break; + case PropertyType.Materializer: + var oldmaterialize = Materializer; + Materializer = ConditionalChainThunk (prop, oldmaterialize); + TLFMaterializer = oldmaterialize == null || Materializer != prop ? tlf : TLFMaterializer; + break; + case PropertyType.DidSet: + var olddidset = DidSet; + DidSet = ConditionalChainThunk (prop, olddidset); + TLFDidSet = olddidset == null || DidSet != prop ? tlf : TLFDidSet; + break; + case PropertyType.WillSet: + var oldwillset = WillSet; + WillSet = ConditionalChainThunk (prop, oldwillset); + TLFWillSet = oldwillset == null || WillSet != prop ? tlf : TLFWillSet; + break; + case PropertyType.ModifyAccessor: + var oldmodify = WillSet; + ModifyAccessor = ConditionalChainThunk (prop, oldmodify); + TLFModifyAccessor = oldmodify == null || ModifyAccessor != prop ? tlf : TLFModifyAccessor; + break; + default: + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 2, $"Unexpected property element {prop.PropertyType.ToString ()}"); + } + } + } + + static SwiftPropertyType ConditionalChainThunk (SwiftPropertyType newProp, SwiftPropertyType oldProp) + { + if (oldProp == null) { + return newProp; + } + if (oldProp.IsThunk) { + newProp.Thunk = oldProp; + return newProp; + } else if (newProp.IsThunk) { + oldProp.Thunk = newProp; + return oldProp; + } else { + throw new NotImplementedException ("At least one needs to be a thunk - should never happen"); + } + } + + SwiftPropertyType getter; + public SwiftPropertyType Getter { + get { + return getter; + } + set { + ThrowOnExistingProperty (getter, "getter"); + getter = value; + } + } + public TLFunction TLFGetter { get; set; } + public TLMethodDescriptor TLFGetterDescriptor { get; set; } + + SwiftPropertyType setter; + public SwiftPropertyType Setter { + get { + return setter; + } + set { + ThrowOnExistingProperty (setter, "setter"); + setter = value; + } + } + public TLFunction TLFSetter { get; set; } + public TLMethodDescriptor TLFSetterDescriptor { get; set; } + + SwiftPropertyType materializer; + public SwiftPropertyType Materializer { + get { + return materializer; + } + set { + ThrowOnExistingProperty (materializer, "materializer"); + materializer = value; + } + } + public TLFunction TLFMaterializer { get; set; } + public TLMethodDescriptor TLFMaterializerDescriptor { get; set; } + + SwiftPropertyType modifyAccessor; + public SwiftPropertyType ModifyAccessor { + get { return modifyAccessor; } + set { + ThrowOnExistingProperty (modifyAccessor, "modifyAccessor"); + modifyAccessor = value; + } + } + public TLFunction TLFModifyAccessor { get; set; } + public TLMethodDescriptor TLFModifyDescriptor { get; set; } + + SwiftPropertyType didSet; + public SwiftPropertyType DidSet { + get { + return didSet; + } + set { + ThrowOnExistingProperty (didSet, "did set"); + didSet = value; + } + } + public TLFunction TLFDidSet { get; set; } + public TLMethodDescriptor TLFDidSetDescriptor { get; set; } + + SwiftPropertyType willSet; + public SwiftPropertyType WillSet { + get { + return willSet; + } + set { + ThrowOnExistingProperty (willSet, "will set"); + willSet = value; + } + } + public TLFunction TLFWillSet { get; set; } + public TLMethodDescriptor TLFWillSetDescriptor { get; set; } + + void ThrowOnExistingProperty (SwiftPropertyType prop, string propType) + { + if (prop != null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 6, $"Already have a {propType} entry for property {Name} in {Class.ClassName.ToFullyQualifiedName ()}"); + } + + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } + +} + diff --git a/src/SwiftReflector/Inventory/PropertyInventory.cs b/src/SwiftReflector/Inventory/PropertyInventory.cs new file mode 100644 index 000000000000..509d5b0cceee --- /dev/null +++ b/src/SwiftReflector/Inventory/PropertyInventory.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class PropertyInventory : Inventory { + int sizeofMachinePointer; + public PropertyInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public override void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 7, $"Expected a TLFunction for a property but got a {tld.GetType ().Name}."); + + SwiftPropertyType prop = tlf.Signature as SwiftPropertyType; + if (prop == null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 8, $"Expected a function of property type but got a {tlf.Signature.GetType ().Name}."); + + PropertyContents contents = null; + SwiftName nameToUse = prop.PrivateName ?? prop.Name; + if (!values.TryGetValue (nameToUse, out contents)) { + contents = new PropertyContents (tlf.Class, nameToUse, sizeofMachinePointer); + values.Add (nameToUse, contents); + } + contents.Add (tlf, prop); + } + } + + public PropertyContents PropertyWithName (SwiftName name) + { + PropertyContents pc = Values.Where (oi => oi.Name.Equals (name)).FirstOrDefault (); + return pc; + } + + public PropertyContents PropertyWithName (string name) + { + SwiftName sn = new SwiftName (name, false); + return PropertyWithName (sn); + } + + } +} + diff --git a/src/SwiftReflector/Inventory/ProtocolContents.cs b/src/SwiftReflector/Inventory/ProtocolContents.cs new file mode 100644 index 000000000000..734a18b14868 --- /dev/null +++ b/src/SwiftReflector/Inventory/ProtocolContents.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Collections.Generic; +using SwiftReflector.ExceptionTools; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class ProtocolContents { + int sizeofMachinePointer; + public ProtocolContents (SwiftClassName className, int sizeofMachiinePointer) + { + this.sizeofMachinePointer = sizeofMachiinePointer; + WitnessTable = new WitnessInventory (sizeofMachinePointer); + FunctionsOfUnknownDestination = new List (); + DefinitionsOfUnknownDestination = new List (); + BaseDescriptors = new List (); + BaseConformanceDescriptors = new List (); + Name = className; + + } + + public TLMetaclass Metaclass { get; private set; } + public TLDirectMetadata DirectMetadata { get; private set; } + public TLProtocolTypeDescriptor TypeDescriptor { get; private set; } + public WitnessInventory WitnessTable { get; private set; } + public List FunctionsOfUnknownDestination { get; private set; } + public List DefinitionsOfUnknownDestination { get; private set; } + public List BaseDescriptors { get; private set; } + public List BaseConformanceDescriptors { get; private set; } + public SwiftClassName Name { get; private set; } + + public void Add (TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) { + if (ClassContents.IsWitnessTable (tlf.Signature, tlf.Class)) { + WitnessTable.Add (tlf, srcStm); + } + FunctionsOfUnknownDestination.Add (tlf); + return; + } + + TLDirectMetadata meta = tld as TLDirectMetadata; + if (meta != null) { + if (DirectMetadata != null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 1, $"duplicate direct metadata in protocol {DirectMetadata.Class.ClassName.ToFullyQualifiedName ()}"); + DirectMetadata = meta; + return; + } + TLMetaclass mc = tld as TLMetaclass; + if (mc != null) { + if (Metaclass != null) { + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 2, $"duplicate type meta data descriptor in protocol {Metaclass.Class.ClassName.ToFullyQualifiedName ()}"); + } + Metaclass = mc; + return; + } + + TLProtocolTypeDescriptor ptd = tld as TLProtocolTypeDescriptor; + if (ptd != null) { + if (TypeDescriptor != null) { + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 3, $"duplicate protocol type descriptor in protocol {TypeDescriptor.Class.ClassName.ToFullyQualifiedName ()}"); + } + TypeDescriptor = ptd; + return; + } + + if (tld is TLProtocolRequirementsBaseDescriptor baseDescriptor) { + BaseDescriptors.Add (baseDescriptor); + return; + } + + if (tld is TLBaseConformanceDescriptor baseConformanceDescriptor) { + BaseConformanceDescriptors.Add (baseConformanceDescriptor); + return; + } + + DefinitionsOfUnknownDestination.Add (tld); + } + } +} + diff --git a/src/SwiftReflector/Inventory/ProtocolInventory.cs b/src/SwiftReflector/Inventory/ProtocolInventory.cs new file mode 100644 index 000000000000..8ce239658f7b --- /dev/null +++ b/src/SwiftReflector/Inventory/ProtocolInventory.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class ProtocolInventory : Inventory { + int sizeofMachinePointer; + public ProtocolInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public override void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + SwiftName className = ClassInventory.ToClassName (tld); + SwiftClassName formalName = ClassInventory.ToFormalClassName (tld); + ProtocolContents contents = null; + if (!values.TryGetValue (className, out contents)) { + contents = new ProtocolContents (formalName, sizeofMachinePointer); + values.Add (className, contents); + } + contents.Add (tld, srcStm); + } + } + } +} + diff --git a/src/SwiftReflector/Inventory/VariableContents.cs b/src/SwiftReflector/Inventory/VariableContents.cs new file mode 100644 index 000000000000..bff5e56dc595 --- /dev/null +++ b/src/SwiftReflector/Inventory/VariableContents.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class VariableContents { + int sizeofMachinePointer; + public VariableContents (SwiftName name, int sizeofMachinePointer) + { + Name = name; + Addressors = new List (); + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public TLVariable Variable { get; set; } + public List Addressors { get; private set; } + public SwiftName Name { get; private set; } + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } +} + diff --git a/src/SwiftReflector/Inventory/VariableInventory.cs b/src/SwiftReflector/Inventory/VariableInventory.cs new file mode 100644 index 000000000000..8a6595e10fe0 --- /dev/null +++ b/src/SwiftReflector/Inventory/VariableInventory.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class VariableInventory : Inventory { + int sizeofMachinePointer; + public VariableInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + public override void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + TLVariable vari = tld as TLVariable; + if (vari != null) { + VariableContents contents = GoGetIt (vari.Name); + if (contents.Variable != null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 4, $"duplicate variable {vari.Name.Name}."); + contents.Variable = vari; + return; + } + + TLFunction tlf = tld as TLFunction; + if (tlf != null) { + VariableContents contents = GoGetIt (tlf.Name); + contents.Addressors.Add (tlf); + return; + } + + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 5, $"expected a top-level function or top-level variable but got a {tld.GetType ().Name}"); + } + + } + + VariableContents GoGetIt (SwiftName name) + { + VariableContents vari = null; + if (!values.TryGetValue (name, out vari)) { + vari = new VariableContents (name, sizeofMachinePointer); + values.Add (name, vari); + } + return vari; + } + } +} + diff --git a/src/SwiftReflector/Inventory/WitnessInventory.cs b/src/SwiftReflector/Inventory/WitnessInventory.cs new file mode 100644 index 000000000000..f4cf7ac564f9 --- /dev/null +++ b/src/SwiftReflector/Inventory/WitnessInventory.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using SwiftReflector.Demangling; + +namespace SwiftReflector.Inventory { + public class WitnessInventory { + object valuesLock = new object (); + Dictionary values = new Dictionary (); + int sizeofMachinePointer; + + public WitnessInventory (int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public void Add (TLDefinition tld, Stream srcStm) + { + lock (valuesLock) { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 9, $"Expected a TLFunction for a witness table but got a {tld.GetType ().Name}."); + + if (values.ContainsKey (tlf.MangledName)) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 10, $"Already received witness table entry for {tlf.MangledName}."); + values.Add (tlf.MangledName, tlf); + LoadWitnessTable (tlf, srcStm); + } + } + + public IEnumerable MangledNames { get { return values.Keys; } } + public IEnumerable Functions { get { return values.Values; } } + public IEnumerable WitnessEntriesOfType (WitnessType wit) + { + return Functions.Where (fn => (fn.Signature is SwiftWitnessTableType) && ((SwiftWitnessTableType)fn.Signature).WitnessType == wit); + } + + public ValueWitnessTable ValueWitnessTable { get; private set; } + + void LoadWitnessTable (TLFunction tlf, Stream stm) + { + WitnessType type = FromTLF (tlf); + switch (type) { + case WitnessType.Value: + ValueWitnessTable = ValueWitnessTable.FromStream (stm, tlf, sizeofMachinePointer); + break; + default: + break; + } + } + + WitnessType FromTLF (TLFunction tlf) + { + SwiftWitnessTableType wit = tlf.Signature as SwiftWitnessTableType; + if (wit == null) + throw new ArgumentException ("tlf"); + return wit.WitnessType; + } + } + +} + diff --git a/src/SwiftReflector/MachOHawley.cs b/src/SwiftReflector/MachOHawley.cs new file mode 100644 index 000000000000..6581f647374f --- /dev/null +++ b/src/SwiftReflector/MachOHawley.cs @@ -0,0 +1,1339 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; +using System.Linq; +using System.Collections; + +#if MTOUCH +using MonoTouch; +#endif + +namespace Xamarin { + public class MachO { + /* definitions from: /usr/include/mach-o/loader.h */ + /* Constant for the magic field of the mach_header (32-bit architectures) */ + internal const uint MH_MAGIC = 0xfeedface; /* the mach magic number */ + internal const uint MH_CIGAM = 0xcefaedfe; /* NXSwapInt(MH_MAGIC) */ + + /* Constant for the magic field of the mach_header_64 (64-bit architectures) */ + internal const uint MH_MAGIC_64 = 0xfeedfacf; /* the 64-bit mach magic number */ + internal const uint MH_CIGAM_64 = 0xcffaedfe; /* NXSwapInt(MH_MAGIC_64) */ + + /* definitions from: /usr/include/mach-o/fat.h */ + internal const uint FAT_MAGIC = 0xcafebabe; + internal const uint FAT_CIGAM = 0xbebafeca; /* NXSwapLong(FAT_MAGIC) */ + + public enum Architectures { + None = 0, + i386 = 1, + ARMv6 = 2, + ARMv7 = 4, + ARMv7s = 8, + ARM64 = 16, + x86_64 = 32, + ARM64e = 64, + ARM64_32 = 128, + } + + public enum LoadCommands : uint { + //#define LC_REQ_DYLD 0x80000000 + ReqDyld = 0x80000000, + // + // /* Constants for the cmd field of all load commands, the type */ + //#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ + Segment = 0x1, + //#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ + SymTab = 0x2, + //#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ + SymSeg = 0x3, + //#define LC_THREAD 0x4 /* thread */ + Thread = 0x4, + //#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ + UnixThread = 0x5, + //#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */ + LoadFVMLib = 0x6, + //#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */ + IDFVMLib = 0x7, + //#define LC_IDENT 0x8 /* object identification info (obsolete) */ + Ident = 0x8, + //#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */ + FVMFile = 0x9, + //#define LC_PREPAGE 0xa /* prepage command (internal use) */ + Prepage = 0xa, + //#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */ + DySymTab = 0x0b, + + //#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */ + LoadDylib = 0xc, + //#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */ + IdDylib = 0xd, + //#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */ + LoadDylinker = 0xe, + //#define LC_ID_DYLINKER 0xf /* dynamic linker identification */ + IdDylinker = 0xf, + //#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */ + PreboundDylib = 0x10, + // /* linked shared library */ + //#define LC_ROUTINES 0x11 /* image routines */ + Routines = 0x11, + //#define LC_SUB_FRAMEWORK 0x12 /* sub framework */ + SubFramework = 0x12, + //#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */ + SubUmbrella = 0x13, + //#define LC_SUB_CLIENT 0x14 /* sub client */ + SubClient = 0x14, + //#define LC_SUB_LIBRARY 0x15 /* sub library */ + SubLibrary = 0x15, + //#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */ + TwolevelHints = 0x16, + //#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */ + PrebindChecksum = 0x17, + // + // /* + // * load a dynamically linked shared library that is allowed to be missing + // * (all symbols are weak imported). + // */ + //#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD) + LoadWeakDylib = 0x18 | ReqDyld, + // + //#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be + Segment64 = 0x19, + // mapped */ + //#define LC_ROUTINES_64 0x1a /* 64-bit image routines */ + Routines64 = 0x1a, + //#define LC_UUID 0x1b /* the uuid */ + Uuid = 0x1b, + //#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */ + RPath = 0x1c | ReqDyld, + //#define LC_CODE_SIGNATURE 0x1d /* local of code signature */ + CodeSignature = 0x1d, + //#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */ + SegmentSplitInfo = 0x1e, + //#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */ + ReexportDylib = 0x1f | ReqDyld, + //#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */ + LazyLoadDylib = 0x20, + //#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */ + EncryptionInfo = 0x21, + //#define LC_DYLD_INFO 0x22 /* compressed dyld information */ + DyldInfo = 0x22, + //#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ + DyldInfoOnly = 0x22 | ReqDyld, + //#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */ + LoadUpwardDylib = 0x23 | ReqDyld, + //#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */ + VersionMinMacOS = 0x24, + //#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */ + VersionMinIPhoneOS = 0x25, + //#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */ + FunctionStarts = 0x26, + //#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat + DyldEnvironment = 0x27, + // like environment variable */ + //#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */ + Main = 0x28 | ReqDyld, + //#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */ + DataInCode = 0x29, + //#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */ + SourceVersion = 0x2a, + //#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */ + DylibCodeSignDrs = 0x2b, + //#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */ + EncryptionInfo64 = 0x2c, + //#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */ + VersionMinTVOS = 0x2f, + //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ + VersionMinWatchOS = 0x30, + //#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */ + Note = 0x31, + //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ + BuildVersion = 0x32, + //#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */ + DyldExportsTrie = 0x33 | ReqDyld, + //#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */ + DyldChainedFixups = 0x34 | ReqDyld, + } + + public enum Platform : uint { + MacOS = 1, + IOS = 2, + TvOS = 3, + WatchOS = 4, + BridgeOS = 5, + IOSSimulator = 7, + TvOSSimulator = 8, + WatchOSSimulator = 9, + } + + internal static uint FromBigEndian (uint number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static int FromBigEndian (int number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static uint ToBigEndian (uint number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static int ToBigEndian (int number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + static IDisposable ReadFile (ReaderParameters parameters) + { + var reader = parameters.Reader; + var magic = reader.ReadUInt32 (); + reader.BaseStream.Position = 0; + switch (magic) { + case MH_MAGIC: + case MH_MAGIC_64: + var mf = new MachOFile (parameters); + mf.Read (); + return mf; + case FAT_MAGIC: // little-endian fat binary + case FAT_CIGAM: // big-endian fat binary + { + var f = new FatFile (parameters); + f.Read (); + return f; + } + default: + throw new Exception (string.Format ("File format not recognized: {0} (magic: 0x{1})", parameters.Filename ?? "(no file name available)", magic.ToString ("X"))); + } + } + + public static MachOFileCollection Read (string filename, ReadingMode mode) + { + var parameters = new ReaderParameters (); + parameters.Filename = filename; + parameters.ReadingMode = mode; + parameters.Reader = new BinaryReader (new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8, false); + try { + return GetMachOFiles (parameters, ReadFile (parameters)); + } finally { + if (mode == ReadingMode.Immediate) + parameters.Dispose (); + } + } + + static MachOFileCollection GetMachOFiles (ReaderParameters parameters, IDisposable readOutput) + { + var rv = new MachOFileCollection (parameters); + if (readOutput is FatFile fatfile) { + foreach (var ff in fatfile.entries) + rv.Add (ff.entry); + } else { + rv.Add ((MachOFile) readOutput); + } + return rv; + } + + public static IEnumerable Read (Stream stm, string filename = null) + { + if (stm == null) + throw new ArgumentNullException (nameof (stm)); + using (var parameters = new ReaderParameters ()) { + parameters.ReadingMode = ReadingMode.Immediate; + parameters.Reader = new BinaryReader (stm, Encoding.UTF8, true); + parameters.Filename = filename; + return GetMachOFiles (parameters, ReadFile (parameters)); + } + } + + public static bool IsMachoFile (string filename) + { + using (FileStream stm = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { + return IsMachoFile (stm); + } + } + + public static bool IsMachoFile (Stream stm) + { + using (var reader = new BinaryReader (stm, UTF8Encoding.UTF8, true)) { + var magic = reader.ReadUInt32 (); + reader.BaseStream.Position = 0; + switch (magic) { + case MH_MAGIC: + case MH_MAGIC_64: + case FAT_MAGIC: // little-endian fat binary + case FAT_CIGAM: // big-endian fat binary + return true; + default: + return false; + } + } + } + + + +#if MTOUCH + // Removes all architectures from the target file, except for those in 'architectures'. + // This method doesn't do anything if the target file is a thin mach-o file. + // Also it doesn't do anything if the result is an empty file (i.e. none of the + // selected architectures match any of the architectures in the file) - this is + // only because I haven't investigated what would be needed elsewhere in the link + // process when the entire file is removed. FIXME <--. + public static void SelectArchitectures (string filename, ICollection abis) + { + var architectures = GetArchitectures (abis); + var tmpfile = filename + ".tmp"; + + if (abis.Count == 0) + return; + + using (var fsr = new FileStream (filename, FileMode.Open, FileAccess.Read)) { + using (var reader = new BinaryReader (fsr)) { + var file = ReadFile (filename); + if (file is MachOFile) { + MTouch.Log (2, "Skipping architecture selecting of '{0}', since it only contains 1 architecture.", filename); + return; + } + + var fatfile = (FatFile) file; + bool any_removed = false; + + // remove architectures we don't want + for (int i = fatfile.entries.Count - 1; i >= 0; i--) { + var ff = fatfile.entries [i]; + if (!architectures.Contains (ff.entry.Architecture)) { + any_removed = true; + fatfile.entries.RemoveAt (i); + fatfile.nfat_arch--; + MTouch.Log (2, "Removing architecture {0} from {1}", ff.entry.Architecture, filename); + } + } + + if (!any_removed) { + MTouch.Log (2, "Architecture selection of '{0}' didn't find any architectures to remove.", filename); + return; + } + + if (fatfile.nfat_arch == 0) { + MTouch.Log (2, "Skipping architecture selection of '{0}', none of the selected architectures match any of the architectures in the archive.", filename, architectures [0]); + return; + } + + if (fatfile.nfat_arch == 1) { + // Thin file + var entry = fatfile.entries [0]; + using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { + using (var writer = new BinaryWriter (fsw)) { + entry.WriteFile (writer, reader, entry.offset); + } + } + } else { + // Fat file + // Re-calculate header data + var read_offset = new List (fatfile.entries.Count); + read_offset.Add (fatfile.entries [0].offset); + fatfile.entries [0].offset = (uint) (1 << (int) fatfile.entries [0].align); + for (int i = 1; i < fatfile.entries.Count; i++) { + read_offset.Add (fatfile.entries [i].offset); + fatfile.entries [i].offset = fatfile.entries [i - 1].offset + fatfile.entries [i - 1].size; + var alignSize = (1 << (int) fatfile.entries [i].align); + var align = (int) fatfile.entries [i].offset % alignSize; + if (align != 0) + fatfile.entries [i].offset += (uint) (alignSize - align); + } + // Write out the fat file + using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { + using (var writer = new BinaryWriter (fsw)) { + // write headers + fatfile.WriteHeaders (writer); + // write data + for (int i = 0; i < fatfile.entries.Count; i++) { + fatfile.entries [i].Write (writer, reader, read_offset [i]); + } + } + } + } + } + } + + File.Delete (filename); + File.Move (tmpfile, filename); + } +#endif + + static Dictionary> native_dependencies = new Dictionary> (); + + public static IEnumerable GetNativeDependencies (string libraryName) + { + IEnumerable result; + lock (native_dependencies) { + if (native_dependencies.TryGetValue (libraryName, out result)) + return result; + } + + var macho_files = Read (libraryName, ReadingMode.Deferred); + var dependencies = new HashSet (); + foreach (var macho_file in macho_files) { + foreach (var lc in macho_file.load_commands) { + var dyld_lc = lc as Xamarin.DylibLoadCommand; + if (dyld_lc != null) { + dependencies.Add (dyld_lc.name); + } + } + } + result = dependencies; + lock (native_dependencies) + native_dependencies.Add (libraryName, result); + return result; + } + +#if MTOUCH + public static List GetArchitectures (string file) + { + var result = new List (); + + // https://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html + + using (var fs = File.OpenRead (file)) { + using (var reader = new BinaryReader (fs)) { + int magic = reader.ReadInt32 (); + int architectures; + switch ((uint) magic) { + case 0xCAFEBABE: // little-endian fat binary + architectures = reader.ReadInt32 (); + for (int i = 0; i < architectures; i++) { + result.Add (GetArch (reader.ReadInt32 (), reader.ReadInt32 ())); + // skip to next entry + reader.ReadInt32 (); // offset + reader.ReadInt32 (); // size + reader.ReadInt32 (); // align + } + break; + case 0xBEBAFECA: + architectures = System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()); + for (int i = 0; i < architectures; i++) { + result.Add (GetArch (System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()), System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()))); + // skip to next entry + reader.ReadInt32 (); // offset + reader.ReadInt32 (); // size + reader.ReadInt32 (); // align + } + break; + case 0xFEEDFACE: // little-endian mach-o header + case 0xFEEDFACF: // little-endian 64-big mach-o header + result.Add (GetArch (reader.ReadInt32 (), reader.ReadInt32 ())); + break; + case 0xCFFAEDFE: + case 0xCEFAEDFE: + result.Add (GetArch (System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()), System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()))); + break; + default: + Console.WriteLine ("File '{0}' is neither a Universal binary nor a Mach-O binary (magic: 0x{1})", file, magic.ToString ("x")); + break; + } + } + } + + return result; + } + + public static List GetArchitectures (ICollection abi) + { + var rv = new List (abi.Count); + foreach (var a in abi) { + rv.Add ((Architectures) (a & Abi.ArchMask)); + } + return rv; + } + + static Abi GetArch (int cputype, int cpusubtype) + { + switch (cputype) { + case 12: // arm + switch (cpusubtype) { + case 6: + return Abi.ARMv6; + case 9: + return Abi.ARMv7; + case 11: + return Abi.ARMv7s; + default: + return Abi.None; + } + case 12 | 0x01000000: + return Abi.ARM64; + case 7: // x86 + return Abi.i386; + case 7 | 0x01000000: // x64 + return Abi.x86_64; + } + + return Abi.None; + } +#endif + } + + public class StaticLibrary + { + public static bool IsStaticLibrary (BinaryReader reader) + { + var pos = reader.BaseStream.Position; + + var bytes = reader.ReadBytes (8); + var rv = bytes [0] == '!' && bytes [1] == '<' && bytes [2] == 'a' && bytes [3] == 'r' && bytes [4] == 'c' && bytes [5] == 'h' && bytes [6] == '>' && bytes [7] == 0xa; + reader.BaseStream.Position = pos; + + return rv; + } + } + + public enum ReadingMode { + Immediate = 1, + Deferred = 2, + } + + sealed class ReaderParameters : IDisposable { + public BinaryReader Reader; + public string Filename; + public ReadingMode ReadingMode { get; set; } + +#region IDisposable Support + void Dispose (bool disposing) + { + Reader?.Dispose (); + } + + ~ReaderParameters () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } +#endregion + } + + public class MachOFileCollection : List, IDisposable { + internal ReaderParameters Parameters { get; private set; } + + internal MachOFileCollection (ReaderParameters parameters) + { + Parameters = parameters; + } + +#region IDisposable Support + protected virtual void Dispose (bool disposing) + { + Parameters.Dispose (); + } + + ~MachOFileCollection () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize(this); + } +#endregion + } + + public class MachOFile : IDisposable { + internal ReaderParameters parameters { get; private set; } + public uint magic; + public int cputype; + public int cpusubtype; + public uint filetype; + public uint ncmds; + public uint sizeofcmds; + public uint flags; + public uint reserved; + + public List load_commands; + + internal MachOFile (ReaderParameters parameters) + { + this.parameters = parameters; + } + + internal void WriteHeader (BinaryWriter writer) + { + writer.Write (magic); + writer.Write (cputype); + writer.Write (cpusubtype); + writer.Write (filetype); + writer.Write (ncmds); + writer.Write (sizeofcmds); + writer.Write ((uint)flags); + if (magic == MachO.MH_MAGIC_64) + writer.Write (reserved); + } + + internal static bool IsMachOLibrary (BinaryReader reader) + { + var pos = reader.BaseStream.Position; + var magic = reader.ReadUInt32 (); + var rv = false; + switch (magic) { + case MachO.MH_CIGAM: + case MachO.MH_MAGIC: + case MachO.MH_CIGAM_64: + case MachO.MH_MAGIC_64: + rv = true; + break; + default: + rv = false; + break; + } + reader.BaseStream.Position = pos; + return rv; + } + + internal void Read () + { + /* definitions from: /usr/include/mach-o/loader.h */ + /* + * The 32-bit mach header appears at the very beginning of the object file for + * 32-bit architectures. + */ + // struct mach_header { + // uint32_t magic; /* mach magic number identifier */ + // cpu_type_t cputype; /* cpu specifier */ + // cpu_subtype_t cpusubtype; /* machine specifier */ + // uint32_t filetype; /* type of file */ + // uint32_t ncmds; /* number of load commands */ + // uint32_t sizeofcmds; /* the size of all the load commands */ + // uint32_t flags; /* flags */ + // }; + + /* + * The 64-bit mach header appears at the very beginning of object files for + * 64-bit architectures. + */ + // struct mach_header_64 { + // uint32_t magic; /* mach magic number identifier */ + // cpu_type_t cputype; /* cpu specifier */ + // cpu_subtype_t cpusubtype; /* machine specifier */ + // uint32_t filetype; /* type of file */ + // uint32_t ncmds; /* number of load commands */ + // uint32_t sizeofcmds; /* the size of all the load commands */ + // uint32_t flags; /* flags */ + // uint32_t reserved; /* reserved */ + // }; + var reader = parameters.Reader; + StartOffset = reader.BaseStream.Position; + if (!MachOFile.IsMachOLibrary (reader)) { + if (StaticLibrary.IsStaticLibrary (reader)) { + throw new Exception ("Static libraries are not supported (yet)."); + } + throw new Exception ($"Unknown format for fat entry at position {StartOffset}"); + } + magic = reader.ReadUInt32 (); + cputype = reader.ReadInt32 (); + cpusubtype = reader.ReadInt32 (); + filetype = reader.ReadUInt32 (); + ncmds = reader.ReadUInt32 (); + sizeofcmds = reader.ReadUInt32 (); + flags = reader.ReadUInt32 (); + if (magic == MachO.MH_MAGIC_64) + reserved = reader.ReadUInt32 (); + var cmds = new List ((int)ncmds); + for (int i = 0; i < ncmds; i++) { + var cmd = (MachO.LoadCommands)reader.ReadUInt32 (); + reader.BaseStream.Position -= 4; + LoadCommand lc; + switch (cmd) { + case MachO.LoadCommands.LoadDylib: + case MachO.LoadCommands.LoadWeakDylib: + case MachO.LoadCommands.ReexportDylib: + lc = DylibLoadCommand.FromBinaryReader (reader); + break; + case MachO.LoadCommands.SymTab: + lc = SymTabLoadCommand.FromBinaryReader (this, StartOffset); + break; + case MachO.LoadCommands.VersionMinTVOS: + case MachO.LoadCommands.VersionMinMacOS: + case MachO.LoadCommands.VersionMinIPhoneOS: + case MachO.LoadCommands.VersionMinWatchOS: + lc = VersionMinOSLoadCommand.FromBinaryReader (reader); + break; + case MachO.LoadCommands.BuildVersion: + var buildVer = new BuildVersionCommand (); + buildVer.cmd = reader.ReadUInt32 (); + buildVer.cmdsize = reader.ReadUInt32 (); + buildVer.platform = reader.ReadUInt32 (); + buildVer.minos = reader.ReadUInt32 (); + buildVer.sdk = reader.ReadUInt32 (); + buildVer.ntools = reader.ReadUInt32 (); + buildVer.tools = new BuildVersionCommand.BuildToolVersion [buildVer.ntools]; + for (int j = 0; j < buildVer.ntools; j++) { + var buildToolVer = new BuildVersionCommand.BuildToolVersion (); + buildToolVer.tool = reader.ReadUInt32 (); + buildToolVer.version = reader.ReadUInt32 (); + buildVer.tools[j] = buildToolVer; + } + lc = buildVer; + break; + default: + lc = new LoadCommand (); + lc.cmd = reader.ReadUInt32 (); + lc.cmdsize = reader.ReadUInt32 (); + reader.BaseStream.Position += lc.cmdsize - 8; + break; + } + cmds.Add (lc); + } + load_commands = cmds; + } + + public MachO.Architectures Architecture { + get { + switch (cputype) { + case 12: // arm + switch (cpusubtype) { + case 6: + return MachO.Architectures.ARMv6; + case 9: + return MachO.Architectures.ARMv7; + case 11: + return MachO.Architectures.ARMv7s; + default: + return MachO.Architectures.None; + } + case 12 | 0x01000000: + switch (cpusubtype) { + case 2: + return MachO.Architectures.ARM64e; + case 0: + default: + return MachO.Architectures.ARM64; + } + case 12 | 0x02000000: + switch (cpusubtype & ~0xff000000) { + case 1: + return MachO.Architectures.ARM64_32; + default: + return MachO.Architectures.ARM64; + } + case 7: // x86 + return MachO.Architectures.i386; + case 7 | 0x01000000: // x64 + return MachO.Architectures.x86_64; + } + + return MachO.Architectures.None; + } + } + + public bool Is32Bit { + get { + switch (Architecture) { + case MachO.Architectures.ARMv6: + case MachO.Architectures.ARMv7: + case MachO.Architectures.ARMv7s: + case MachO.Architectures.i386: + case MachO.Architectures.None: // not sure what to do with None. + return true; + default: + return false; + } + } + } + + public long StartOffset { get; private set; } + + public class MinOSVersion { + public Version Version; + public string OSName { + get { + switch (Platform) { + case MachO.Platform.IOS: + case MachO.Platform.IOSSimulator: + return "ios"; + case MachO.Platform.MacOS: + return "macosx"; + case MachO.Platform.TvOS: + case MachO.Platform.TvOSSimulator: + return "tvos"; + case MachO.Platform.WatchOS: + case MachO.Platform.WatchOSSimulator: + return "watchos"; + default: + throw new ArgumentOutOfRangeException (Platform.ToString ()); + } + } + } + public MachO.Platform Platform; + public Version Sdk; + } + + public MinOSVersion MinOS { + get { + uint? version = null; + uint? sdk = null; + MachO.Platform platform = (MachO.Platform) 0; + foreach (var lc in load_commands) { + if (lc is VersionMinOSLoadCommand min_lc) { + if (version.HasValue) + throw new NotSupportedException ("File has multiple minOS load commands."); + version = min_lc.version; + sdk = min_lc.sdk; + + switch (min_lc.Command) { + case MachO.LoadCommands.VersionMinMacOS: + platform = MachO.Platform.MacOS; + break; + case MachO.LoadCommands.VersionMinIPhoneOS: + platform = MachO.Platform.IOS; + break; + case MachO.LoadCommands.VersionMinTVOS: + platform = MachO.Platform.TvOS; + break; + case MachO.LoadCommands.VersionMinWatchOS: + platform = MachO.Platform.WatchOS; + break; + default: + throw new ArgumentOutOfRangeException (nameof (min_lc.Command)); + } + } else if (lc is BuildVersionCommand build_lc) { + if (version.HasValue) + throw new NotSupportedException ("File has multiple minOS load commands."); + version = build_lc.minos; + sdk = build_lc.sdk; + platform = build_lc.Platform; + } + } + if (!version.HasValue) + return null; + + return new MinOSVersion { + Version = BuildVersionCommand.DeNibble (version.Value), + Platform = platform, + Sdk = BuildVersionCommand.DeNibble (sdk.Value) + }; + } + } + +#region IDisposable Support + protected virtual void Dispose (bool disposing) + { + parameters?.Dispose (); + } + + ~MachOFile () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } +#endregion + } + + public class FatFile : IDisposable { + internal ReaderParameters parameters { get; private set; } + public uint magic; + public uint nfat_arch; + + public List entries; + internal FatFile (ReaderParameters parameters) + { + this.parameters = parameters; + } + + internal bool is_big_endian { + get { return magic == MachO.FAT_CIGAM; } + } + + internal void WriteHeader (BinaryWriter writer) + { + writer.Write (magic); + if (is_big_endian) { + writer.Write (MachO.ToBigEndian (nfat_arch)); + } else { + writer.Write (nfat_arch); + } + } + + internal void WriteHeaders (BinaryWriter writer) + { + WriteHeader (writer); + for (int i = 0; i < entries.Count; i++) { + entries [i].WriteHeader (writer); + } + } + + internal void Read () + { + var reader = parameters.Reader; + magic = reader.ReadUInt32 (); + nfat_arch = reader.ReadUInt32 (); + if (is_big_endian) + nfat_arch = MachO.FromBigEndian (nfat_arch); + + entries = new List ((int)nfat_arch); + for (int i = 0; i < (int)nfat_arch; i++) { + var entry = new FatEntry (this); + entry.Read (); + entries.Add (entry); + } + foreach (var entry in entries) + entry.ReadEntry (); + } + +#region IDisposable Support + protected virtual void Dispose (bool disposing) + { + parameters.Dispose (); + } + + ~FatFile () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } +#endregion + } + + public class FatEntry { + FatFile parent; + public int cputype; + public int cpusubtype; + public uint offset; + public uint size; + public uint align; + + public MachOFile entry; + + public FatEntry (FatFile parent) + { + this.parent = parent; + } + + internal void WriteHeader (BinaryWriter writer) + { + if (parent.is_big_endian) { + writer.Write (MachO.ToBigEndian (cputype)); + writer.Write (MachO.ToBigEndian (cpusubtype)); + writer.Write (MachO.ToBigEndian (offset)); + writer.Write (MachO.ToBigEndian (size)); + writer.Write (MachO.ToBigEndian (align)); + } else { + writer.Write (cputype); + writer.Write (cpusubtype); + writer.Write (offset); + writer.Write (size); + writer.Write (align); + } + } + + internal void Write (BinaryWriter writer, BinaryReader reader, uint reader_offset) + { + writer.BaseStream.Position = offset; + // write data + WriteFile (writer, reader, reader_offset); + } + + internal void WriteFile (BinaryWriter writer, BinaryReader reader, uint reader_offset) + { + // write data + var ofs = writer.BaseStream.Position; + reader.BaseStream.Position = reader_offset; + var buffer = new byte [1 << (int)align]; + var left = (int)size; + while (left > 0) { + var read = reader.Read (buffer, 0, Math.Min (buffer.Length, left)); + writer.Write (buffer, 0, read); + left -= read; + } + writer.BaseStream.Position = ofs; // restore to the post-header location. + } + + internal void Read () + { + var reader = parent.parameters.Reader; + cputype = reader.ReadInt32 (); + cpusubtype = reader.ReadInt32 (); + offset = reader.ReadUInt32 (); + size = reader.ReadUInt32 (); + align = reader.ReadUInt32 (); + + if (parent.is_big_endian) { + cputype = MachO.FromBigEndian (cputype); + cpusubtype = MachO.FromBigEndian (cpusubtype); + offset = MachO.FromBigEndian (offset); + size = MachO.FromBigEndian (size); + align = MachO.FromBigEndian (align); + } + } + + internal void ReadEntry () + { + var reader = parent.parameters.Reader; + reader.BaseStream.Position = offset; + entry = new MachOFile (parent.parameters); + entry.Read (); + } + } + + public class LoadCommand { + public uint cmd; + public uint cmdsize; + + public MachO.LoadCommands Command { + get { return (MachO.LoadCommands) cmd; } + } + +#if DEBUG + public virtual void Dump () + { + Console.WriteLine (" cmd: {0}", cmd); + Console.WriteLine (" cmdsize: {0}", cmdsize); + } +#endif + + public override string ToString () + { + return Command.ToString (); + } + } + + public class DylibLoadCommand : LoadCommand { + public string name; + public uint timestamp; + public uint current_version; + public uint compatibility_version; + + public static LoadCommand FromBinaryReader (BinaryReader reader) + { + var dlc = new DylibLoadCommand (); + dlc.cmd = reader.ReadUInt32 (); + dlc.cmdsize = reader.ReadUInt32 (); + /*var nameofs = */ + reader.ReadUInt32 (); + dlc.timestamp = reader.ReadUInt32 (); + dlc.current_version = reader.ReadUInt32 (); + dlc.compatibility_version = reader.ReadUInt32 (); + var namelength = dlc.cmdsize - 6 * 4; + var namechars = reader.ReadBytes ((int)namelength); + // strip off any null characters at the end. + for (int n = namechars.Length - 1; n >= 0; n--) { + if (namechars [n] == 0) + namelength--; + else + break; + } + dlc.name = System.Text.UTF8Encoding.UTF8.GetString (namechars, 0, (int)namelength); + return dlc; + } + +#if DEBUG + public override void Dump () + { + base.Dump (); + Console.WriteLine (" name: {0}", name); + Console.WriteLine (" timestamp: {0}", timestamp); + Console.WriteLine (" current_version: {0}", current_version); + Console.WriteLine (" compatibility_version: {0}", compatibility_version); + } +#endif + } + + public class VersionMinOSLoadCommand : LoadCommand { + public uint version; + public uint sdk; + public static LoadCommand FromBinaryReader (BinaryReader reader) + { + var vmlc = new VersionMinOSLoadCommand (); + vmlc.cmd = reader.ReadUInt32 (); + vmlc.cmdsize = reader.ReadUInt32 (); + vmlc.version = reader.ReadUInt32 (); + vmlc.sdk = reader.ReadUInt32 (); + return vmlc; + } + string ToConventionalString (uint val) + { + uint major = val >> 16; + uint minor = (val >> 8) & 0xff; + uint sub = val & 0xff; + if (sub == 0) + return $"{major}.{minor}"; + else + return $"{major}.{minor}.{sub}"; + } + string ToOperatingSystemString (uint theCmd) + { + switch ((MachO.LoadCommands)theCmd) { + case MachO.LoadCommands.VersionMinMacOS: + return "macosx"; + case MachO.LoadCommands.VersionMinIPhoneOS: + return "ios"; + case MachO.LoadCommands.VersionMinTVOS: + return "tvos"; + case MachO.LoadCommands.VersionMinWatchOS: + return "watchos"; + default: + throw new ArgumentOutOfRangeException (nameof (theCmd)); + } + } + + public string ToOSVersionString () + { + return $"{ToConventionalString (version)}"; + } + + public string ToOSString (bool isx8664) + { + return $"{ToOperatingSystemString (cmd)}{ToConventionalString (version)}"; + } + } + + + + public class SymTabLoadCommand : LoadCommand { + MachOFile file; + long startOffset; + + public uint symoff; /* symbol table offset */ + public uint nsyms; /* number of symbol table entries */ + public uint stroff; /* string table offset */ + public uint strsize; /* string table size in bytes */ + NListEntry [] _nlist; + + public NListEntry [] nlist { + get { + if (_nlist == null) + ReadNList (); + return _nlist; + } + } + + public static LoadCommand FromBinaryReader (MachOFile file, long startOffset) + { + var parameters = file.parameters; + var reader = parameters.Reader; + + var stc = new SymTabLoadCommand (); + stc.file = file; + stc.startOffset = startOffset; + stc.cmd = reader.ReadUInt32 (); + stc.cmdsize = reader.ReadUInt32 (); + stc.symoff = reader.ReadUInt32 (); + stc.nsyms = reader.ReadUInt32 (); + stc.stroff = reader.ReadUInt32 (); + stc.strsize = reader.ReadUInt32 (); + if (parameters.ReadingMode == ReadingMode.Immediate) + stc.ReadNList (); + return stc; + } + + public void ReadNList () + { + var reader = file.parameters.Reader; + _nlist = new NListEntry [nsyms]; + long savePos = reader.BaseStream.Position; + try { + reader.BaseStream.Seek (startOffset + symoff, SeekOrigin.Begin); + for (uint i = 0; i < nsyms; i++) + _nlist [i] = NListEntry.FromBinaryReader (reader, file.Is32Bit); + + for (uint i = 0; i < nsyms; i++) { + var entry = _nlist [i]; + reader.BaseStream.Seek (startOffset + stroff + entry.n_strx, SeekOrigin.Begin); + entry.str = ReadStringEntry (reader); + } + } finally { + reader.BaseStream.Seek (savePos, SeekOrigin.Begin); + } + } + + + static string ReadStringEntry (BinaryReader reader) + { + StringBuilder builder = new StringBuilder (); + byte b; + while ((b = reader.ReadByte ()) != 0) { + builder.Append ((char)b); + } + return builder.ToString (); + } + + IEnumerable PublicSymbols { + get { + return nlist.Where ((nle, i) => nle.IsPublic && !nle.IsSymbolicDebuggerEntry); + } + } + +#if DEBUG + public override void Dump () + { + base.Dump (); + Console.WriteLine (" symoff: {0}", symoff); + Console.WriteLine (" nsyms: {0}", nsyms); + Console.WriteLine (" stroff: {0}", stroff); + Console.WriteLine (" strsize: {0}", strsize); + } +#endif + } + + public class BuildVersionCommand : LoadCommand { + public uint platform; + public uint minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + public uint sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + public uint ntools; + public BuildToolVersion[] tools; + + public class BuildToolVersion { + public uint tool; + public uint version; + } + + public static Version DeNibble (uint value) + { + var major = (int) (value >> 16); + var minor = (int) ((value >> 8) & 0xff); + var sub = (int) (value & 0xff); + if (sub == 0) { + // This makes sure the string version is a two-part version (X.Y) when the 'sub' version is 0, + // otherwise various toolchain tools (swiftc among others) will complain. + return new Version (major, minor); + } else { + // Here we have no choice but to be a three-part version (X.Y.Z). + return new Version (major, minor, sub); + } + } + + public Version MinOS { + get { return DeNibble (minos); } + } + + public Version Sdk { + get { return DeNibble (sdk); } + } + + public MachO.Platform Platform { + get { return (MachO.Platform) platform; } + } + } + + // #define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */ + // #define N_ABS 0x2 /* absolute, n_sect == NO_SECT */ + // #define N_SECT 0xe /* defined in section number n_sect */ + // #define N_PBUD 0xc /* prebound undefined (defined in a dylib) */ + // #define N_INDR 0xa /* indirect */ + + public enum NListEntryType { + Undefined = 0, + Absolute = 0x2, + InSection = 0xe, + PreboundUndefined = 0x0c, + Indirect = 0x0a + }; + + public class NListEntry { + const int kSymbolTableMask = 0xe0, + kPrivateExternalMask = 0x10, + kTypeMask = 0x0e, + kExternalMask = 0x01; + + // from nlist.h + public int n_strx; + public byte n_type; + public byte n_sect; + public short n_desc; + public string str; + + public static NListEntry FromBinaryReader (BinaryReader reader, bool is32Bit) + { + NListEntry entry = is32Bit ? (NListEntry)new NListEntry32 () : (NListEntry)new NListEntry64 (); + return entry.FromBinaryReader (reader); + } + + protected virtual NListEntry FromBinaryReader (BinaryReader reader) + { + n_strx = reader.ReadInt32 (); + n_type = reader.ReadByte (); + n_sect = reader.ReadByte (); + n_desc = reader.ReadInt16 (); + return this; + } + + public NListEntryType EntryType { + get { + switch (n_type & kTypeMask) { + case 0x2: + return NListEntryType.Absolute; + case 0xa: + return NListEntryType.Indirect; + case 0xc: + return NListEntryType.PreboundUndefined; + case 0xe: + return NListEntryType.InSection; + default: + return NListEntryType.Undefined; + } + } + } + + public bool IsSymbolicDebuggerEntry { get { return (n_type & kSymbolTableMask) != 0; } } + public bool IsPublic { get { return (n_type & kExternalMask) != 0; } } + public bool IsPrivate { get { return (n_type & kPrivateExternalMask) != 0; } } + + public override string ToString () + { + return str ?? ""; + } + } + + public class NListEntry32 : NListEntry { + public uint n_value; + + protected override NListEntry FromBinaryReader (BinaryReader reader) + { + base.FromBinaryReader (reader); + n_value = reader.ReadUInt32 (); + return this; + } + } + + public class NListEntry64 : NListEntry { + public ulong n_value; + protected override NListEntry FromBinaryReader (BinaryReader reader) + { + base.FromBinaryReader (reader); + n_value = reader.ReadUInt64 (); + return this; + } + } +} + diff --git a/src/SwiftReflector/MarshalEngine.cs b/src/SwiftReflector/MarshalEngine.cs new file mode 100644 index 000000000000..85c4c5d909fc --- /dev/null +++ b/src/SwiftReflector/MarshalEngine.cs @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using SyntaxDynamo.CSLang; +using System.Text; +using System.Linq; +using SwiftRuntimeLibrary; +using SwiftReflector.TypeMapping; +using SyntaxDynamo; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.Demangling; + +namespace SwiftReflector { + public class MarshalEngine { + CSUsingPackages use; + List identifiersUsed; + TypeMapper typeMapper; + public bool skipThisParameterPremarshal = false; + List fixedChain = new List (); + Version swiftLangVersion; + public Func genericReferenceNamer = null; + + public MarshalEngine (CSUsingPackages use, List identifiersUsed, TypeMapper typeMapper, Version swiftLangVersion) + { + this.use = use; + this.identifiersUsed = identifiersUsed; + absolutelyMustBeFirst = new List (); + preMarshalCode = new List (); + postMarshalCode = new List (); + + this.typeMapper = typeMapper; + this.swiftLangVersion = swiftLangVersion; + } + + public IEnumerable MarshalFunctionCall (FunctionDeclaration wrapperFuncDecl, bool isExtension, string pinvokeCall, + CSParameterList pl, + BaseDeclaration typeContext, + TypeSpec swiftReturnType, + CSType returnType, + TypeSpec swiftInstanceType, + CSType instanceType, + bool includeCastToReturnType, + FunctionDeclaration originalFunction, + bool includeIntermediateCastToLong = false, + int passedInIndexOfReturn = -1, + bool originalThrows = false, + bool restoreDynamicSelf = false) + { + RequiredUnsafeCode = false; + preMarshalCode.Clear (); + postMarshalCode.Clear (); + fixedChain.Clear (); + returnLine = null; + functionCall = null; + + var parms = new CSParameterList (pl); // work with local copy + CSIdentifier returnIdent = null, returnIntPtr = null, returnProtocol = null; + var indexOfReturn = passedInIndexOfReturn; + + var originalReturn = swiftReturnType; + + int indexOfInstance = (swiftReturnType != null && (typeMapper.MustForcePassByReference (typeContext, swiftReturnType)) && !swiftReturnType.IsDynamicSelf) || originalThrows ? + 1 : 0; + var instanceIsSwiftProtocol = false; + var instanceIsObjC = false; + + if (swiftInstanceType != null) { + var entity = typeMapper.GetEntityForTypeSpec (swiftInstanceType); + instanceIsSwiftProtocol = entity.EntityType == EntityType.Protocol; + instanceIsObjC = entity.Type.IsObjC; + var thisIdentifier = isExtension ? new CSIdentifier ("self") : CSIdentifier.This; + parms.Insert (0, new CSParameter (instanceType, thisIdentifier, wrapperFuncDecl.ParameterLists.Last () [indexOfInstance].IsInOut ? + CSParameterKind.Ref : CSParameterKind.None)); + } + + var hasReturn = returnType != null && returnType != CSSimpleType.Void; + + if (hasReturn) + returnType = ReworkTypeWithNamer (returnType); + + var isExtensionMethod = pl.Count () > 0 && pl [0].ParameterKind == CSParameterKind.This; + var returnIsScalar = returnType != null && TypeMapper.IsScalar (swiftReturnType); + var returnEntity = hasReturn && !typeContext.IsTypeSpecGenericReference (swiftReturnType) ? typeMapper.GetEntityForTypeSpec (swiftReturnType) : null; + var returnIsTrivialEnum = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.TrivialEnum; + var returnIsGenericClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class && swiftReturnType.ContainsGenericParameters; + var returnIsClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class; + var returnIsNonTrivialTuple = hasReturn && swiftReturnType is TupleTypeSpec && ((TupleTypeSpec)swiftReturnType).Elements.Count > 1; + var returnIsClosure = hasReturn && swiftReturnType is ClosureTypeSpec; + var returnIsGeneric = hasReturn && typeContext.IsTypeSpecGeneric (swiftReturnType) && !returnIsClosure; + var returnIsAssocPath = hasReturn && typeContext.IsProtocolWithAssociatedTypesFullPath (swiftReturnType as NamedTypeSpec, typeMapper); + var returnIsNonScalarStruct = hasReturn && !returnIsScalar && returnEntity != null && + (returnEntity.EntityType == EntityType.Struct || returnEntity.EntityType == EntityType.Enum); + var returnIsSelf = hasReturn && swiftReturnType.IsDynamicSelf; + + var retSimple = returnType as CSSimpleType; + var returnIsInterfaceFromProtocol = + hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Protocol && retSimple != null; + var returnIsProtocolList = hasReturn && swiftReturnType is ProtocolListTypeSpec; + var returnIsObjCProtocol = hasReturn && returnEntity != null && returnEntity.IsObjCProtocol; + var returnNeedsPostProcessing = (hasReturn && (returnIsClass || returnIsProtocolList || returnIsInterfaceFromProtocol || returnIsNonTrivialTuple || + returnIsGeneric || returnIsNonScalarStruct || returnIsAssocPath || (returnIsSelf && !restoreDynamicSelf))) || originalThrows + || returnIsTrivialEnum; + + includeCastToReturnType = includeCastToReturnType || returnIsTrivialEnum; + includeIntermediateCastToLong = includeIntermediateCastToLong || returnIsTrivialEnum; + + var filteredTypeSpec = FilterParams (parms, wrapperFuncDecl, originalThrows); + + var callParameters = new List (parms.Count); + + var offsetToOriginalArgs = 0; + if ((hasReturn && indexOfReturn >= 0) || originalThrows) + offsetToOriginalArgs++; + if (swiftInstanceType != null) + offsetToOriginalArgs++; + if (isExtensionMethod && swiftInstanceType == null) + offsetToOriginalArgs++; + + for (int i = 0; i < parms.Count; i++) { + var p = parms [i]; + // if it's the instance, pass that + // if it's the return, pass that + // otherwise take it from the original functions primary parameter list + TypeSpec originalParm = null; + + if (i == indexOfInstance && swiftInstanceType != null) { + originalParm = swiftInstanceType; + } else if ((hasReturn && i == indexOfReturn) || (originalThrows && i == indexOfReturn)) { + originalParm = swiftReturnType; + } else if (isExtensionMethod && p.ParameterKind == CSParameterKind.This) { + originalParm = originalFunction.IsExtension ? originalFunction.ParentExtension.ExtensionOnType : + new NamedTypeSpec (originalFunction.Parent.ToFullyQualifiedNameWithGenerics ()); + } else { + var index = i - offsetToOriginalArgs; + originalParm = originalFunction.ParameterLists.Last () [i - offsetToOriginalArgs].TypeSpec; + } + callParameters.Add (Marshal (typeContext, wrapperFuncDecl, p, filteredTypeSpec [i], instanceIsSwiftProtocol && i == indexOfInstance, + indexOfReturn >= 0 && i == indexOfReturn, originalParm)); + } + + + var call = new CSFunctionCall (pinvokeCall, false, callParameters.ToArray ()); + + // Post marshal code demands an intermediate return value + if (postMarshalCode.Count > 0 && ((object)returnIdent) == null && (returnType != null && returnType != CSSimpleType.Void)) { + returnIdent = new CSIdentifier (Uniqueify ("retval", identifiersUsed)); + identifiersUsed.Add (returnIdent.Name); + preMarshalCode.Add (CSVariableDeclaration.VarLine (returnType, returnIdent, returnType.Default ())); + } + + + if (((object)returnIdent) != null) { + // if returnIntPtr is non-null, then the function returns a pointer to a class + // If this is the case, we have post marshal code which will assign it to + // retval. + + if (typeMapper.MustForcePassByReference (typeContext, swiftReturnType) || returnIsNonTrivialTuple || returnIsProtocolList) { + this.functionCall = new CSLine (call); + } else { + CSBaseExpression callExpr = call; + if (includeCastToReturnType && returnType != null && returnType != CSSimpleType.Void) { + if (includeIntermediateCastToLong) { + callExpr = new CSCastExpression (CSSimpleType.Long, callExpr); + } + callExpr = new CSCastExpression (returnType, callExpr); + } + this.functionCall = CSAssignment.Assign ((returnIntPtr ?? returnProtocol) ?? returnIdent, callExpr); + } + this.returnLine = CSReturn.ReturnLine (returnIdent); + } else { + if (returnType != null && returnType != CSSimpleType.Void) { + if (includeCastToReturnType) { + CSBaseExpression expr = call; + if (includeIntermediateCastToLong) { + expr = new CSCastExpression (CSSimpleType.Long, expr); + } + expr = new CSCastExpression (returnType, expr); + this.functionCall = CSReturn.ReturnLine (expr); + } else { + this.functionCall = CSReturn.ReturnLine ((ICSExpression)call); + } + } else + this.functionCall = new CSLine (call); + } + + foreach (var l in absolutelyMustBeFirst) + yield return l; + foreach (var l in preMarshalCode) + yield return l; + yield return functionCall; + foreach (var l in postMarshalCode) + yield return l; + if (returnLine != null) + yield return returnLine; + } + + CSParameter ReworkParameterWithNamer (CSParameter p) + { + if (GenericReferenceNamer == null) + return p; + var pClone = ReworkTypeWithNamer (p.CSType); + return new CSParameter (pClone, p.Name, p.ParameterKind, p.DefaultValue); + } + + CSType ReworkTypeWithNamer (CSType ty) + { + if (ty is CSGenericReferenceType genRef) { + var newGen = new CSGenericReferenceType (genRef.Depth, genRef.Index); + newGen.ReferenceNamer = GenericReferenceNamer; + return newGen; + } else if (ty is CSSimpleType simple) { + if (simple.GenericTypes == null) + return simple; + var genSubTypes = new CSType [simple.GenericTypes.Length]; + for (int i = 0; i < genSubTypes.Length; i++) { + genSubTypes [i] = ReworkTypeWithNamer (simple.GenericTypes [i]); + } + var simpleClone = new CSSimpleType (simple.GenericTypeName, simple.IsArray, genSubTypes); + return simpleClone; + } else { + throw new NotImplementedException ($"Unable to rework type {ty.GetType ().Name} {ty.ToString ()} as generic reference"); + } + } + + CSBaseExpression Marshal (BaseDeclaration typeContext, FunctionDeclaration funcDecl, CSParameter p, TypeSpec swiftType, + bool marshalProtocolAsValueType, bool isReturnVariable, TypeSpec originalType) + { + p = ReworkParameterWithNamer (p); + + var entityType = typeMapper.GetEntityTypeForTypeSpec (swiftType); + switch (entityType) { + case EntityType.Scalar: + case EntityType.Tuple: + case EntityType.None: + // Add more types + break; + } + throw new NotImplementedException ($"Uh-oh - not ready for {swiftType.ToString ()}, a {entityType}."); + } + + public static string Uniqueify (string name, IEnumerable names) + { + int thisTime = 0; + var sb = new StringBuilder (name); + while (names.Contains (sb.ToString ())) { + sb.Clear ().Append (name).Append (thisTime++); + } + return sb.ToString (); + } + + TypeSpec [] FilterParams (CSParameterList parms, FunctionDeclaration wrapperFunc, bool originalThrows) + { + var results = new TypeSpec [parms.Count]; + var parameterList = wrapperFunc.ParameterLists.Last (); + for (int i=0; i < parms.Count; i++) { + var currType = parameterList [i].TypeSpec; + results [i] = currType; + } + return results; + } + + List absolutelyMustBeFirst; + List preMarshalCode; + CSLine functionCall; + List postMarshalCode; + CSLine returnLine; + + public bool MarshalProtocolsDirectly { get; set; } + public bool RequiredUnsafeCode { get; private set; } + public bool MarshalingConstructor { get; set; } + public Func GenericReferenceNamer { get; set; } + public CSType ProtocolInterfaceType { get; set; } + + } +} + diff --git a/src/SwiftReflector/PunyCode.cs b/src/SwiftReflector/PunyCode.cs new file mode 100644 index 000000000000..1b342c8be262 --- /dev/null +++ b/src/SwiftReflector/PunyCode.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SwiftReflector { + public class PunyCode { + const string kEncodingStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"; + + Dictionary decodeTable; + const int kBase = 36; + const int tMin = 1; + const int tMax = 26; + const int skew = 38; + const int damp = 700; + const int initialBias = 72; + const int initialN = 0x80; + const char delimiter = '_'; + + public PunyCode () + { + decodeTable = MakeDecodeTable (kEncodingStr); + } + + public Dictionary MakeDecodeTable (string s) + { + var table = new Dictionary (); + for (int i = 0; i < s.Length; i++) { + table [s [i]] = i; + } + return table; + } + + static int Adapt (int delta, int numPoints, bool firstTime) + { + delta = delta / (firstTime ? damp : 2); + + delta += delta / numPoints; + int k = 0; + while (delta > ((kBase - tMin) * tMax) / 2) { + delta = delta / (kBase - tMin); + k = k + kBase; + } + k += ((kBase - tMin + 1) * delta) / (delta + skew); + return k; + } + + public string Decode (string input) + { + + int n = initialN; + int i = 0; + int bias = initialBias; + var output = new StringBuilder (); + + int pos = 0; + var delim = input.LastIndexOf ('_'); + if (delim > 0) { + output.Append (input.Substring (0, delim)); + pos = delim + 1; + } + + int outputLength = output.Length; + int inputLength = input.Length; + while (pos < inputLength) { + int oldi = i; + int w = 1; + for (int k = kBase; ; k += kBase) { + int digit = decodeTable [input [pos++]]; + i = i + (digit * w); + int t = Math.Max (Math.Min (k - bias, tMax), tMin); + if (digit < t) { + break; + } + w = w * (kBase - t); + } + bias = Adapt (i - oldi, ++outputLength, (oldi == 0)); + n = n + i / outputLength; + i = i % outputLength; + if (n >= 0xd800 && n <= 0xdfff) + output.Insert (i, (char)n); + else + output.Insert (i, Char.ConvertFromUtf32 (n)); + i++; + } + return output.ToString (); + } + + static int digit_index (char value) + { + if (value >= 'a' && value <= 'z') + return value - 'a'; + if (value >= 'A' && value <= 'J') + return value - 'A' + 26; + return -1; + } + + // I'm leaving this here for possible future need. + // This is a port of Apple's decode which is more or less equivalent to + // the above Decode. They both have their plusses and minuses, but I like Apple's + // lees, so it's not (currently) active. + + public string AppleDecode (string inputPunyCode) + { + var output = new StringBuilder (); + int i = 0; + var n = initialN; + var bias = initialBias; + + var lastDelimiter = inputPunyCode.LastIndexOf (delimiter); + if (lastDelimiter > 0) { + for (int x=0; x < lastDelimiter; x++) { + if (inputPunyCode [x] > 0x7f) + return output.ToString (); + output.Append (inputPunyCode [x]); + } + } + + var inputPunySlice = new StringSlice (inputPunyCode.Substring (lastDelimiter + 1)); + + while (!inputPunySlice.IsAtEnd) { + var oldi = i; + var w = 1; + for (int k = kBase; ; k += kBase) { + if (inputPunySlice.IsAtEnd) + return output.ToString (); + var codePoint = inputPunySlice.Advance (); + + var digit = digit_index (codePoint); + if (digit < 0) + return output.ToString (); + + i = i + digit * w; + var t = k <= bias ? tMin + : (k >= bias + tMax ? tMax : k - bias); + if (digit < t) + break; + w = w * (kBase - t); + } + bias = Adapt (i - oldi, output.Length + 1, oldi == 0); + n = n + i / (output.Length + 1); + i = i % (output.Length + 1); + if (n < 0x80) + return output.ToString (); + if (n >= 0xd800 && n <= 0xdfff) + output.Insert (i, (char)n); + else + output.Insert (i, Char.ConvertFromUtf32 (n)); + i++; + } + return output.ToString (); + } + + static PunyCode _puny = new PunyCode (); + public static PunyCode PunySingleton { get { return _puny; } } + } +} + diff --git a/src/SwiftReflector/ReflectorError.cs b/src/SwiftReflector/ReflectorError.cs new file mode 100644 index 000000000000..06d753b007a7 --- /dev/null +++ b/src/SwiftReflector/ReflectorError.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using SwiftReflector.ExceptionTools; +using System.Linq; + +namespace SwiftReflector { + + // Range of error messages + // 0000 - total abject failure + // 0500 - should never, ever happen. Ever. (skipped case, argument null, argument out of range) + // 1000 - compiler error, generating C# + // 1500 - compiler error, C# trying to reference swift wrapper + // 2500 - importing types from C# bindings + // 2000 - wrapping error, wrapping swift code in C# callable wrappers + // 3000 - decomposition error, demangling swift symbols + // 4000 - error dropping swift symbols into inventory + // 5000 - error reflecting on swift module + // 6000 - error parsing TypeSpec + // 7000 - error mapping one type to another + + + public class ReflectorError { + public const int kCantHappenBase = 500; + public const int kCompilerBase = 1000; + public const int kCompilerReferenceBase = 1500; + public const int kWrappingBase = 2000; + public const int kImportingBase = 2500; + public const int kDecomposeBase = 3000; + public const int kInventoryBase = 4000; + public const int kReflectionErrorBase = 5000; + public const int kTypeParseBase = 6000; + public const int kTypeMapBase = 7000; + + public ReflectorError (Exception e) + { + if (e is RuntimeException re) { + Exception = re; + Error = re.Error; + } else if (e is AggregateException ae && ae.InnerExceptions.All ((v) => v is RuntimeException)) { + Exception = ae; + // If any of the exceptions is an error, the whole collection is an error as well. + Error = ae.InnerExceptions.Cast ().Any ((v) => v.Error); + } else { + Exception = new RuntimeException (kCantHappenBase + 54, error: true, innerException: e, message: e.Message); + Error = true; + } + } + + public Exception Exception { get; private set; } + public bool Error { get; private set; } + + public bool IsWarning => !Error; + public string Message => Exception.Message; + } +} diff --git a/src/SwiftReflector/StringSlice.cs b/src/SwiftReflector/StringSlice.cs new file mode 100644 index 000000000000..cc271e8b08cf --- /dev/null +++ b/src/SwiftReflector/StringSlice.cs @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Text; +using System.Collections.Generic; +using SwiftRuntimeLibrary; + +namespace SwiftReflector { + public class StringSlice { + string slice; + + public StringSlice (string s) + { + slice = Exceptions.ThrowOnNull (s, "s"); + } + + public bool StartsWith (char c) + { + return Current == c; + } + + public bool StartsWith (string s) + { + if (s == null) + throw new ArgumentNullException (nameof(s)); + if (s == "") + return true; // I guess? + if (s.Length > Length) + return false; + for (int i = 0; i < s.Length; i++) { + if (s [i] != this [i]) + return false; + } + return true; + } + + public char Current { + get { + // returns the current character in the slice + // this[0] always points to the character (see + // the indexer). + if (IsAtEnd) + throw new ArgumentException ("at end"); + return this [0]; + } + } + + public bool IsAtEnd { get { return Position == slice.Length; } } + + public int Position { get; private set; } + public int Length { get { return slice.Length - Position; } } + + public string Original { get { return slice; } } + + public override string ToString () + { + if (IsAtEnd) + return ""; + return Position == 0 ? slice : slice.Substring (Current); + } + + public char Advance () + { + if (IsAtEnd) { + throw new IndexOutOfRangeException (); + } + char c = Current; + Position++; + return c; + } + + public bool AdvanceIfEquals (char c) + { + return AdvanceIf (sl => sl.Current == c); + } + + public bool AdvanceIf (Predicate pred) + { + if (pred == null) + throw new ArgumentNullException (); + bool eq = pred (this); + if (eq) + Advance (); + return eq; + } + + public string Advance (int n) + { + if (n < 0 || n + Position > slice.Length) + throw new ArgumentOutOfRangeException (nameof(n)); + if (n == 0) + return ""; + string sub = slice.Substring (Position, n); + Position += n; + return sub; + } + + public void Rewind() + { + if (Position <= 0) + throw new InvalidOperationException ("Can't rewind a slice already at the start."); + Position -= 1; + } + + public char this [int index] { + get { + if (index + Position >= slice.Length) + throw new IndexOutOfRangeException (); + return slice [index + Position]; + } + } + + static bool IsNameStart (char c) + { + return Char.IsDigit (c) || c == 'X'; + } + + public bool IsNameNext { + get { + return !IsAtEnd && IsNameStart (Current); + } + } + + public string ConsumeRemaining() + { + if (IsAtEnd) + return ""; + var result = slice.Substring (Position); + Advance (result.Length); + return result; + } + + public string Substring(int position, int length) + { + return slice.Substring (position, length); + } + + public string ExtractSwiftString (out bool isPunyCode) + { + if (!IsNameNext) { + isPunyCode = false; + return null; + } + + int count = 0; + + if ((isPunyCode = Current == 'X')) + Advance (); + + while (!IsAtEnd && Char.IsDigit (Current)) { + count = count * 10 + Advance () - '0'; + } + return Advance (count); + } + + public SwiftName ExtractSwiftName () + { + bool isPunyCode = false; + string s = ExtractSwiftString (out isPunyCode); + if (s == null) + return null; + return new SwiftName (s, isPunyCode); + } + + public SwiftName ExtractSwiftNameMaybeOperator (out OperatorType oper) + { + oper = OperatorType.None; + if (StartsWith ('o')) { + Advance (); + char c = Advance (); + switch (c) { + case 'p': + oper = OperatorType.Prefix; + break; + case 'P': + oper = OperatorType.Postfix; + break; + case 'i': + oper = OperatorType.Infix; + break; + default: + break; + } + } + bool isPunyCode = false; + string s = ExtractSwiftString (out isPunyCode); + if (s == null) + return null; + if (oper != OperatorType.None) { + s = DecodeOperatorName (s); + } + return new SwiftName (s, isPunyCode); + } + + static string _opChars = "& @/= > <*!|+?%-~ ^ ."; + static string DecodeOperatorName (string s) + { + var sb = new StringBuilder (); + foreach (char c in s) { + if (c > 32767) { + sb.Append (c); + continue; + } + if (c < 'a' || c > 'z') + throw new ArgumentOutOfRangeException (nameof(s), String.Format ("operator name '{0}' contains illegal characters", s)); + char o = _opChars [c - 'a']; + sb.Append (o); + } + return sb.ToString (); + } + + + } +} + diff --git a/src/SwiftReflector/SwiftClassName.cs b/src/SwiftReflector/SwiftClassName.cs new file mode 100644 index 000000000000..da6c1cf424ef --- /dev/null +++ b/src/SwiftReflector/SwiftClassName.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SwiftReflector.Demangling; +using SwiftRuntimeLibrary; + +namespace SwiftReflector { + public class SwiftClassName { + public SwiftClassName (SwiftName module, IList nesting, IList nestingNames, OperatorType oper = OperatorType.None) + { + Module = Exceptions.ThrowOnNull (module, "module"); + Nesting = Exceptions.ThrowOnNull (nesting, "nesting"); + NestingNames = Exceptions.ThrowOnNull (nestingNames, "nestingNames"); + Terminus = NestingNames.Count > 0 ? NestingNames [NestingNames.Count - 1] : null; + Operator = oper; + } + + public static SwiftClassName FromFullyQualifiedName (string fullyQualifiedName, OperatorType oper, params char [] nesting) + { + string [] parts = Exceptions.ThrowOnNull (fullyQualifiedName, "fullyQualifiedName").Split ('.'); + if (parts.Length < 2) + throw new ArgumentException (String.Format ("Fully qualified name '{0}' requires at least a module and one name.", + fullyQualifiedName)); + if (nesting.Length != parts.Length - 1) + throw new ArgumentException (String.Format ("Nesting should have {0} elements, but has {1}.", + parts.Length - 1, nesting.Length), "nesting"); + SwiftName module = new SwiftName (parts [0], false); + List nestingNames = parts.Skip (1).Select (name => new SwiftName (name, false)).ToList (); + List actualNesting = nesting.Select (c => Decomposer.ToMaybeMemberNesting (c, true).Value).ToList (); + return new SwiftClassName (module, actualNesting, nestingNames, oper); + } + + public static SwiftClassName FromFullyQualifiedName (string fullyQualifiedName, OperatorType oper, string nesting) + { + return FromFullyQualifiedName (fullyQualifiedName, oper, nesting.ToArray ()); + } + + public SwiftName Module { get; private set; } + public IList Nesting { get; private set; } + public IList NestingNames { get; private set; } + public SwiftName Terminus { get; private set; } + public OperatorType Operator { get; set; } + + public bool IsClass { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Class; } } + public bool IsStruct { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Struct; } } + public bool IsEnum { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Enum; } } + public bool IsOperator { get { return Operator != OperatorType.None; } } + public string ToFullyQualifiedName (bool includeModule = true) + { + var sb = new StringBuilder (); + if (includeModule) + sb.Append (Module.Name); + for (int i = 0; i < NestingNames.Count; i++) { + if (includeModule || (!includeModule && i > 0)) + sb.Append ('.'); + sb.Append (NestingNames [i].Name); + } + return sb.ToString (); + } + + public override int GetHashCode () + { + int hashCode = Module.GetHashCode (); + foreach (SwiftName name in NestingNames) + hashCode += name.GetHashCode (); + return hashCode; + } + + public override bool Equals (object obj) + { + var other = obj as SwiftClassName; + if (other == null) { + return false; + } + if (other == this) + return true; + return Module.Equals (other.Module) && NamesAreEqual (other); + } + + public override string ToString () + { + return ToFullyQualifiedName (true); + } + + bool NamesAreEqual (SwiftClassName other) + { + if (NestingNames.Count != other.NestingNames.Count) + return false; + for (int i = 0; i < NestingNames.Count; i++) { + if (!NestingNames [i].Equals (other.NestingNames [i])) + return false; + } + return true; + } + + } +} + diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs new file mode 100644 index 000000000000..07d5302b6611 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs @@ -0,0 +1,2131 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// ANTLR Version: 4.9.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// Generated from SwiftInterface.g4 by ANTLR 4.9.1 + +// Unreachable code detected +#pragma warning disable 0162 +// The variable '...' is assigned but its value is never used +#pragma warning disable 0219 +// Missing XML comment for publicly visible type or member '...' +#pragma warning disable 1591 +// Ambiguous reference in cref attribute +#pragma warning disable 419 + + +using Antlr4.Runtime.Misc; +using IErrorNode = Antlr4.Runtime.Tree.IErrorNode; +using ITerminalNode = Antlr4.Runtime.Tree.ITerminalNode; +using IToken = Antlr4.Runtime.IToken; +using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; + +/// +/// This class provides an empty implementation of , +/// which can be extended to create a listener which only needs to handle a subset +/// of the available methods. +/// +[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] +[System.Diagnostics.DebuggerNonUserCode] +// [System.CLSCompliant(false)] +public partial class SwiftInterfaceBaseListener : ISwiftInterfaceListener { + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterStatement([NotNull] SwiftInterfaceParser.StatementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitStatement([NotNull] SwiftInterfaceParser.StatementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterComment([NotNull] SwiftInterfaceParser.CommentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitComment([NotNull] SwiftInterfaceParser.CommentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterParameter([NotNull] SwiftInterfaceParser.ParameterContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitParameter([NotNull] SwiftInterfaceParser.ParameterContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAttribute([NotNull] SwiftInterfaceParser.AttributeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAttribute([NotNull] SwiftInterfaceParser.AttributeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAttributes([NotNull] SwiftInterfaceParser.AttributesContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAttributes([NotNull] SwiftInterfaceParser.AttributesContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterPattern([NotNull] SwiftInterfaceParser.PatternContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitPattern([NotNull] SwiftInterfaceParser.PatternContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context) { } + /// + /// Enter a parse tree produced by the dict_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context) { } + /// + /// Exit a parse tree produced by the dict_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context) { } + /// + /// Enter a parse tree produced by the any_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context) { } + /// + /// Exit a parse tree produced by the any_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context) { } + /// + /// Enter a parse tree produced by the identifier_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context) { } + /// + /// Exit a parse tree produced by the identifier_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context) { } + /// + /// Enter a parse tree produced by the func_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context) { } + /// + /// Exit a parse tree produced by the func_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context) { } + /// + /// Enter a parse tree produced by the arr_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context) { } + /// + /// Exit a parse tree produced by the arr_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context) { } + /// + /// Enter a parse tree produced by the meta_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context) { } + /// + /// Exit a parse tree produced by the meta_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context) { } + /// + /// Enter a parse tree produced by the boxed_protocol_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context) { } + /// + /// Exit a parse tree produced by the boxed_protocol_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context) { } + /// + /// Enter a parse tree produced by the optional_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context) { } + /// + /// Exit a parse tree produced by the optional_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context) { } + /// + /// Enter a parse tree produced by the self_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context) { } + /// + /// Exit a parse tree produced by the self_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context) { } + /// + /// Enter a parse tree produced by the unwrapped_optional_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context) { } + /// + /// Exit a parse tree produced by the unwrapped_optional_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context) { } + /// + /// Enter a parse tree produced by the proto_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context) { } + /// + /// Exit a parse tree produced by the proto_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context) { } + /// + /// Enter a parse tree produced by the tup_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context) { } + /// + /// Exit a parse tree produced by the tup_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context) { } + /// + /// Enter a parse tree produced by the self_long + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context) { } + /// + /// Exit a parse tree produced by the self_long + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context) { } + /// + /// Enter a parse tree produced by the proto_comp_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context) { } + /// + /// Exit a parse tree produced by the proto_comp_type + /// labeled alternative in . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterType_name([NotNull] SwiftInterfaceParser.Type_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitType_name([NotNull] SwiftInterfaceParser.Type_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterLiteral([NotNull] SwiftInterfaceParser.LiteralContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitLiteral([NotNull] SwiftInterfaceParser.LiteralContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterString_literal([NotNull] SwiftInterfaceParser.String_literalContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitString_literal([NotNull] SwiftInterfaceParser.String_literalContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRequirement([NotNull] SwiftInterfaceParser.RequirementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRequirement([NotNull] SwiftInterfaceParser.RequirementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOperator([NotNull] SwiftInterfaceParser.OperatorContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOperator([NotNull] SwiftInterfaceParser.OperatorContext context) { } + /// + /// Enter a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void EnterOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context) { } + /// + /// Exit a parse tree produced by . + /// The default implementation does nothing. + /// + /// The parse tree. + public virtual void ExitOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context) { } + + /// + /// The default implementation does nothing. + public virtual void EnterEveryRule([NotNull] ParserRuleContext context) { } + /// + /// The default implementation does nothing. + public virtual void ExitEveryRule([NotNull] ParserRuleContext context) { } + /// + /// The default implementation does nothing. + public virtual void VisitTerminal([NotNull] ITerminalNode node) { } + /// + /// The default implementation does nothing. + public virtual void VisitErrorNode([NotNull] IErrorNode node) { } +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs new file mode 100644 index 000000000000..46601ea02f16 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs @@ -0,0 +1,1395 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// ANTLR Version: 4.9.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// Generated from SwiftInterface.g4 by ANTLR 4.9.1 + +// Unreachable code detected +#pragma warning disable 0162 +// The variable '...' is assigned but its value is never used +#pragma warning disable 0219 +// Missing XML comment for publicly visible type or member '...' +#pragma warning disable 1591 +// Ambiguous reference in cref attribute +#pragma warning disable 419 + +using System; +using System.IO; +using System.Text; +using Antlr4.Runtime; +using Antlr4.Runtime.Atn; +using Antlr4.Runtime.Misc; +using DFA = Antlr4.Runtime.Dfa.DFA; + +[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] +// [System.CLSCompliant(false)] +public partial class SwiftInterfaceLexer : Lexer { + protected static DFA[] decisionToDFA; + protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); + public const int + T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, + T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, + T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24, + T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31, + T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, T__37=38, + T__38=39, T__39=40, T__40=41, T__41=42, T__42=43, T__43=44, T__44=45, + T__45=46, T__46=47, T__47=48, T__48=49, T__49=50, T__50=51, T__51=52, + T__52=53, T__53=54, T__54=55, T__55=56, T__56=57, T__57=58, T__58=59, + T__59=60, T__60=61, T__61=62, T__62=63, T__63=64, T__64=65, T__65=66, + T__66=67, T__67=68, T__68=69, T__69=70, T__70=71, T__71=72, T__72=73, + T__73=74, T__74=75, T__75=76, T__76=77, T__77=78, T__78=79, T__79=80, + T__80=81, T__81=82, T__82=83, T__83=84, T__84=85, T__85=86, T__86=87, + T__87=88, T__88=89, T__89=90, T__90=91, T__91=92, T__92=93, T__93=94, + T__94=95, T__95=96, T__96=97, T__97=98, T__98=99, T__99=100, T__100=101, + T__101=102, T__102=103, T__103=104, T__104=105, T__105=106, T__106=107, + T__107=108, T__108=109, T__109=110, T__110=111, T__111=112, Binary_literal=113, + Octal_literal=114, Decimal_literal=115, Pure_decimal_digits=116, Hexadecimal_literal=117, + Static_string_literal=118, Identifier=119, Implicit_parameter_name=120, + WS=121, OpPlus=122, OpMinus=123, OpAssign=124, OpAmp=125, OpQuestion=126, + OpLess=127, OpBang=128, OpDot=129, OpComma=130, OpTilde=131, OpColon=132, + OpSemi=133, OpAt=134, OpPound=135, OpBackTick=136, OpUnder=137, OpLParen=138, + OpRParen=139, OpLBracket=140, OpRBracket=141, OpLBrace=142, OpRBrace=143, + Decimal_digits=144, Operator=145, DotOperatorHead=146, DotOperatorFollow=147, + OpEqEq=148, Comment_line=149; + public static string[] channelNames = { + "DEFAULT_TOKEN_CHANNEL", "HIDDEN" + }; + + public static string[] modeNames = { + "DEFAULT_MODE" + }; + + public static readonly string[] ruleNames = { + "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", + "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16", + "T__17", "T__18", "T__19", "T__20", "T__21", "T__22", "T__23", "T__24", + "T__25", "T__26", "T__27", "T__28", "T__29", "T__30", "T__31", "T__32", + "T__33", "T__34", "T__35", "T__36", "T__37", "T__38", "T__39", "T__40", + "T__41", "T__42", "T__43", "T__44", "T__45", "T__46", "T__47", "T__48", + "T__49", "T__50", "T__51", "T__52", "T__53", "T__54", "T__55", "T__56", + "T__57", "T__58", "T__59", "T__60", "T__61", "T__62", "T__63", "T__64", + "T__65", "T__66", "T__67", "T__68", "T__69", "T__70", "T__71", "T__72", + "T__73", "T__74", "T__75", "T__76", "T__77", "T__78", "T__79", "T__80", + "T__81", "T__82", "T__83", "T__84", "T__85", "T__86", "T__87", "T__88", + "T__89", "T__90", "T__91", "T__92", "T__93", "T__94", "T__95", "T__96", + "T__97", "T__98", "T__99", "T__100", "T__101", "T__102", "T__103", "T__104", + "T__105", "T__106", "T__107", "T__108", "T__109", "T__110", "T__111", + "Binary_literal", "Binary_digit", "Binary_literal_character", "Binary_literal_characters", + "Octal_literal", "Octal_digit", "Octal_literal_character", "Octal_literal_characters", + "Decimal_literal", "Pure_decimal_digits", "Hexadecimal_literal", "Hexadecimal_digit", + "Hexadecimal_literal_character", "Hexadecimal_literal_characters", "Static_string_literal", + "Quoted_text", "Quoted_text_item", "Escaped_character", "Identifier", + "Identifier_head", "Identifier_character", "Identifier_characters", "Implicit_parameter_name", + "WS", "OpPlus", "OpMinus", "OpAssign", "OpAmp", "OpQuestion", "OpLess", + "OpBang", "OpDot", "OpComma", "OpTilde", "OpColon", "OpSemi", "OpAt", + "OpPound", "OpBackTick", "OpUnder", "OpLParen", "OpRParen", "OpLBracket", + "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", "Operator", "OperatorHeadGreater", + "OperatorHead", "OperatorCharacters", "OperatorFollowNoGreater", "OperatorFollow", + "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line" + }; + + + public SwiftInterfaceLexer(ICharStream input) + : this(input, Console.Out, Console.Error) { } + + public SwiftInterfaceLexer(ICharStream input, TextWriter output, TextWriter errorOutput) + : base(input, output, errorOutput) + { + Interpreter = new LexerATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); + } + + private static readonly string[] _LiteralNames = { + null, "'import'", "'typealias'", "'struct'", "'class'", "'enum'", "'protocol'", + "'var'", "'func'", "'let'", "'get'", "'set'", "'indirect'", "'case'", + "'final'", "'prefix'", "'operator'", "'postfix'", "'infix'", "'precedencegroup'", + "'higherThan'", "'lowerThan'", "'assignment'", "'associativity'", "'left'", + "'right'", "'none'", "'extension'", "'subscript'", "'associatedtype'", + "'async'", "'throws'", "'rethrows'", "'init'", "'deinit'", "'convenience'", + "'dynamic'", "'lazy'", "'optional'", "'override'", "'required'", "'static'", + "'unowned'", "'safe'", "'unsafe'", "'weak'", "'private'", "'fileprivate'", + "'internal'", "'public'", "'open'", "'mutating'", "'nonmutating'", "'is'", + "'as'", "'Type'", "'Protocol'", "'Any'", "'Self'", "'any'", "'inout'", + "'nil'", "'true'", "'false'", "'where'", "'>'", "'->'", "'...'", "'alpha'", + "'arch'", "'arm'", "'arm64'", "'blue'", "'didSet'", "'file'", "'green'", + "'i386'", "'iOS'", "'iOSApplicationExtension'", "'line'", "'macOS'", "'macOSApplicationExtension'", + "'of'", "'os'", "'precedence'", "'red'", "'resourceName'", "'swift'", + "'tvOS'", "'type'", "'watchOS'", "'willSet'", "'x86_64'", "'break'", "'catch'", + "'continue'", "'default'", "'defer'", "'do'", "'else'", "'fallthrough'", + "'for'", "'guard'", "'if'", "'in'", "'repeat'", "'return'", "'self'", + "'super'", "'switch'", "'throw'", "'try'", "'while'", null, null, null, + null, null, null, null, null, null, "'+'", "'-'", "'='", "'&'", "'?'", + "'<'", "'!'", "'.'", "','", "'~'", "':'", "';'", "'@'", "'#'", "'`'", + "'_'", "'('", "')'", "'['", "']'", "'{'", "'}'", null, null, null, null, + "'=='" + }; + private static readonly string[] _SymbolicNames = { + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, "Binary_literal", "Octal_literal", "Decimal_literal", + "Pure_decimal_digits", "Hexadecimal_literal", "Static_string_literal", + "Identifier", "Implicit_parameter_name", "WS", "OpPlus", "OpMinus", "OpAssign", + "OpAmp", "OpQuestion", "OpLess", "OpBang", "OpDot", "OpComma", "OpTilde", + "OpColon", "OpSemi", "OpAt", "OpPound", "OpBackTick", "OpUnder", "OpLParen", + "OpRParen", "OpLBracket", "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", + "Operator", "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line" + }; + public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); + + [NotNull] + public override IVocabulary Vocabulary + { + get + { + return DefaultVocabulary; + } + } + + public override string GrammarFileName { get { return "SwiftInterface.g4"; } } + + public override string[] RuleNames { get { return ruleNames; } } + + public override string[] ChannelNames { get { return channelNames; } } + + public override string[] ModeNames { get { return modeNames; } } + + public override string SerializedAtn { get { return new string(_serializedATN); } } + + static SwiftInterfaceLexer() { + decisionToDFA = new DFA[_ATN.NumberOfDecisions]; + for (int i = 0; i < _ATN.NumberOfDecisions; i++) { + decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); + } + } + private static char[] _serializedATN = { + '\x3', '\x608B', '\xA72A', '\x8133', '\xB9ED', '\x417C', '\x3BE7', '\x7786', + '\x5964', '\x2', '\x97', '\x565', '\b', '\x1', '\x4', '\x2', '\t', '\x2', + '\x4', '\x3', '\t', '\x3', '\x4', '\x4', '\t', '\x4', '\x4', '\x5', '\t', + '\x5', '\x4', '\x6', '\t', '\x6', '\x4', '\a', '\t', '\a', '\x4', '\b', + '\t', '\b', '\x4', '\t', '\t', '\t', '\x4', '\n', '\t', '\n', '\x4', '\v', + '\t', '\v', '\x4', '\f', '\t', '\f', '\x4', '\r', '\t', '\r', '\x4', '\xE', + '\t', '\xE', '\x4', '\xF', '\t', '\xF', '\x4', '\x10', '\t', '\x10', '\x4', + '\x11', '\t', '\x11', '\x4', '\x12', '\t', '\x12', '\x4', '\x13', '\t', + '\x13', '\x4', '\x14', '\t', '\x14', '\x4', '\x15', '\t', '\x15', '\x4', + '\x16', '\t', '\x16', '\x4', '\x17', '\t', '\x17', '\x4', '\x18', '\t', + '\x18', '\x4', '\x19', '\t', '\x19', '\x4', '\x1A', '\t', '\x1A', '\x4', + '\x1B', '\t', '\x1B', '\x4', '\x1C', '\t', '\x1C', '\x4', '\x1D', '\t', + '\x1D', '\x4', '\x1E', '\t', '\x1E', '\x4', '\x1F', '\t', '\x1F', '\x4', + ' ', '\t', ' ', '\x4', '!', '\t', '!', '\x4', '\"', '\t', '\"', '\x4', + '#', '\t', '#', '\x4', '$', '\t', '$', '\x4', '%', '\t', '%', '\x4', '&', + '\t', '&', '\x4', '\'', '\t', '\'', '\x4', '(', '\t', '(', '\x4', ')', + '\t', ')', '\x4', '*', '\t', '*', '\x4', '+', '\t', '+', '\x4', ',', '\t', + ',', '\x4', '-', '\t', '-', '\x4', '.', '\t', '.', '\x4', '/', '\t', '/', + '\x4', '\x30', '\t', '\x30', '\x4', '\x31', '\t', '\x31', '\x4', '\x32', + '\t', '\x32', '\x4', '\x33', '\t', '\x33', '\x4', '\x34', '\t', '\x34', + '\x4', '\x35', '\t', '\x35', '\x4', '\x36', '\t', '\x36', '\x4', '\x37', + '\t', '\x37', '\x4', '\x38', '\t', '\x38', '\x4', '\x39', '\t', '\x39', + '\x4', ':', '\t', ':', '\x4', ';', '\t', ';', '\x4', '<', '\t', '<', '\x4', + '=', '\t', '=', '\x4', '>', '\t', '>', '\x4', '?', '\t', '?', '\x4', '@', + '\t', '@', '\x4', '\x41', '\t', '\x41', '\x4', '\x42', '\t', '\x42', '\x4', + '\x43', '\t', '\x43', '\x4', '\x44', '\t', '\x44', '\x4', '\x45', '\t', + '\x45', '\x4', '\x46', '\t', '\x46', '\x4', 'G', '\t', 'G', '\x4', 'H', + '\t', 'H', '\x4', 'I', '\t', 'I', '\x4', 'J', '\t', 'J', '\x4', 'K', '\t', + 'K', '\x4', 'L', '\t', 'L', '\x4', 'M', '\t', 'M', '\x4', 'N', '\t', 'N', + '\x4', 'O', '\t', 'O', '\x4', 'P', '\t', 'P', '\x4', 'Q', '\t', 'Q', '\x4', + 'R', '\t', 'R', '\x4', 'S', '\t', 'S', '\x4', 'T', '\t', 'T', '\x4', 'U', + '\t', 'U', '\x4', 'V', '\t', 'V', '\x4', 'W', '\t', 'W', '\x4', 'X', '\t', + 'X', '\x4', 'Y', '\t', 'Y', '\x4', 'Z', '\t', 'Z', '\x4', '[', '\t', '[', + '\x4', '\\', '\t', '\\', '\x4', ']', '\t', ']', '\x4', '^', '\t', '^', + '\x4', '_', '\t', '_', '\x4', '`', '\t', '`', '\x4', '\x61', '\t', '\x61', + '\x4', '\x62', '\t', '\x62', '\x4', '\x63', '\t', '\x63', '\x4', '\x64', + '\t', '\x64', '\x4', '\x65', '\t', '\x65', '\x4', '\x66', '\t', '\x66', + '\x4', 'g', '\t', 'g', '\x4', 'h', '\t', 'h', '\x4', 'i', '\t', 'i', '\x4', + 'j', '\t', 'j', '\x4', 'k', '\t', 'k', '\x4', 'l', '\t', 'l', '\x4', 'm', + '\t', 'm', '\x4', 'n', '\t', 'n', '\x4', 'o', '\t', 'o', '\x4', 'p', '\t', + 'p', '\x4', 'q', '\t', 'q', '\x4', 'r', '\t', 'r', '\x4', 's', '\t', 's', + '\x4', 't', '\t', 't', '\x4', 'u', '\t', 'u', '\x4', 'v', '\t', 'v', '\x4', + 'w', '\t', 'w', '\x4', 'x', '\t', 'x', '\x4', 'y', '\t', 'y', '\x4', 'z', + '\t', 'z', '\x4', '{', '\t', '{', '\x4', '|', '\t', '|', '\x4', '}', '\t', + '}', '\x4', '~', '\t', '~', '\x4', '\x7F', '\t', '\x7F', '\x4', '\x80', + '\t', '\x80', '\x4', '\x81', '\t', '\x81', '\x4', '\x82', '\t', '\x82', + '\x4', '\x83', '\t', '\x83', '\x4', '\x84', '\t', '\x84', '\x4', '\x85', + '\t', '\x85', '\x4', '\x86', '\t', '\x86', '\x4', '\x87', '\t', '\x87', + '\x4', '\x88', '\t', '\x88', '\x4', '\x89', '\t', '\x89', '\x4', '\x8A', + '\t', '\x8A', '\x4', '\x8B', '\t', '\x8B', '\x4', '\x8C', '\t', '\x8C', + '\x4', '\x8D', '\t', '\x8D', '\x4', '\x8E', '\t', '\x8E', '\x4', '\x8F', + '\t', '\x8F', '\x4', '\x90', '\t', '\x90', '\x4', '\x91', '\t', '\x91', + '\x4', '\x92', '\t', '\x92', '\x4', '\x93', '\t', '\x93', '\x4', '\x94', + '\t', '\x94', '\x4', '\x95', '\t', '\x95', '\x4', '\x96', '\t', '\x96', + '\x4', '\x97', '\t', '\x97', '\x4', '\x98', '\t', '\x98', '\x4', '\x99', + '\t', '\x99', '\x4', '\x9A', '\t', '\x9A', '\x4', '\x9B', '\t', '\x9B', + '\x4', '\x9C', '\t', '\x9C', '\x4', '\x9D', '\t', '\x9D', '\x4', '\x9E', + '\t', '\x9E', '\x4', '\x9F', '\t', '\x9F', '\x4', '\xA0', '\t', '\xA0', + '\x4', '\xA1', '\t', '\xA1', '\x4', '\xA2', '\t', '\xA2', '\x4', '\xA3', + '\t', '\xA3', '\x4', '\xA4', '\t', '\xA4', '\x4', '\xA5', '\t', '\xA5', + '\x4', '\xA6', '\t', '\xA6', '\x4', '\xA7', '\t', '\xA7', '\x4', '\xA8', + '\t', '\xA8', '\x4', '\xA9', '\t', '\xA9', '\x4', '\xAA', '\t', '\xAA', + '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', + '\x3', '\x2', '\x3', '\x2', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', + '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', + '\x3', '\x3', '\x3', '\x3', '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', + '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', '\x3', '\x5', + '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', + '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', + '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', + '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\b', '\x3', '\b', + '\x3', '\b', '\x3', '\b', '\x3', '\t', '\x3', '\t', '\x3', '\t', '\x3', + '\t', '\x3', '\t', '\x3', '\n', '\x3', '\n', '\x3', '\n', '\x3', '\n', + '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', '\f', '\x3', + '\f', '\x3', '\f', '\x3', '\f', '\x3', '\r', '\x3', '\r', '\x3', '\r', + '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', + '\r', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', + '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', + '\x3', '\xF', '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', + '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', '\x3', '\x11', '\x3', '\x11', + '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', + '\x3', '\x11', '\x3', '\x11', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', + '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', + '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', + '\x3', '\x13', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', + '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', + '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', + '\x3', '\x14', '\x3', '\x14', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', + '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', + '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x16', '\x3', '\x16', + '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', + '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x17', '\x3', '\x17', + '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', + '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x18', + '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', + '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', + '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x19', '\x3', '\x19', + '\x3', '\x19', '\x3', '\x19', '\x3', '\x19', '\x3', '\x1A', '\x3', '\x1A', + '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1B', + '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1C', + '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', + '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1D', + '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', + '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1E', + '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', + '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', + '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1F', + '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', + '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', + '\x3', ' ', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', + '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '\"', '\x3', '\"', + '\x3', '\"', '\x3', '\"', '\x3', '\"', '\x3', '#', '\x3', '#', '\x3', + '#', '\x3', '#', '\x3', '#', '\x3', '#', '\x3', '#', '\x3', '$', '\x3', + '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', + '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '%', '\x3', + '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', + '%', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', + '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', + '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '(', '\x3', '(', '\x3', + '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', + '(', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', + ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', '*', '\x3', '*', '\x3', + '*', '\x3', '*', '\x3', '*', '\x3', '*', '\x3', '*', '\x3', '+', '\x3', + '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', + '+', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', + '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', + '-', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', + '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', + '/', '\x3', '/', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', + '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', + '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x31', '\x3', '\x31', + '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', + '\x3', '\x31', '\x3', '\x31', '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', + '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x33', + '\x3', '\x33', '\x3', '\x33', '\x3', '\x33', '\x3', '\x33', '\x3', '\x34', + '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', + '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x35', '\x3', '\x35', + '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', + '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', + '\x3', '\x36', '\x3', '\x36', '\x3', '\x36', '\x3', '\x37', '\x3', '\x37', + '\x3', '\x37', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', + '\x3', '\x38', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', + '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', + '\x3', ':', '\x3', ':', '\x3', ':', '\x3', ':', '\x3', ';', '\x3', ';', + '\x3', ';', '\x3', ';', '\x3', ';', '\x3', '<', '\x3', '<', '\x3', '<', + '\x3', '<', '\x3', '=', '\x3', '=', '\x3', '=', '\x3', '=', '\x3', '=', + '\x3', '=', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '?', + '\x3', '?', '\x3', '?', '\x3', '?', '\x3', '?', '\x3', '@', '\x3', '@', + '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '\x41', '\x3', + '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', + '\x42', '\x3', '\x42', '\x3', '\x43', '\x3', '\x43', '\x3', '\x43', '\x3', + '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x45', '\x3', + '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', + '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', + 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'H', '\x3', 'H', '\x3', + 'H', '\x3', 'H', '\x3', 'H', '\x3', 'H', '\x3', 'I', '\x3', 'I', '\x3', + 'I', '\x3', 'I', '\x3', 'I', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x3', + 'J', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x3', 'K', '\x3', 'K', '\x3', + 'K', '\x3', 'K', '\x3', 'K', '\x3', 'L', '\x3', 'L', '\x3', 'L', '\x3', + 'L', '\x3', 'L', '\x3', 'L', '\x3', 'M', '\x3', 'M', '\x3', 'M', '\x3', + 'M', '\x3', 'M', '\x3', 'N', '\x3', 'N', '\x3', 'N', '\x3', 'N', '\x3', + 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', + 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', + 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', + 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', + 'P', '\x3', 'P', '\x3', 'P', '\x3', 'P', '\x3', 'P', '\x3', 'Q', '\x3', + 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'R', '\x3', + 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', + 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', + 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', + 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', + 'R', '\x3', 'S', '\x3', 'S', '\x3', 'S', '\x3', 'T', '\x3', 'T', '\x3', + 'T', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', + 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', + 'V', '\x3', 'V', '\x3', 'V', '\x3', 'V', '\x3', 'W', '\x3', 'W', '\x3', + 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', + 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'X', '\x3', + 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'Y', '\x3', + 'Y', '\x3', 'Y', '\x3', 'Y', '\x3', 'Y', '\x3', 'Z', '\x3', 'Z', '\x3', + 'Z', '\x3', 'Z', '\x3', 'Z', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', + '[', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', '\\', '\x3', + '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', + '\x3', '\\', '\x3', ']', '\x3', ']', '\x3', ']', '\x3', ']', '\x3', ']', + '\x3', ']', '\x3', ']', '\x3', '^', '\x3', '^', '\x3', '^', '\x3', '^', + '\x3', '^', '\x3', '^', '\x3', '_', '\x3', '_', '\x3', '_', '\x3', '_', + '\x3', '_', '\x3', '_', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', + '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '\x61', + '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', + '\x3', '\x61', '\x3', '\x61', '\x3', '\x62', '\x3', '\x62', '\x3', '\x62', + '\x3', '\x62', '\x3', '\x62', '\x3', '\x62', '\x3', '\x63', '\x3', '\x63', + '\x3', '\x63', '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', + '\x3', '\x64', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', + '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', + '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x66', '\x3', '\x66', + '\x3', '\x66', '\x3', '\x66', '\x3', 'g', '\x3', 'g', '\x3', 'g', '\x3', + 'g', '\x3', 'g', '\x3', 'g', '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', + 'i', '\x3', 'i', '\x3', 'i', '\x3', 'j', '\x3', 'j', '\x3', 'j', '\x3', + 'j', '\x3', 'j', '\x3', 'j', '\x3', 'j', '\x3', 'k', '\x3', 'k', '\x3', + 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'l', '\x3', + 'l', '\x3', 'l', '\x3', 'l', '\x3', 'l', '\x3', 'm', '\x3', 'm', '\x3', + 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'n', '\x3', 'n', '\x3', + 'n', '\x3', 'n', '\x3', 'n', '\x3', 'n', '\x3', 'n', '\x3', 'o', '\x3', + 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'p', '\x3', + 'p', '\x3', 'p', '\x3', 'p', '\x3', 'q', '\x3', 'q', '\x3', 'q', '\x3', + 'q', '\x3', 'q', '\x3', 'q', '\x3', 'r', '\x3', 'r', '\x3', 'r', '\x3', + 'r', '\x3', 'r', '\x5', 'r', '\x46A', '\n', 'r', '\x3', 's', '\x3', 's', + '\x3', 't', '\x3', 't', '\x5', 't', '\x470', '\n', 't', '\x3', 'u', '\x6', + 'u', '\x473', '\n', 'u', '\r', 'u', '\xE', 'u', '\x474', '\x3', 'v', '\x3', + 'v', '\x3', 'v', '\x3', 'v', '\x3', 'v', '\x5', 'v', '\x47C', '\n', 'v', + '\x3', 'w', '\x3', 'w', '\x3', 'x', '\x3', 'x', '\x5', 'x', '\x482', '\n', + 'x', '\x3', 'y', '\x6', 'y', '\x485', '\n', 'y', '\r', 'y', '\xE', 'y', + '\x486', '\x3', 'z', '\x3', 'z', '\a', 'z', '\x48B', '\n', 'z', '\f', + 'z', '\xE', 'z', '\x48E', '\v', 'z', '\x3', '{', '\x6', '{', '\x491', + '\n', '{', '\r', '{', '\xE', '{', '\x492', '\x3', '|', '\x3', '|', '\x3', + '|', '\x3', '|', '\x3', '|', '\x5', '|', '\x49A', '\n', '|', '\x3', '}', + '\x3', '}', '\x3', '~', '\x3', '~', '\x5', '~', '\x4A0', '\n', '~', '\x3', + '\x7F', '\x6', '\x7F', '\x4A3', '\n', '\x7F', '\r', '\x7F', '\xE', '\x7F', + '\x4A4', '\x3', '\x80', '\x3', '\x80', '\x5', '\x80', '\x4A9', '\n', '\x80', + '\x3', '\x80', '\x3', '\x80', '\x3', '\x81', '\x6', '\x81', '\x4AE', '\n', + '\x81', '\r', '\x81', '\xE', '\x81', '\x4AF', '\x3', '\x82', '\x3', '\x82', + '\x5', '\x82', '\x4B4', '\n', '\x82', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', + '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x5', + '\x83', '\x4D6', '\n', '\x83', '\x3', '\x84', '\x3', '\x84', '\x5', '\x84', + '\x4DA', '\n', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', '\x5', + '\x84', '\x4DF', '\n', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', + '\x5', '\x84', '\x4E4', '\n', '\x84', '\x3', '\x85', '\x5', '\x85', '\x4E7', + '\n', '\x85', '\x3', '\x86', '\x3', '\x86', '\x5', '\x86', '\x4EB', '\n', + '\x86', '\x3', '\x87', '\x6', '\x87', '\x4EE', '\n', '\x87', '\r', '\x87', + '\xE', '\x87', '\x4EF', '\x3', '\x88', '\x3', '\x88', '\x3', '\x88', '\x3', + '\x89', '\x6', '\x89', '\x4F6', '\n', '\x89', '\r', '\x89', '\xE', '\x89', + '\x4F7', '\x3', '\x89', '\x3', '\x89', '\x3', '\x8A', '\x3', '\x8A', '\x3', + '\x8B', '\x3', '\x8B', '\x3', '\x8C', '\x3', '\x8C', '\x3', '\x8D', '\x3', + '\x8D', '\x3', '\x8E', '\x3', '\x8E', '\x3', '\x8F', '\x3', '\x8F', '\x3', + '\x90', '\x3', '\x90', '\x3', '\x91', '\x3', '\x91', '\x3', '\x92', '\x3', + '\x92', '\x3', '\x93', '\x3', '\x93', '\x3', '\x94', '\x3', '\x94', '\x3', + '\x95', '\x3', '\x95', '\x3', '\x96', '\x3', '\x96', '\x3', '\x97', '\x3', + '\x97', '\x3', '\x98', '\x3', '\x98', '\x3', '\x99', '\x3', '\x99', '\x3', + '\x9A', '\x3', '\x9A', '\x3', '\x9B', '\x3', '\x9B', '\x3', '\x9C', '\x3', + '\x9C', '\x3', '\x9D', '\x3', '\x9D', '\x3', '\x9E', '\x3', '\x9E', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\xA0', '\x6', '\xA0', '\x529', '\n', '\xA0', + '\r', '\xA0', '\xE', '\xA0', '\x52A', '\x3', '\xA1', '\x3', '\xA1', '\x5', + '\xA1', '\x52F', '\n', '\xA1', '\x3', '\xA1', '\x3', '\xA1', '\x3', '\xA1', + '\x3', '\xA1', '\x3', '\xA1', '\x3', '\xA1', '\x6', '\xA1', '\x537', '\n', + '\xA1', '\r', '\xA1', '\xE', '\xA1', '\x538', '\x3', '\xA1', '\x3', '\xA1', + '\x6', '\xA1', '\x53D', '\n', '\xA1', '\r', '\xA1', '\xE', '\xA1', '\x53E', + '\x5', '\xA1', '\x541', '\n', '\xA1', '\x3', '\xA2', '\x5', '\xA2', '\x544', + '\n', '\xA2', '\x3', '\xA3', '\x5', '\xA3', '\x547', '\n', '\xA3', '\x3', + '\xA4', '\x6', '\xA4', '\x54A', '\n', '\xA4', '\r', '\xA4', '\xE', '\xA4', + '\x54B', '\x3', '\xA5', '\x5', '\xA5', '\x54F', '\n', '\xA5', '\x3', '\xA6', + '\x5', '\xA6', '\x552', '\n', '\xA6', '\x3', '\xA7', '\x3', '\xA7', '\x3', + '\xA8', '\x3', '\xA8', '\x5', '\xA8', '\x558', '\n', '\xA8', '\x3', '\xA9', + '\x3', '\xA9', '\x3', '\xA9', '\x3', '\xAA', '\x3', '\xAA', '\x3', '\xAA', + '\x3', '\xAA', '\a', '\xAA', '\x561', '\n', '\xAA', '\f', '\xAA', '\xE', + '\xAA', '\x564', '\v', '\xAA', '\x2', '\x2', '\xAB', '\x3', '\x3', '\x5', + '\x4', '\a', '\x5', '\t', '\x6', '\v', '\a', '\r', '\b', '\xF', '\t', + '\x11', '\n', '\x13', '\v', '\x15', '\f', '\x17', '\r', '\x19', '\xE', + '\x1B', '\xF', '\x1D', '\x10', '\x1F', '\x11', '!', '\x12', '#', '\x13', + '%', '\x14', '\'', '\x15', ')', '\x16', '+', '\x17', '-', '\x18', '/', + '\x19', '\x31', '\x1A', '\x33', '\x1B', '\x35', '\x1C', '\x37', '\x1D', + '\x39', '\x1E', ';', '\x1F', '=', ' ', '?', '!', '\x41', '\"', '\x43', + '#', '\x45', '$', 'G', '%', 'I', '&', 'K', '\'', 'M', '(', 'O', ')', 'Q', + '*', 'S', '+', 'U', ',', 'W', '-', 'Y', '.', '[', '/', ']', '\x30', '_', + '\x31', '\x61', '\x32', '\x63', '\x33', '\x65', '\x34', 'g', '\x35', 'i', + '\x36', 'k', '\x37', 'm', '\x38', 'o', '\x39', 'q', ':', 's', ';', 'u', + '<', 'w', '=', 'y', '>', '{', '?', '}', '@', '\x7F', '\x41', '\x81', '\x42', + '\x83', '\x43', '\x85', '\x44', '\x87', '\x45', '\x89', '\x46', '\x8B', + 'G', '\x8D', 'H', '\x8F', 'I', '\x91', 'J', '\x93', 'K', '\x95', 'L', + '\x97', 'M', '\x99', 'N', '\x9B', 'O', '\x9D', 'P', '\x9F', 'Q', '\xA1', + 'R', '\xA3', 'S', '\xA5', 'T', '\xA7', 'U', '\xA9', 'V', '\xAB', 'W', + '\xAD', 'X', '\xAF', 'Y', '\xB1', 'Z', '\xB3', '[', '\xB5', '\\', '\xB7', + ']', '\xB9', '^', '\xBB', '_', '\xBD', '`', '\xBF', '\x61', '\xC1', '\x62', + '\xC3', '\x63', '\xC5', '\x64', '\xC7', '\x65', '\xC9', '\x66', '\xCB', + 'g', '\xCD', 'h', '\xCF', 'i', '\xD1', 'j', '\xD3', 'k', '\xD5', 'l', + '\xD7', 'm', '\xD9', 'n', '\xDB', 'o', '\xDD', 'p', '\xDF', 'q', '\xE1', + 'r', '\xE3', 's', '\xE5', '\x2', '\xE7', '\x2', '\xE9', '\x2', '\xEB', + 't', '\xED', '\x2', '\xEF', '\x2', '\xF1', '\x2', '\xF3', 'u', '\xF5', + 'v', '\xF7', 'w', '\xF9', '\x2', '\xFB', '\x2', '\xFD', '\x2', '\xFF', + 'x', '\x101', '\x2', '\x103', '\x2', '\x105', '\x2', '\x107', 'y', '\x109', + '\x2', '\x10B', '\x2', '\x10D', '\x2', '\x10F', 'z', '\x111', '{', '\x113', + '|', '\x115', '}', '\x117', '~', '\x119', '\x7F', '\x11B', '\x80', '\x11D', + '\x81', '\x11F', '\x82', '\x121', '\x83', '\x123', '\x84', '\x125', '\x85', + '\x127', '\x86', '\x129', '\x87', '\x12B', '\x88', '\x12D', '\x89', '\x12F', + '\x8A', '\x131', '\x8B', '\x133', '\x8C', '\x135', '\x8D', '\x137', '\x8E', + '\x139', '\x8F', '\x13B', '\x90', '\x13D', '\x91', '\x13F', '\x92', '\x141', + '\x93', '\x143', '\x2', '\x145', '\x2', '\x147', '\x2', '\x149', '\x2', + '\x14B', '\x2', '\x14D', '\x94', '\x14F', '\x95', '\x151', '\x96', '\x153', + '\x97', '\x3', '\x2', '\r', '\x3', '\x2', '\x32', '\x33', '\x3', '\x2', + '\x32', '\x39', '\x3', '\x2', '\x32', ';', '\x4', '\x2', '\x32', ';', + '\x61', '\x61', '\x6', '\x2', '\f', '\f', '\xF', '\xF', '$', '$', '^', + '^', '\t', '\x2', '$', '$', ')', ')', '\x32', '\x32', '^', '^', 'p', 'p', + 't', 't', 'v', 'v', '\a', '\x2', '\x32', ';', '\x302', '\x371', '\x1DC2', + '\x1E01', '\x20D2', '\x2101', '\xFE22', '\xFE31', '\x5', '\x2', '\x2', + '\x2', '\v', '\xF', '\"', '\"', '!', '\x2', '#', '#', '\'', '(', ',', + '-', '/', '/', '\x31', '\x31', '>', '\x41', '`', '`', '~', '~', '\x80', + '\x80', '\xA3', '\xA9', '\xAB', '\xAB', '\xAD', '\xAE', '\xB0', '\xB0', + '\xB2', '\xB3', '\xB8', '\xB8', '\xBD', '\xBD', '\xC1', '\xC1', '\xD9', + '\xD9', '\xF9', '\xF9', '\x2018', '\x2019', '\x2022', '\x2029', '\x2032', + '\x2040', '\x2043', '\x2055', '\x2057', '\x2060', '\x2192', '\x2401', + '\x2502', '\x2777', '\x2796', '\x2C01', '\x2E02', '\x2E81', '\x3003', + '\x3005', '\x300A', '\x3022', '\x3032', '\x3032', '\"', '\x2', '#', '#', + '\'', '(', ',', '-', '/', '/', '\x31', '\x31', '>', '?', '\x41', '\x41', + '`', '`', '~', '~', '\x80', '\x80', '\xA3', '\xA9', '\xAB', '\xAB', '\xAD', + '\xAE', '\xB0', '\xB0', '\xB2', '\xB3', '\xB8', '\xB8', '\xBD', '\xBD', + '\xC1', '\xC1', '\xD9', '\xD9', '\xF9', '\xF9', '\x2018', '\x2019', '\x2022', + '\x2029', '\x2032', '\x2040', '\x2043', '\x2055', '\x2057', '\x2060', + '\x2192', '\x2401', '\x2502', '\x2777', '\x2796', '\x2C01', '\x2E02', + '\x2E81', '\x3003', '\x3005', '\x300A', '\x3022', '\x3032', '\x3032', + '\x4', '\x2', '\f', '\f', '\xF', '\xF', '\x5', '\x33', '\x2', '\x43', + '\x2', '\\', '\x2', '\x61', '\x2', '\x61', '\x2', '\x63', '\x2', '|', + '\x2', '\xAA', '\x2', '\xAA', '\x2', '\xAC', '\x2', '\xAC', '\x2', '\xAF', + '\x2', '\xAF', '\x2', '\xB1', '\x2', '\xB1', '\x2', '\xB4', '\x2', '\xB7', + '\x2', '\xB9', '\x2', '\xBC', '\x2', '\xBE', '\x2', '\xC0', '\x2', '\xC2', + '\x2', '\xD8', '\x2', '\xDA', '\x2', '\xF8', '\x2', '\xFA', '\x2', '\x301', + '\x2', '\x372', '\x2', '\x1681', '\x2', '\x1683', '\x2', '\x180F', '\x2', + '\x1811', '\x2', '\x1DC1', '\x2', '\x1E02', '\x2', '\x2001', '\x2', '\x200D', + '\x2', '\x200F', '\x2', '\x202C', '\x2', '\x2030', '\x2', '\x2041', '\x2', + '\x2042', '\x2', '\x2056', '\x2', '\x2056', '\x2', '\x2062', '\x2', '\x20D1', + '\x2', '\x2102', '\x2', '\x2191', '\x2', '\x2462', '\x2', '\x2501', '\x2', + '\x2778', '\x2', '\x2795', '\x2', '\x2C02', '\x2', '\x2E01', '\x2', '\x2E82', + '\x2', '\x3001', '\x2', '\x3006', '\x2', '\x3009', '\x2', '\x3023', '\x2', + '\x3031', '\x2', '\x3033', '\x2', '\xD801', '\x2', '\xF902', '\x2', '\xFD3F', + '\x2', '\xFD42', '\x2', '\xFDD1', '\x2', '\xFDF2', '\x2', '\xFE21', '\x2', + '\xFE32', '\x2', '\xFE46', '\x2', '\xFE49', '\x2', '\xFFFF', '\x2', '\x2', + '\x3', '\xFFFF', '\x3', '\x2', '\x4', '\xFFFF', '\x4', '\x2', '\x5', '\xFFFF', + '\x5', '\x2', '\x6', '\xFFFF', '\x6', '\x2', '\a', '\xFFFF', '\a', '\x2', + '\b', '\xFFFF', '\b', '\x2', '\t', '\xFFFF', '\t', '\x2', '\n', '\xFFFF', + '\n', '\x2', '\v', '\xFFFF', '\v', '\x2', '\f', '\xFFFF', '\f', '\x2', + '\r', '\xFFFF', '\r', '\x2', '\xE', '\xFFFF', '\xE', '\x2', '\xF', '\xFFFF', + '\xF', '\x2', '\x10', '\xFFFF', '\x10', '*', '\x2', '#', '\x2', '#', '\x2', + '\'', '\x2', '(', '\x2', ',', '\x2', '-', '\x2', '/', '\x2', '/', '\x2', + '\x31', '\x2', '\x31', '\x2', '>', '\x2', '?', '\x2', '\x41', '\x2', '\x41', + '\x2', '`', '\x2', '`', '\x2', '~', '\x2', '~', '\x2', '\x80', '\x2', + '\x80', '\x2', '\xA3', '\x2', '\xA9', '\x2', '\xAB', '\x2', '\xAB', '\x2', + '\xAD', '\x2', '\xAE', '\x2', '\xB0', '\x2', '\xB0', '\x2', '\xB2', '\x2', + '\xB3', '\x2', '\xB8', '\x2', '\xB8', '\x2', '\xBD', '\x2', '\xBD', '\x2', + '\xC1', '\x2', '\xC1', '\x2', '\xD9', '\x2', '\xD9', '\x2', '\xF9', '\x2', + '\xF9', '\x2', '\x302', '\x2', '\x302', '\x2', '\x371', '\x2', '\x371', + '\x2', '\x1DC2', '\x2', '\x1E01', '\x2', '\x2015', '\x2', '\x2015', '\x2', + '\x2018', '\x2', '\x2019', '\x2', '\x2022', '\x2', '\x2029', '\x2', '\x2032', + '\x2', '\x2040', '\x2', '\x2043', '\x2', '\x2055', '\x2', '\x2057', '\x2', + '\x2060', '\x2', '\x20D2', '\x2', '\x2101', '\x2', '\x2192', '\x2', '\x2401', + '\x2', '\x2502', '\x2', '\x2777', '\x2', '\x2796', '\x2', '\x2C01', '\x2', + '\x2E02', '\x2', '\x2E81', '\x2', '\x3003', '\x2', '\x3005', '\x2', '\x300A', + '\x2', '\x3022', '\x2', '\x3032', '\x2', '\x3032', '\x2', '\xFE02', '\x2', + '\xFE11', '\x2', '\xFE22', '\x2', '\xFE31', '\x2', '\x102', '\x10', '\x1F1', + '\x10', ')', '\x2', '#', '\x2', '#', '\x2', '\'', '\x2', '(', '\x2', ',', + '\x2', '-', '\x2', '/', '\x2', '/', '\x2', '\x31', '\x2', '\x31', '\x2', + '>', '\x2', '\x41', '\x2', '`', '\x2', '`', '\x2', '~', '\x2', '~', '\x2', + '\x80', '\x2', '\x80', '\x2', '\xA3', '\x2', '\xA9', '\x2', '\xAB', '\x2', + '\xAB', '\x2', '\xAD', '\x2', '\xAE', '\x2', '\xB0', '\x2', '\xB0', '\x2', + '\xB2', '\x2', '\xB3', '\x2', '\xB8', '\x2', '\xB8', '\x2', '\xBD', '\x2', + '\xBD', '\x2', '\xC1', '\x2', '\xC1', '\x2', '\xD9', '\x2', '\xD9', '\x2', + '\xF9', '\x2', '\xF9', '\x2', '\x302', '\x2', '\x302', '\x2', '\x371', + '\x2', '\x371', '\x2', '\x1DC2', '\x2', '\x1E01', '\x2', '\x2015', '\x2', + '\x2015', '\x2', '\x2018', '\x2', '\x2019', '\x2', '\x2022', '\x2', '\x2029', + '\x2', '\x2032', '\x2', '\x2040', '\x2', '\x2043', '\x2', '\x2055', '\x2', + '\x2057', '\x2', '\x2060', '\x2', '\x20D2', '\x2', '\x2101', '\x2', '\x2192', + '\x2', '\x2401', '\x2', '\x2502', '\x2', '\x2777', '\x2', '\x2796', '\x2', + '\x2C01', '\x2', '\x2E02', '\x2', '\x2E81', '\x2', '\x3003', '\x2', '\x3005', + '\x2', '\x300A', '\x2', '\x3022', '\x2', '\x3032', '\x2', '\x3032', '\x2', + '\xFE02', '\x2', '\xFE11', '\x2', '\xFE22', '\x2', '\xFE31', '\x2', '\x102', + '\x10', '\x1F1', '\x10', '\x572', '\x2', '\x3', '\x3', '\x2', '\x2', '\x2', + '\x2', '\x5', '\x3', '\x2', '\x2', '\x2', '\x2', '\a', '\x3', '\x2', '\x2', + '\x2', '\x2', '\t', '\x3', '\x2', '\x2', '\x2', '\x2', '\v', '\x3', '\x2', + '\x2', '\x2', '\x2', '\r', '\x3', '\x2', '\x2', '\x2', '\x2', '\xF', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x11', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x13', '\x3', '\x2', '\x2', '\x2', '\x2', '\x15', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x17', '\x3', '\x2', '\x2', '\x2', '\x2', '\x19', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x1B', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x1D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x1F', '\x3', '\x2', '\x2', + '\x2', '\x2', '!', '\x3', '\x2', '\x2', '\x2', '\x2', '#', '\x3', '\x2', + '\x2', '\x2', '\x2', '%', '\x3', '\x2', '\x2', '\x2', '\x2', '\'', '\x3', + '\x2', '\x2', '\x2', '\x2', ')', '\x3', '\x2', '\x2', '\x2', '\x2', '+', + '\x3', '\x2', '\x2', '\x2', '\x2', '-', '\x3', '\x2', '\x2', '\x2', '\x2', + '/', '\x3', '\x2', '\x2', '\x2', '\x2', '\x31', '\x3', '\x2', '\x2', '\x2', + '\x2', '\x33', '\x3', '\x2', '\x2', '\x2', '\x2', '\x35', '\x3', '\x2', + '\x2', '\x2', '\x2', '\x37', '\x3', '\x2', '\x2', '\x2', '\x2', '\x39', + '\x3', '\x2', '\x2', '\x2', '\x2', ';', '\x3', '\x2', '\x2', '\x2', '\x2', + '=', '\x3', '\x2', '\x2', '\x2', '\x2', '?', '\x3', '\x2', '\x2', '\x2', + '\x2', '\x41', '\x3', '\x2', '\x2', '\x2', '\x2', '\x43', '\x3', '\x2', + '\x2', '\x2', '\x2', '\x45', '\x3', '\x2', '\x2', '\x2', '\x2', 'G', '\x3', + '\x2', '\x2', '\x2', '\x2', 'I', '\x3', '\x2', '\x2', '\x2', '\x2', 'K', + '\x3', '\x2', '\x2', '\x2', '\x2', 'M', '\x3', '\x2', '\x2', '\x2', '\x2', + 'O', '\x3', '\x2', '\x2', '\x2', '\x2', 'Q', '\x3', '\x2', '\x2', '\x2', + '\x2', 'S', '\x3', '\x2', '\x2', '\x2', '\x2', 'U', '\x3', '\x2', '\x2', + '\x2', '\x2', 'W', '\x3', '\x2', '\x2', '\x2', '\x2', 'Y', '\x3', '\x2', + '\x2', '\x2', '\x2', '[', '\x3', '\x2', '\x2', '\x2', '\x2', ']', '\x3', + '\x2', '\x2', '\x2', '\x2', '_', '\x3', '\x2', '\x2', '\x2', '\x2', '\x61', + '\x3', '\x2', '\x2', '\x2', '\x2', '\x63', '\x3', '\x2', '\x2', '\x2', + '\x2', '\x65', '\x3', '\x2', '\x2', '\x2', '\x2', 'g', '\x3', '\x2', '\x2', + '\x2', '\x2', 'i', '\x3', '\x2', '\x2', '\x2', '\x2', 'k', '\x3', '\x2', + '\x2', '\x2', '\x2', 'm', '\x3', '\x2', '\x2', '\x2', '\x2', 'o', '\x3', + '\x2', '\x2', '\x2', '\x2', 'q', '\x3', '\x2', '\x2', '\x2', '\x2', 's', + '\x3', '\x2', '\x2', '\x2', '\x2', 'u', '\x3', '\x2', '\x2', '\x2', '\x2', + 'w', '\x3', '\x2', '\x2', '\x2', '\x2', 'y', '\x3', '\x2', '\x2', '\x2', + '\x2', '{', '\x3', '\x2', '\x2', '\x2', '\x2', '}', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x7F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x81', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x83', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x85', '\x3', '\x2', '\x2', '\x2', '\x2', '\x87', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x89', '\x3', '\x2', '\x2', '\x2', '\x2', '\x8B', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x8D', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x8F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x91', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x93', '\x3', '\x2', '\x2', '\x2', '\x2', '\x95', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x97', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x99', '\x3', '\x2', '\x2', '\x2', '\x2', '\x9B', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x9D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x9F', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xA1', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xA3', '\x3', '\x2', '\x2', '\x2', '\x2', '\xA5', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xA7', '\x3', '\x2', '\x2', '\x2', '\x2', '\xA9', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xAB', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xAD', '\x3', '\x2', '\x2', '\x2', '\x2', '\xAF', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xB1', '\x3', '\x2', '\x2', '\x2', '\x2', '\xB3', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xB5', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xB7', '\x3', '\x2', '\x2', '\x2', '\x2', '\xB9', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xBB', '\x3', '\x2', '\x2', '\x2', '\x2', '\xBD', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xBF', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xC1', '\x3', '\x2', '\x2', '\x2', '\x2', '\xC3', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xC5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xC7', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xC9', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xCB', '\x3', '\x2', '\x2', '\x2', '\x2', '\xCD', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xCF', '\x3', '\x2', '\x2', '\x2', '\x2', '\xD1', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xD3', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xD5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xD7', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xD9', '\x3', '\x2', '\x2', '\x2', '\x2', '\xDB', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xDD', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xDF', '\x3', '\x2', '\x2', '\x2', '\x2', '\xE1', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xE3', '\x3', '\x2', '\x2', '\x2', '\x2', '\xEB', '\x3', + '\x2', '\x2', '\x2', '\x2', '\xF3', '\x3', '\x2', '\x2', '\x2', '\x2', + '\xF5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xF7', '\x3', '\x2', '\x2', + '\x2', '\x2', '\xFF', '\x3', '\x2', '\x2', '\x2', '\x2', '\x107', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x10F', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x111', '\x3', '\x2', '\x2', '\x2', '\x2', '\x113', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x115', '\x3', '\x2', '\x2', '\x2', '\x2', '\x117', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x119', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x11B', '\x3', '\x2', '\x2', '\x2', '\x2', '\x11D', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x11F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x121', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x123', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x125', '\x3', '\x2', '\x2', '\x2', '\x2', '\x127', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x129', '\x3', '\x2', '\x2', '\x2', '\x2', '\x12B', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x12D', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x12F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x131', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x133', '\x3', '\x2', '\x2', '\x2', '\x2', '\x135', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x137', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x139', '\x3', '\x2', '\x2', '\x2', '\x2', '\x13B', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x13D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x13F', '\x3', + '\x2', '\x2', '\x2', '\x2', '\x141', '\x3', '\x2', '\x2', '\x2', '\x2', + '\x14D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x14F', '\x3', '\x2', '\x2', + '\x2', '\x2', '\x151', '\x3', '\x2', '\x2', '\x2', '\x2', '\x153', '\x3', + '\x2', '\x2', '\x2', '\x3', '\x155', '\x3', '\x2', '\x2', '\x2', '\x5', + '\x15C', '\x3', '\x2', '\x2', '\x2', '\a', '\x166', '\x3', '\x2', '\x2', + '\x2', '\t', '\x16D', '\x3', '\x2', '\x2', '\x2', '\v', '\x173', '\x3', + '\x2', '\x2', '\x2', '\r', '\x178', '\x3', '\x2', '\x2', '\x2', '\xF', + '\x181', '\x3', '\x2', '\x2', '\x2', '\x11', '\x185', '\x3', '\x2', '\x2', + '\x2', '\x13', '\x18A', '\x3', '\x2', '\x2', '\x2', '\x15', '\x18E', '\x3', + '\x2', '\x2', '\x2', '\x17', '\x192', '\x3', '\x2', '\x2', '\x2', '\x19', + '\x196', '\x3', '\x2', '\x2', '\x2', '\x1B', '\x19F', '\x3', '\x2', '\x2', + '\x2', '\x1D', '\x1A4', '\x3', '\x2', '\x2', '\x2', '\x1F', '\x1AA', '\x3', + '\x2', '\x2', '\x2', '!', '\x1B1', '\x3', '\x2', '\x2', '\x2', '#', '\x1BA', + '\x3', '\x2', '\x2', '\x2', '%', '\x1C2', '\x3', '\x2', '\x2', '\x2', + '\'', '\x1C8', '\x3', '\x2', '\x2', '\x2', ')', '\x1D8', '\x3', '\x2', + '\x2', '\x2', '+', '\x1E3', '\x3', '\x2', '\x2', '\x2', '-', '\x1ED', + '\x3', '\x2', '\x2', '\x2', '/', '\x1F8', '\x3', '\x2', '\x2', '\x2', + '\x31', '\x206', '\x3', '\x2', '\x2', '\x2', '\x33', '\x20B', '\x3', '\x2', + '\x2', '\x2', '\x35', '\x211', '\x3', '\x2', '\x2', '\x2', '\x37', '\x216', + '\x3', '\x2', '\x2', '\x2', '\x39', '\x220', '\x3', '\x2', '\x2', '\x2', + ';', '\x22A', '\x3', '\x2', '\x2', '\x2', '=', '\x239', '\x3', '\x2', + '\x2', '\x2', '?', '\x23F', '\x3', '\x2', '\x2', '\x2', '\x41', '\x246', + '\x3', '\x2', '\x2', '\x2', '\x43', '\x24F', '\x3', '\x2', '\x2', '\x2', + '\x45', '\x254', '\x3', '\x2', '\x2', '\x2', 'G', '\x25B', '\x3', '\x2', + '\x2', '\x2', 'I', '\x267', '\x3', '\x2', '\x2', '\x2', 'K', '\x26F', + '\x3', '\x2', '\x2', '\x2', 'M', '\x274', '\x3', '\x2', '\x2', '\x2', + 'O', '\x27D', '\x3', '\x2', '\x2', '\x2', 'Q', '\x286', '\x3', '\x2', + '\x2', '\x2', 'S', '\x28F', '\x3', '\x2', '\x2', '\x2', 'U', '\x296', + '\x3', '\x2', '\x2', '\x2', 'W', '\x29E', '\x3', '\x2', '\x2', '\x2', + 'Y', '\x2A3', '\x3', '\x2', '\x2', '\x2', '[', '\x2AA', '\x3', '\x2', + '\x2', '\x2', ']', '\x2AF', '\x3', '\x2', '\x2', '\x2', '_', '\x2B7', + '\x3', '\x2', '\x2', '\x2', '\x61', '\x2C3', '\x3', '\x2', '\x2', '\x2', + '\x63', '\x2CC', '\x3', '\x2', '\x2', '\x2', '\x65', '\x2D3', '\x3', '\x2', + '\x2', '\x2', 'g', '\x2D8', '\x3', '\x2', '\x2', '\x2', 'i', '\x2E1', + '\x3', '\x2', '\x2', '\x2', 'k', '\x2ED', '\x3', '\x2', '\x2', '\x2', + 'm', '\x2F0', '\x3', '\x2', '\x2', '\x2', 'o', '\x2F3', '\x3', '\x2', + '\x2', '\x2', 'q', '\x2F8', '\x3', '\x2', '\x2', '\x2', 's', '\x301', + '\x3', '\x2', '\x2', '\x2', 'u', '\x305', '\x3', '\x2', '\x2', '\x2', + 'w', '\x30A', '\x3', '\x2', '\x2', '\x2', 'y', '\x30E', '\x3', '\x2', + '\x2', '\x2', '{', '\x314', '\x3', '\x2', '\x2', '\x2', '}', '\x318', + '\x3', '\x2', '\x2', '\x2', '\x7F', '\x31D', '\x3', '\x2', '\x2', '\x2', + '\x81', '\x323', '\x3', '\x2', '\x2', '\x2', '\x83', '\x329', '\x3', '\x2', + '\x2', '\x2', '\x85', '\x32B', '\x3', '\x2', '\x2', '\x2', '\x87', '\x32E', + '\x3', '\x2', '\x2', '\x2', '\x89', '\x332', '\x3', '\x2', '\x2', '\x2', + '\x8B', '\x338', '\x3', '\x2', '\x2', '\x2', '\x8D', '\x33D', '\x3', '\x2', + '\x2', '\x2', '\x8F', '\x341', '\x3', '\x2', '\x2', '\x2', '\x91', '\x347', + '\x3', '\x2', '\x2', '\x2', '\x93', '\x34C', '\x3', '\x2', '\x2', '\x2', + '\x95', '\x353', '\x3', '\x2', '\x2', '\x2', '\x97', '\x358', '\x3', '\x2', + '\x2', '\x2', '\x99', '\x35E', '\x3', '\x2', '\x2', '\x2', '\x9B', '\x363', + '\x3', '\x2', '\x2', '\x2', '\x9D', '\x367', '\x3', '\x2', '\x2', '\x2', + '\x9F', '\x37F', '\x3', '\x2', '\x2', '\x2', '\xA1', '\x384', '\x3', '\x2', + '\x2', '\x2', '\xA3', '\x38A', '\x3', '\x2', '\x2', '\x2', '\xA5', '\x3A4', + '\x3', '\x2', '\x2', '\x2', '\xA7', '\x3A7', '\x3', '\x2', '\x2', '\x2', + '\xA9', '\x3AA', '\x3', '\x2', '\x2', '\x2', '\xAB', '\x3B5', '\x3', '\x2', + '\x2', '\x2', '\xAD', '\x3B9', '\x3', '\x2', '\x2', '\x2', '\xAF', '\x3C6', + '\x3', '\x2', '\x2', '\x2', '\xB1', '\x3CC', '\x3', '\x2', '\x2', '\x2', + '\xB3', '\x3D1', '\x3', '\x2', '\x2', '\x2', '\xB5', '\x3D6', '\x3', '\x2', + '\x2', '\x2', '\xB7', '\x3DE', '\x3', '\x2', '\x2', '\x2', '\xB9', '\x3E6', + '\x3', '\x2', '\x2', '\x2', '\xBB', '\x3ED', '\x3', '\x2', '\x2', '\x2', + '\xBD', '\x3F3', '\x3', '\x2', '\x2', '\x2', '\xBF', '\x3F9', '\x3', '\x2', + '\x2', '\x2', '\xC1', '\x402', '\x3', '\x2', '\x2', '\x2', '\xC3', '\x40A', + '\x3', '\x2', '\x2', '\x2', '\xC5', '\x410', '\x3', '\x2', '\x2', '\x2', + '\xC7', '\x413', '\x3', '\x2', '\x2', '\x2', '\xC9', '\x418', '\x3', '\x2', + '\x2', '\x2', '\xCB', '\x424', '\x3', '\x2', '\x2', '\x2', '\xCD', '\x428', + '\x3', '\x2', '\x2', '\x2', '\xCF', '\x42E', '\x3', '\x2', '\x2', '\x2', + '\xD1', '\x431', '\x3', '\x2', '\x2', '\x2', '\xD3', '\x434', '\x3', '\x2', + '\x2', '\x2', '\xD5', '\x43B', '\x3', '\x2', '\x2', '\x2', '\xD7', '\x442', + '\x3', '\x2', '\x2', '\x2', '\xD9', '\x447', '\x3', '\x2', '\x2', '\x2', + '\xDB', '\x44D', '\x3', '\x2', '\x2', '\x2', '\xDD', '\x454', '\x3', '\x2', + '\x2', '\x2', '\xDF', '\x45A', '\x3', '\x2', '\x2', '\x2', '\xE1', '\x45E', + '\x3', '\x2', '\x2', '\x2', '\xE3', '\x464', '\x3', '\x2', '\x2', '\x2', + '\xE5', '\x46B', '\x3', '\x2', '\x2', '\x2', '\xE7', '\x46F', '\x3', '\x2', + '\x2', '\x2', '\xE9', '\x472', '\x3', '\x2', '\x2', '\x2', '\xEB', '\x476', + '\x3', '\x2', '\x2', '\x2', '\xED', '\x47D', '\x3', '\x2', '\x2', '\x2', + '\xEF', '\x481', '\x3', '\x2', '\x2', '\x2', '\xF1', '\x484', '\x3', '\x2', + '\x2', '\x2', '\xF3', '\x488', '\x3', '\x2', '\x2', '\x2', '\xF5', '\x490', + '\x3', '\x2', '\x2', '\x2', '\xF7', '\x494', '\x3', '\x2', '\x2', '\x2', + '\xF9', '\x49B', '\x3', '\x2', '\x2', '\x2', '\xFB', '\x49F', '\x3', '\x2', + '\x2', '\x2', '\xFD', '\x4A2', '\x3', '\x2', '\x2', '\x2', '\xFF', '\x4A6', + '\x3', '\x2', '\x2', '\x2', '\x101', '\x4AD', '\x3', '\x2', '\x2', '\x2', + '\x103', '\x4B3', '\x3', '\x2', '\x2', '\x2', '\x105', '\x4D5', '\x3', + '\x2', '\x2', '\x2', '\x107', '\x4E3', '\x3', '\x2', '\x2', '\x2', '\x109', + '\x4E6', '\x3', '\x2', '\x2', '\x2', '\x10B', '\x4EA', '\x3', '\x2', '\x2', + '\x2', '\x10D', '\x4ED', '\x3', '\x2', '\x2', '\x2', '\x10F', '\x4F1', + '\x3', '\x2', '\x2', '\x2', '\x111', '\x4F5', '\x3', '\x2', '\x2', '\x2', + '\x113', '\x4FB', '\x3', '\x2', '\x2', '\x2', '\x115', '\x4FD', '\x3', + '\x2', '\x2', '\x2', '\x117', '\x4FF', '\x3', '\x2', '\x2', '\x2', '\x119', + '\x501', '\x3', '\x2', '\x2', '\x2', '\x11B', '\x503', '\x3', '\x2', '\x2', + '\x2', '\x11D', '\x505', '\x3', '\x2', '\x2', '\x2', '\x11F', '\x507', + '\x3', '\x2', '\x2', '\x2', '\x121', '\x509', '\x3', '\x2', '\x2', '\x2', + '\x123', '\x50B', '\x3', '\x2', '\x2', '\x2', '\x125', '\x50D', '\x3', + '\x2', '\x2', '\x2', '\x127', '\x50F', '\x3', '\x2', '\x2', '\x2', '\x129', + '\x511', '\x3', '\x2', '\x2', '\x2', '\x12B', '\x513', '\x3', '\x2', '\x2', + '\x2', '\x12D', '\x515', '\x3', '\x2', '\x2', '\x2', '\x12F', '\x517', + '\x3', '\x2', '\x2', '\x2', '\x131', '\x519', '\x3', '\x2', '\x2', '\x2', + '\x133', '\x51B', '\x3', '\x2', '\x2', '\x2', '\x135', '\x51D', '\x3', + '\x2', '\x2', '\x2', '\x137', '\x51F', '\x3', '\x2', '\x2', '\x2', '\x139', + '\x521', '\x3', '\x2', '\x2', '\x2', '\x13B', '\x523', '\x3', '\x2', '\x2', + '\x2', '\x13D', '\x525', '\x3', '\x2', '\x2', '\x2', '\x13F', '\x528', + '\x3', '\x2', '\x2', '\x2', '\x141', '\x540', '\x3', '\x2', '\x2', '\x2', + '\x143', '\x543', '\x3', '\x2', '\x2', '\x2', '\x145', '\x546', '\x3', + '\x2', '\x2', '\x2', '\x147', '\x549', '\x3', '\x2', '\x2', '\x2', '\x149', + '\x54E', '\x3', '\x2', '\x2', '\x2', '\x14B', '\x551', '\x3', '\x2', '\x2', + '\x2', '\x14D', '\x553', '\x3', '\x2', '\x2', '\x2', '\x14F', '\x557', + '\x3', '\x2', '\x2', '\x2', '\x151', '\x559', '\x3', '\x2', '\x2', '\x2', + '\x153', '\x55C', '\x3', '\x2', '\x2', '\x2', '\x155', '\x156', '\a', + 'k', '\x2', '\x2', '\x156', '\x157', '\a', 'o', '\x2', '\x2', '\x157', + '\x158', '\a', 'r', '\x2', '\x2', '\x158', '\x159', '\a', 'q', '\x2', + '\x2', '\x159', '\x15A', '\a', 't', '\x2', '\x2', '\x15A', '\x15B', '\a', + 'v', '\x2', '\x2', '\x15B', '\x4', '\x3', '\x2', '\x2', '\x2', '\x15C', + '\x15D', '\a', 'v', '\x2', '\x2', '\x15D', '\x15E', '\a', '{', '\x2', + '\x2', '\x15E', '\x15F', '\a', 'r', '\x2', '\x2', '\x15F', '\x160', '\a', + 'g', '\x2', '\x2', '\x160', '\x161', '\a', '\x63', '\x2', '\x2', '\x161', + '\x162', '\a', 'n', '\x2', '\x2', '\x162', '\x163', '\a', 'k', '\x2', + '\x2', '\x163', '\x164', '\a', '\x63', '\x2', '\x2', '\x164', '\x165', + '\a', 'u', '\x2', '\x2', '\x165', '\x6', '\x3', '\x2', '\x2', '\x2', '\x166', + '\x167', '\a', 'u', '\x2', '\x2', '\x167', '\x168', '\a', 'v', '\x2', + '\x2', '\x168', '\x169', '\a', 't', '\x2', '\x2', '\x169', '\x16A', '\a', + 'w', '\x2', '\x2', '\x16A', '\x16B', '\a', '\x65', '\x2', '\x2', '\x16B', + '\x16C', '\a', 'v', '\x2', '\x2', '\x16C', '\b', '\x3', '\x2', '\x2', + '\x2', '\x16D', '\x16E', '\a', '\x65', '\x2', '\x2', '\x16E', '\x16F', + '\a', 'n', '\x2', '\x2', '\x16F', '\x170', '\a', '\x63', '\x2', '\x2', + '\x170', '\x171', '\a', 'u', '\x2', '\x2', '\x171', '\x172', '\a', 'u', + '\x2', '\x2', '\x172', '\n', '\x3', '\x2', '\x2', '\x2', '\x173', '\x174', + '\a', 'g', '\x2', '\x2', '\x174', '\x175', '\a', 'p', '\x2', '\x2', '\x175', + '\x176', '\a', 'w', '\x2', '\x2', '\x176', '\x177', '\a', 'o', '\x2', + '\x2', '\x177', '\f', '\x3', '\x2', '\x2', '\x2', '\x178', '\x179', '\a', + 'r', '\x2', '\x2', '\x179', '\x17A', '\a', 't', '\x2', '\x2', '\x17A', + '\x17B', '\a', 'q', '\x2', '\x2', '\x17B', '\x17C', '\a', 'v', '\x2', + '\x2', '\x17C', '\x17D', '\a', 'q', '\x2', '\x2', '\x17D', '\x17E', '\a', + '\x65', '\x2', '\x2', '\x17E', '\x17F', '\a', 'q', '\x2', '\x2', '\x17F', + '\x180', '\a', 'n', '\x2', '\x2', '\x180', '\xE', '\x3', '\x2', '\x2', + '\x2', '\x181', '\x182', '\a', 'x', '\x2', '\x2', '\x182', '\x183', '\a', + '\x63', '\x2', '\x2', '\x183', '\x184', '\a', 't', '\x2', '\x2', '\x184', + '\x10', '\x3', '\x2', '\x2', '\x2', '\x185', '\x186', '\a', 'h', '\x2', + '\x2', '\x186', '\x187', '\a', 'w', '\x2', '\x2', '\x187', '\x188', '\a', + 'p', '\x2', '\x2', '\x188', '\x189', '\a', '\x65', '\x2', '\x2', '\x189', + '\x12', '\x3', '\x2', '\x2', '\x2', '\x18A', '\x18B', '\a', 'n', '\x2', + '\x2', '\x18B', '\x18C', '\a', 'g', '\x2', '\x2', '\x18C', '\x18D', '\a', + 'v', '\x2', '\x2', '\x18D', '\x14', '\x3', '\x2', '\x2', '\x2', '\x18E', + '\x18F', '\a', 'i', '\x2', '\x2', '\x18F', '\x190', '\a', 'g', '\x2', + '\x2', '\x190', '\x191', '\a', 'v', '\x2', '\x2', '\x191', '\x16', '\x3', + '\x2', '\x2', '\x2', '\x192', '\x193', '\a', 'u', '\x2', '\x2', '\x193', + '\x194', '\a', 'g', '\x2', '\x2', '\x194', '\x195', '\a', 'v', '\x2', + '\x2', '\x195', '\x18', '\x3', '\x2', '\x2', '\x2', '\x196', '\x197', + '\a', 'k', '\x2', '\x2', '\x197', '\x198', '\a', 'p', '\x2', '\x2', '\x198', + '\x199', '\a', '\x66', '\x2', '\x2', '\x199', '\x19A', '\a', 'k', '\x2', + '\x2', '\x19A', '\x19B', '\a', 't', '\x2', '\x2', '\x19B', '\x19C', '\a', + 'g', '\x2', '\x2', '\x19C', '\x19D', '\a', '\x65', '\x2', '\x2', '\x19D', + '\x19E', '\a', 'v', '\x2', '\x2', '\x19E', '\x1A', '\x3', '\x2', '\x2', + '\x2', '\x19F', '\x1A0', '\a', '\x65', '\x2', '\x2', '\x1A0', '\x1A1', + '\a', '\x63', '\x2', '\x2', '\x1A1', '\x1A2', '\a', 'u', '\x2', '\x2', + '\x1A2', '\x1A3', '\a', 'g', '\x2', '\x2', '\x1A3', '\x1C', '\x3', '\x2', + '\x2', '\x2', '\x1A4', '\x1A5', '\a', 'h', '\x2', '\x2', '\x1A5', '\x1A6', + '\a', 'k', '\x2', '\x2', '\x1A6', '\x1A7', '\a', 'p', '\x2', '\x2', '\x1A7', + '\x1A8', '\a', '\x63', '\x2', '\x2', '\x1A8', '\x1A9', '\a', 'n', '\x2', + '\x2', '\x1A9', '\x1E', '\x3', '\x2', '\x2', '\x2', '\x1AA', '\x1AB', + '\a', 'r', '\x2', '\x2', '\x1AB', '\x1AC', '\a', 't', '\x2', '\x2', '\x1AC', + '\x1AD', '\a', 'g', '\x2', '\x2', '\x1AD', '\x1AE', '\a', 'h', '\x2', + '\x2', '\x1AE', '\x1AF', '\a', 'k', '\x2', '\x2', '\x1AF', '\x1B0', '\a', + 'z', '\x2', '\x2', '\x1B0', ' ', '\x3', '\x2', '\x2', '\x2', '\x1B1', + '\x1B2', '\a', 'q', '\x2', '\x2', '\x1B2', '\x1B3', '\a', 'r', '\x2', + '\x2', '\x1B3', '\x1B4', '\a', 'g', '\x2', '\x2', '\x1B4', '\x1B5', '\a', + 't', '\x2', '\x2', '\x1B5', '\x1B6', '\a', '\x63', '\x2', '\x2', '\x1B6', + '\x1B7', '\a', 'v', '\x2', '\x2', '\x1B7', '\x1B8', '\a', 'q', '\x2', + '\x2', '\x1B8', '\x1B9', '\a', 't', '\x2', '\x2', '\x1B9', '\"', '\x3', + '\x2', '\x2', '\x2', '\x1BA', '\x1BB', '\a', 'r', '\x2', '\x2', '\x1BB', + '\x1BC', '\a', 'q', '\x2', '\x2', '\x1BC', '\x1BD', '\a', 'u', '\x2', + '\x2', '\x1BD', '\x1BE', '\a', 'v', '\x2', '\x2', '\x1BE', '\x1BF', '\a', + 'h', '\x2', '\x2', '\x1BF', '\x1C0', '\a', 'k', '\x2', '\x2', '\x1C0', + '\x1C1', '\a', 'z', '\x2', '\x2', '\x1C1', '$', '\x3', '\x2', '\x2', '\x2', + '\x1C2', '\x1C3', '\a', 'k', '\x2', '\x2', '\x1C3', '\x1C4', '\a', 'p', + '\x2', '\x2', '\x1C4', '\x1C5', '\a', 'h', '\x2', '\x2', '\x1C5', '\x1C6', + '\a', 'k', '\x2', '\x2', '\x1C6', '\x1C7', '\a', 'z', '\x2', '\x2', '\x1C7', + '&', '\x3', '\x2', '\x2', '\x2', '\x1C8', '\x1C9', '\a', 'r', '\x2', '\x2', + '\x1C9', '\x1CA', '\a', 't', '\x2', '\x2', '\x1CA', '\x1CB', '\a', 'g', + '\x2', '\x2', '\x1CB', '\x1CC', '\a', '\x65', '\x2', '\x2', '\x1CC', '\x1CD', + '\a', 'g', '\x2', '\x2', '\x1CD', '\x1CE', '\a', '\x66', '\x2', '\x2', + '\x1CE', '\x1CF', '\a', 'g', '\x2', '\x2', '\x1CF', '\x1D0', '\a', 'p', + '\x2', '\x2', '\x1D0', '\x1D1', '\a', '\x65', '\x2', '\x2', '\x1D1', '\x1D2', + '\a', 'g', '\x2', '\x2', '\x1D2', '\x1D3', '\a', 'i', '\x2', '\x2', '\x1D3', + '\x1D4', '\a', 't', '\x2', '\x2', '\x1D4', '\x1D5', '\a', 'q', '\x2', + '\x2', '\x1D5', '\x1D6', '\a', 'w', '\x2', '\x2', '\x1D6', '\x1D7', '\a', + 'r', '\x2', '\x2', '\x1D7', '(', '\x3', '\x2', '\x2', '\x2', '\x1D8', + '\x1D9', '\a', 'j', '\x2', '\x2', '\x1D9', '\x1DA', '\a', 'k', '\x2', + '\x2', '\x1DA', '\x1DB', '\a', 'i', '\x2', '\x2', '\x1DB', '\x1DC', '\a', + 'j', '\x2', '\x2', '\x1DC', '\x1DD', '\a', 'g', '\x2', '\x2', '\x1DD', + '\x1DE', '\a', 't', '\x2', '\x2', '\x1DE', '\x1DF', '\a', 'V', '\x2', + '\x2', '\x1DF', '\x1E0', '\a', 'j', '\x2', '\x2', '\x1E0', '\x1E1', '\a', + '\x63', '\x2', '\x2', '\x1E1', '\x1E2', '\a', 'p', '\x2', '\x2', '\x1E2', + '*', '\x3', '\x2', '\x2', '\x2', '\x1E3', '\x1E4', '\a', 'n', '\x2', '\x2', + '\x1E4', '\x1E5', '\a', 'q', '\x2', '\x2', '\x1E5', '\x1E6', '\a', 'y', + '\x2', '\x2', '\x1E6', '\x1E7', '\a', 'g', '\x2', '\x2', '\x1E7', '\x1E8', + '\a', 't', '\x2', '\x2', '\x1E8', '\x1E9', '\a', 'V', '\x2', '\x2', '\x1E9', + '\x1EA', '\a', 'j', '\x2', '\x2', '\x1EA', '\x1EB', '\a', '\x63', '\x2', + '\x2', '\x1EB', '\x1EC', '\a', 'p', '\x2', '\x2', '\x1EC', ',', '\x3', + '\x2', '\x2', '\x2', '\x1ED', '\x1EE', '\a', '\x63', '\x2', '\x2', '\x1EE', + '\x1EF', '\a', 'u', '\x2', '\x2', '\x1EF', '\x1F0', '\a', 'u', '\x2', + '\x2', '\x1F0', '\x1F1', '\a', 'k', '\x2', '\x2', '\x1F1', '\x1F2', '\a', + 'i', '\x2', '\x2', '\x1F2', '\x1F3', '\a', 'p', '\x2', '\x2', '\x1F3', + '\x1F4', '\a', 'o', '\x2', '\x2', '\x1F4', '\x1F5', '\a', 'g', '\x2', + '\x2', '\x1F5', '\x1F6', '\a', 'p', '\x2', '\x2', '\x1F6', '\x1F7', '\a', + 'v', '\x2', '\x2', '\x1F7', '.', '\x3', '\x2', '\x2', '\x2', '\x1F8', + '\x1F9', '\a', '\x63', '\x2', '\x2', '\x1F9', '\x1FA', '\a', 'u', '\x2', + '\x2', '\x1FA', '\x1FB', '\a', 'u', '\x2', '\x2', '\x1FB', '\x1FC', '\a', + 'q', '\x2', '\x2', '\x1FC', '\x1FD', '\a', '\x65', '\x2', '\x2', '\x1FD', + '\x1FE', '\a', 'k', '\x2', '\x2', '\x1FE', '\x1FF', '\a', '\x63', '\x2', + '\x2', '\x1FF', '\x200', '\a', 'v', '\x2', '\x2', '\x200', '\x201', '\a', + 'k', '\x2', '\x2', '\x201', '\x202', '\a', 'x', '\x2', '\x2', '\x202', + '\x203', '\a', 'k', '\x2', '\x2', '\x203', '\x204', '\a', 'v', '\x2', + '\x2', '\x204', '\x205', '\a', '{', '\x2', '\x2', '\x205', '\x30', '\x3', + '\x2', '\x2', '\x2', '\x206', '\x207', '\a', 'n', '\x2', '\x2', '\x207', + '\x208', '\a', 'g', '\x2', '\x2', '\x208', '\x209', '\a', 'h', '\x2', + '\x2', '\x209', '\x20A', '\a', 'v', '\x2', '\x2', '\x20A', '\x32', '\x3', + '\x2', '\x2', '\x2', '\x20B', '\x20C', '\a', 't', '\x2', '\x2', '\x20C', + '\x20D', '\a', 'k', '\x2', '\x2', '\x20D', '\x20E', '\a', 'i', '\x2', + '\x2', '\x20E', '\x20F', '\a', 'j', '\x2', '\x2', '\x20F', '\x210', '\a', + 'v', '\x2', '\x2', '\x210', '\x34', '\x3', '\x2', '\x2', '\x2', '\x211', + '\x212', '\a', 'p', '\x2', '\x2', '\x212', '\x213', '\a', 'q', '\x2', + '\x2', '\x213', '\x214', '\a', 'p', '\x2', '\x2', '\x214', '\x215', '\a', + 'g', '\x2', '\x2', '\x215', '\x36', '\x3', '\x2', '\x2', '\x2', '\x216', + '\x217', '\a', 'g', '\x2', '\x2', '\x217', '\x218', '\a', 'z', '\x2', + '\x2', '\x218', '\x219', '\a', 'v', '\x2', '\x2', '\x219', '\x21A', '\a', + 'g', '\x2', '\x2', '\x21A', '\x21B', '\a', 'p', '\x2', '\x2', '\x21B', + '\x21C', '\a', 'u', '\x2', '\x2', '\x21C', '\x21D', '\a', 'k', '\x2', + '\x2', '\x21D', '\x21E', '\a', 'q', '\x2', '\x2', '\x21E', '\x21F', '\a', + 'p', '\x2', '\x2', '\x21F', '\x38', '\x3', '\x2', '\x2', '\x2', '\x220', + '\x221', '\a', 'u', '\x2', '\x2', '\x221', '\x222', '\a', 'w', '\x2', + '\x2', '\x222', '\x223', '\a', '\x64', '\x2', '\x2', '\x223', '\x224', + '\a', 'u', '\x2', '\x2', '\x224', '\x225', '\a', '\x65', '\x2', '\x2', + '\x225', '\x226', '\a', 't', '\x2', '\x2', '\x226', '\x227', '\a', 'k', + '\x2', '\x2', '\x227', '\x228', '\a', 'r', '\x2', '\x2', '\x228', '\x229', + '\a', 'v', '\x2', '\x2', '\x229', ':', '\x3', '\x2', '\x2', '\x2', '\x22A', + '\x22B', '\a', '\x63', '\x2', '\x2', '\x22B', '\x22C', '\a', 'u', '\x2', + '\x2', '\x22C', '\x22D', '\a', 'u', '\x2', '\x2', '\x22D', '\x22E', '\a', + 'q', '\x2', '\x2', '\x22E', '\x22F', '\a', '\x65', '\x2', '\x2', '\x22F', + '\x230', '\a', 'k', '\x2', '\x2', '\x230', '\x231', '\a', '\x63', '\x2', + '\x2', '\x231', '\x232', '\a', 'v', '\x2', '\x2', '\x232', '\x233', '\a', + 'g', '\x2', '\x2', '\x233', '\x234', '\a', '\x66', '\x2', '\x2', '\x234', + '\x235', '\a', 'v', '\x2', '\x2', '\x235', '\x236', '\a', '{', '\x2', + '\x2', '\x236', '\x237', '\a', 'r', '\x2', '\x2', '\x237', '\x238', '\a', + 'g', '\x2', '\x2', '\x238', '<', '\x3', '\x2', '\x2', '\x2', '\x239', + '\x23A', '\a', '\x63', '\x2', '\x2', '\x23A', '\x23B', '\a', 'u', '\x2', + '\x2', '\x23B', '\x23C', '\a', '{', '\x2', '\x2', '\x23C', '\x23D', '\a', + 'p', '\x2', '\x2', '\x23D', '\x23E', '\a', '\x65', '\x2', '\x2', '\x23E', + '>', '\x3', '\x2', '\x2', '\x2', '\x23F', '\x240', '\a', 'v', '\x2', '\x2', + '\x240', '\x241', '\a', 'j', '\x2', '\x2', '\x241', '\x242', '\a', 't', + '\x2', '\x2', '\x242', '\x243', '\a', 'q', '\x2', '\x2', '\x243', '\x244', + '\a', 'y', '\x2', '\x2', '\x244', '\x245', '\a', 'u', '\x2', '\x2', '\x245', + '@', '\x3', '\x2', '\x2', '\x2', '\x246', '\x247', '\a', 't', '\x2', '\x2', + '\x247', '\x248', '\a', 'g', '\x2', '\x2', '\x248', '\x249', '\a', 'v', + '\x2', '\x2', '\x249', '\x24A', '\a', 'j', '\x2', '\x2', '\x24A', '\x24B', + '\a', 't', '\x2', '\x2', '\x24B', '\x24C', '\a', 'q', '\x2', '\x2', '\x24C', + '\x24D', '\a', 'y', '\x2', '\x2', '\x24D', '\x24E', '\a', 'u', '\x2', + '\x2', '\x24E', '\x42', '\x3', '\x2', '\x2', '\x2', '\x24F', '\x250', + '\a', 'k', '\x2', '\x2', '\x250', '\x251', '\a', 'p', '\x2', '\x2', '\x251', + '\x252', '\a', 'k', '\x2', '\x2', '\x252', '\x253', '\a', 'v', '\x2', + '\x2', '\x253', '\x44', '\x3', '\x2', '\x2', '\x2', '\x254', '\x255', + '\a', '\x66', '\x2', '\x2', '\x255', '\x256', '\a', 'g', '\x2', '\x2', + '\x256', '\x257', '\a', 'k', '\x2', '\x2', '\x257', '\x258', '\a', 'p', + '\x2', '\x2', '\x258', '\x259', '\a', 'k', '\x2', '\x2', '\x259', '\x25A', + '\a', 'v', '\x2', '\x2', '\x25A', '\x46', '\x3', '\x2', '\x2', '\x2', + '\x25B', '\x25C', '\a', '\x65', '\x2', '\x2', '\x25C', '\x25D', '\a', + 'q', '\x2', '\x2', '\x25D', '\x25E', '\a', 'p', '\x2', '\x2', '\x25E', + '\x25F', '\a', 'x', '\x2', '\x2', '\x25F', '\x260', '\a', 'g', '\x2', + '\x2', '\x260', '\x261', '\a', 'p', '\x2', '\x2', '\x261', '\x262', '\a', + 'k', '\x2', '\x2', '\x262', '\x263', '\a', 'g', '\x2', '\x2', '\x263', + '\x264', '\a', 'p', '\x2', '\x2', '\x264', '\x265', '\a', '\x65', '\x2', + '\x2', '\x265', '\x266', '\a', 'g', '\x2', '\x2', '\x266', 'H', '\x3', + '\x2', '\x2', '\x2', '\x267', '\x268', '\a', '\x66', '\x2', '\x2', '\x268', + '\x269', '\a', '{', '\x2', '\x2', '\x269', '\x26A', '\a', 'p', '\x2', + '\x2', '\x26A', '\x26B', '\a', '\x63', '\x2', '\x2', '\x26B', '\x26C', + '\a', 'o', '\x2', '\x2', '\x26C', '\x26D', '\a', 'k', '\x2', '\x2', '\x26D', + '\x26E', '\a', '\x65', '\x2', '\x2', '\x26E', 'J', '\x3', '\x2', '\x2', + '\x2', '\x26F', '\x270', '\a', 'n', '\x2', '\x2', '\x270', '\x271', '\a', + '\x63', '\x2', '\x2', '\x271', '\x272', '\a', '|', '\x2', '\x2', '\x272', + '\x273', '\a', '{', '\x2', '\x2', '\x273', 'L', '\x3', '\x2', '\x2', '\x2', + '\x274', '\x275', '\a', 'q', '\x2', '\x2', '\x275', '\x276', '\a', 'r', + '\x2', '\x2', '\x276', '\x277', '\a', 'v', '\x2', '\x2', '\x277', '\x278', + '\a', 'k', '\x2', '\x2', '\x278', '\x279', '\a', 'q', '\x2', '\x2', '\x279', + '\x27A', '\a', 'p', '\x2', '\x2', '\x27A', '\x27B', '\a', '\x63', '\x2', + '\x2', '\x27B', '\x27C', '\a', 'n', '\x2', '\x2', '\x27C', 'N', '\x3', + '\x2', '\x2', '\x2', '\x27D', '\x27E', '\a', 'q', '\x2', '\x2', '\x27E', + '\x27F', '\a', 'x', '\x2', '\x2', '\x27F', '\x280', '\a', 'g', '\x2', + '\x2', '\x280', '\x281', '\a', 't', '\x2', '\x2', '\x281', '\x282', '\a', + 't', '\x2', '\x2', '\x282', '\x283', '\a', 'k', '\x2', '\x2', '\x283', + '\x284', '\a', '\x66', '\x2', '\x2', '\x284', '\x285', '\a', 'g', '\x2', + '\x2', '\x285', 'P', '\x3', '\x2', '\x2', '\x2', '\x286', '\x287', '\a', + 't', '\x2', '\x2', '\x287', '\x288', '\a', 'g', '\x2', '\x2', '\x288', + '\x289', '\a', 's', '\x2', '\x2', '\x289', '\x28A', '\a', 'w', '\x2', + '\x2', '\x28A', '\x28B', '\a', 'k', '\x2', '\x2', '\x28B', '\x28C', '\a', + 't', '\x2', '\x2', '\x28C', '\x28D', '\a', 'g', '\x2', '\x2', '\x28D', + '\x28E', '\a', '\x66', '\x2', '\x2', '\x28E', 'R', '\x3', '\x2', '\x2', + '\x2', '\x28F', '\x290', '\a', 'u', '\x2', '\x2', '\x290', '\x291', '\a', + 'v', '\x2', '\x2', '\x291', '\x292', '\a', '\x63', '\x2', '\x2', '\x292', + '\x293', '\a', 'v', '\x2', '\x2', '\x293', '\x294', '\a', 'k', '\x2', + '\x2', '\x294', '\x295', '\a', '\x65', '\x2', '\x2', '\x295', 'T', '\x3', + '\x2', '\x2', '\x2', '\x296', '\x297', '\a', 'w', '\x2', '\x2', '\x297', + '\x298', '\a', 'p', '\x2', '\x2', '\x298', '\x299', '\a', 'q', '\x2', + '\x2', '\x299', '\x29A', '\a', 'y', '\x2', '\x2', '\x29A', '\x29B', '\a', + 'p', '\x2', '\x2', '\x29B', '\x29C', '\a', 'g', '\x2', '\x2', '\x29C', + '\x29D', '\a', '\x66', '\x2', '\x2', '\x29D', 'V', '\x3', '\x2', '\x2', + '\x2', '\x29E', '\x29F', '\a', 'u', '\x2', '\x2', '\x29F', '\x2A0', '\a', + '\x63', '\x2', '\x2', '\x2A0', '\x2A1', '\a', 'h', '\x2', '\x2', '\x2A1', + '\x2A2', '\a', 'g', '\x2', '\x2', '\x2A2', 'X', '\x3', '\x2', '\x2', '\x2', + '\x2A3', '\x2A4', '\a', 'w', '\x2', '\x2', '\x2A4', '\x2A5', '\a', 'p', + '\x2', '\x2', '\x2A5', '\x2A6', '\a', 'u', '\x2', '\x2', '\x2A6', '\x2A7', + '\a', '\x63', '\x2', '\x2', '\x2A7', '\x2A8', '\a', 'h', '\x2', '\x2', + '\x2A8', '\x2A9', '\a', 'g', '\x2', '\x2', '\x2A9', 'Z', '\x3', '\x2', + '\x2', '\x2', '\x2AA', '\x2AB', '\a', 'y', '\x2', '\x2', '\x2AB', '\x2AC', + '\a', 'g', '\x2', '\x2', '\x2AC', '\x2AD', '\a', '\x63', '\x2', '\x2', + '\x2AD', '\x2AE', '\a', 'm', '\x2', '\x2', '\x2AE', '\\', '\x3', '\x2', + '\x2', '\x2', '\x2AF', '\x2B0', '\a', 'r', '\x2', '\x2', '\x2B0', '\x2B1', + '\a', 't', '\x2', '\x2', '\x2B1', '\x2B2', '\a', 'k', '\x2', '\x2', '\x2B2', + '\x2B3', '\a', 'x', '\x2', '\x2', '\x2B3', '\x2B4', '\a', '\x63', '\x2', + '\x2', '\x2B4', '\x2B5', '\a', 'v', '\x2', '\x2', '\x2B5', '\x2B6', '\a', + 'g', '\x2', '\x2', '\x2B6', '^', '\x3', '\x2', '\x2', '\x2', '\x2B7', + '\x2B8', '\a', 'h', '\x2', '\x2', '\x2B8', '\x2B9', '\a', 'k', '\x2', + '\x2', '\x2B9', '\x2BA', '\a', 'n', '\x2', '\x2', '\x2BA', '\x2BB', '\a', + 'g', '\x2', '\x2', '\x2BB', '\x2BC', '\a', 'r', '\x2', '\x2', '\x2BC', + '\x2BD', '\a', 't', '\x2', '\x2', '\x2BD', '\x2BE', '\a', 'k', '\x2', + '\x2', '\x2BE', '\x2BF', '\a', 'x', '\x2', '\x2', '\x2BF', '\x2C0', '\a', + '\x63', '\x2', '\x2', '\x2C0', '\x2C1', '\a', 'v', '\x2', '\x2', '\x2C1', + '\x2C2', '\a', 'g', '\x2', '\x2', '\x2C2', '`', '\x3', '\x2', '\x2', '\x2', + '\x2C3', '\x2C4', '\a', 'k', '\x2', '\x2', '\x2C4', '\x2C5', '\a', 'p', + '\x2', '\x2', '\x2C5', '\x2C6', '\a', 'v', '\x2', '\x2', '\x2C6', '\x2C7', + '\a', 'g', '\x2', '\x2', '\x2C7', '\x2C8', '\a', 't', '\x2', '\x2', '\x2C8', + '\x2C9', '\a', 'p', '\x2', '\x2', '\x2C9', '\x2CA', '\a', '\x63', '\x2', + '\x2', '\x2CA', '\x2CB', '\a', 'n', '\x2', '\x2', '\x2CB', '\x62', '\x3', + '\x2', '\x2', '\x2', '\x2CC', '\x2CD', '\a', 'r', '\x2', '\x2', '\x2CD', + '\x2CE', '\a', 'w', '\x2', '\x2', '\x2CE', '\x2CF', '\a', '\x64', '\x2', + '\x2', '\x2CF', '\x2D0', '\a', 'n', '\x2', '\x2', '\x2D0', '\x2D1', '\a', + 'k', '\x2', '\x2', '\x2D1', '\x2D2', '\a', '\x65', '\x2', '\x2', '\x2D2', + '\x64', '\x3', '\x2', '\x2', '\x2', '\x2D3', '\x2D4', '\a', 'q', '\x2', + '\x2', '\x2D4', '\x2D5', '\a', 'r', '\x2', '\x2', '\x2D5', '\x2D6', '\a', + 'g', '\x2', '\x2', '\x2D6', '\x2D7', '\a', 'p', '\x2', '\x2', '\x2D7', + '\x66', '\x3', '\x2', '\x2', '\x2', '\x2D8', '\x2D9', '\a', 'o', '\x2', + '\x2', '\x2D9', '\x2DA', '\a', 'w', '\x2', '\x2', '\x2DA', '\x2DB', '\a', + 'v', '\x2', '\x2', '\x2DB', '\x2DC', '\a', '\x63', '\x2', '\x2', '\x2DC', + '\x2DD', '\a', 'v', '\x2', '\x2', '\x2DD', '\x2DE', '\a', 'k', '\x2', + '\x2', '\x2DE', '\x2DF', '\a', 'p', '\x2', '\x2', '\x2DF', '\x2E0', '\a', + 'i', '\x2', '\x2', '\x2E0', 'h', '\x3', '\x2', '\x2', '\x2', '\x2E1', + '\x2E2', '\a', 'p', '\x2', '\x2', '\x2E2', '\x2E3', '\a', 'q', '\x2', + '\x2', '\x2E3', '\x2E4', '\a', 'p', '\x2', '\x2', '\x2E4', '\x2E5', '\a', + 'o', '\x2', '\x2', '\x2E5', '\x2E6', '\a', 'w', '\x2', '\x2', '\x2E6', + '\x2E7', '\a', 'v', '\x2', '\x2', '\x2E7', '\x2E8', '\a', '\x63', '\x2', + '\x2', '\x2E8', '\x2E9', '\a', 'v', '\x2', '\x2', '\x2E9', '\x2EA', '\a', + 'k', '\x2', '\x2', '\x2EA', '\x2EB', '\a', 'p', '\x2', '\x2', '\x2EB', + '\x2EC', '\a', 'i', '\x2', '\x2', '\x2EC', 'j', '\x3', '\x2', '\x2', '\x2', + '\x2ED', '\x2EE', '\a', 'k', '\x2', '\x2', '\x2EE', '\x2EF', '\a', 'u', + '\x2', '\x2', '\x2EF', 'l', '\x3', '\x2', '\x2', '\x2', '\x2F0', '\x2F1', + '\a', '\x63', '\x2', '\x2', '\x2F1', '\x2F2', '\a', 'u', '\x2', '\x2', + '\x2F2', 'n', '\x3', '\x2', '\x2', '\x2', '\x2F3', '\x2F4', '\a', 'V', + '\x2', '\x2', '\x2F4', '\x2F5', '\a', '{', '\x2', '\x2', '\x2F5', '\x2F6', + '\a', 'r', '\x2', '\x2', '\x2F6', '\x2F7', '\a', 'g', '\x2', '\x2', '\x2F7', + 'p', '\x3', '\x2', '\x2', '\x2', '\x2F8', '\x2F9', '\a', 'R', '\x2', '\x2', + '\x2F9', '\x2FA', '\a', 't', '\x2', '\x2', '\x2FA', '\x2FB', '\a', 'q', + '\x2', '\x2', '\x2FB', '\x2FC', '\a', 'v', '\x2', '\x2', '\x2FC', '\x2FD', + '\a', 'q', '\x2', '\x2', '\x2FD', '\x2FE', '\a', '\x65', '\x2', '\x2', + '\x2FE', '\x2FF', '\a', 'q', '\x2', '\x2', '\x2FF', '\x300', '\a', 'n', + '\x2', '\x2', '\x300', 'r', '\x3', '\x2', '\x2', '\x2', '\x301', '\x302', + '\a', '\x43', '\x2', '\x2', '\x302', '\x303', '\a', 'p', '\x2', '\x2', + '\x303', '\x304', '\a', '{', '\x2', '\x2', '\x304', 't', '\x3', '\x2', + '\x2', '\x2', '\x305', '\x306', '\a', 'U', '\x2', '\x2', '\x306', '\x307', + '\a', 'g', '\x2', '\x2', '\x307', '\x308', '\a', 'n', '\x2', '\x2', '\x308', + '\x309', '\a', 'h', '\x2', '\x2', '\x309', 'v', '\x3', '\x2', '\x2', '\x2', + '\x30A', '\x30B', '\a', '\x63', '\x2', '\x2', '\x30B', '\x30C', '\a', + 'p', '\x2', '\x2', '\x30C', '\x30D', '\a', '{', '\x2', '\x2', '\x30D', + 'x', '\x3', '\x2', '\x2', '\x2', '\x30E', '\x30F', '\a', 'k', '\x2', '\x2', + '\x30F', '\x310', '\a', 'p', '\x2', '\x2', '\x310', '\x311', '\a', 'q', + '\x2', '\x2', '\x311', '\x312', '\a', 'w', '\x2', '\x2', '\x312', '\x313', + '\a', 'v', '\x2', '\x2', '\x313', 'z', '\x3', '\x2', '\x2', '\x2', '\x314', + '\x315', '\a', 'p', '\x2', '\x2', '\x315', '\x316', '\a', 'k', '\x2', + '\x2', '\x316', '\x317', '\a', 'n', '\x2', '\x2', '\x317', '|', '\x3', + '\x2', '\x2', '\x2', '\x318', '\x319', '\a', 'v', '\x2', '\x2', '\x319', + '\x31A', '\a', 't', '\x2', '\x2', '\x31A', '\x31B', '\a', 'w', '\x2', + '\x2', '\x31B', '\x31C', '\a', 'g', '\x2', '\x2', '\x31C', '~', '\x3', + '\x2', '\x2', '\x2', '\x31D', '\x31E', '\a', 'h', '\x2', '\x2', '\x31E', + '\x31F', '\a', '\x63', '\x2', '\x2', '\x31F', '\x320', '\a', 'n', '\x2', + '\x2', '\x320', '\x321', '\a', 'u', '\x2', '\x2', '\x321', '\x322', '\a', + 'g', '\x2', '\x2', '\x322', '\x80', '\x3', '\x2', '\x2', '\x2', '\x323', + '\x324', '\a', 'y', '\x2', '\x2', '\x324', '\x325', '\a', 'j', '\x2', + '\x2', '\x325', '\x326', '\a', 'g', '\x2', '\x2', '\x326', '\x327', '\a', + 't', '\x2', '\x2', '\x327', '\x328', '\a', 'g', '\x2', '\x2', '\x328', + '\x82', '\x3', '\x2', '\x2', '\x2', '\x329', '\x32A', '\a', '@', '\x2', + '\x2', '\x32A', '\x84', '\x3', '\x2', '\x2', '\x2', '\x32B', '\x32C', + '\a', '/', '\x2', '\x2', '\x32C', '\x32D', '\a', '@', '\x2', '\x2', '\x32D', + '\x86', '\x3', '\x2', '\x2', '\x2', '\x32E', '\x32F', '\a', '\x30', '\x2', + '\x2', '\x32F', '\x330', '\a', '\x30', '\x2', '\x2', '\x330', '\x331', + '\a', '\x30', '\x2', '\x2', '\x331', '\x88', '\x3', '\x2', '\x2', '\x2', + '\x332', '\x333', '\a', '\x63', '\x2', '\x2', '\x333', '\x334', '\a', + 'n', '\x2', '\x2', '\x334', '\x335', '\a', 'r', '\x2', '\x2', '\x335', + '\x336', '\a', 'j', '\x2', '\x2', '\x336', '\x337', '\a', '\x63', '\x2', + '\x2', '\x337', '\x8A', '\x3', '\x2', '\x2', '\x2', '\x338', '\x339', + '\a', '\x63', '\x2', '\x2', '\x339', '\x33A', '\a', 't', '\x2', '\x2', + '\x33A', '\x33B', '\a', '\x65', '\x2', '\x2', '\x33B', '\x33C', '\a', + 'j', '\x2', '\x2', '\x33C', '\x8C', '\x3', '\x2', '\x2', '\x2', '\x33D', + '\x33E', '\a', '\x63', '\x2', '\x2', '\x33E', '\x33F', '\a', 't', '\x2', + '\x2', '\x33F', '\x340', '\a', 'o', '\x2', '\x2', '\x340', '\x8E', '\x3', + '\x2', '\x2', '\x2', '\x341', '\x342', '\a', '\x63', '\x2', '\x2', '\x342', + '\x343', '\a', 't', '\x2', '\x2', '\x343', '\x344', '\a', 'o', '\x2', + '\x2', '\x344', '\x345', '\a', '\x38', '\x2', '\x2', '\x345', '\x346', + '\a', '\x36', '\x2', '\x2', '\x346', '\x90', '\x3', '\x2', '\x2', '\x2', + '\x347', '\x348', '\a', '\x64', '\x2', '\x2', '\x348', '\x349', '\a', + 'n', '\x2', '\x2', '\x349', '\x34A', '\a', 'w', '\x2', '\x2', '\x34A', + '\x34B', '\a', 'g', '\x2', '\x2', '\x34B', '\x92', '\x3', '\x2', '\x2', + '\x2', '\x34C', '\x34D', '\a', '\x66', '\x2', '\x2', '\x34D', '\x34E', + '\a', 'k', '\x2', '\x2', '\x34E', '\x34F', '\a', '\x66', '\x2', '\x2', + '\x34F', '\x350', '\a', 'U', '\x2', '\x2', '\x350', '\x351', '\a', 'g', + '\x2', '\x2', '\x351', '\x352', '\a', 'v', '\x2', '\x2', '\x352', '\x94', + '\x3', '\x2', '\x2', '\x2', '\x353', '\x354', '\a', 'h', '\x2', '\x2', + '\x354', '\x355', '\a', 'k', '\x2', '\x2', '\x355', '\x356', '\a', 'n', + '\x2', '\x2', '\x356', '\x357', '\a', 'g', '\x2', '\x2', '\x357', '\x96', + '\x3', '\x2', '\x2', '\x2', '\x358', '\x359', '\a', 'i', '\x2', '\x2', + '\x359', '\x35A', '\a', 't', '\x2', '\x2', '\x35A', '\x35B', '\a', 'g', + '\x2', '\x2', '\x35B', '\x35C', '\a', 'g', '\x2', '\x2', '\x35C', '\x35D', + '\a', 'p', '\x2', '\x2', '\x35D', '\x98', '\x3', '\x2', '\x2', '\x2', + '\x35E', '\x35F', '\a', 'k', '\x2', '\x2', '\x35F', '\x360', '\a', '\x35', + '\x2', '\x2', '\x360', '\x361', '\a', ':', '\x2', '\x2', '\x361', '\x362', + '\a', '\x38', '\x2', '\x2', '\x362', '\x9A', '\x3', '\x2', '\x2', '\x2', + '\x363', '\x364', '\a', 'k', '\x2', '\x2', '\x364', '\x365', '\a', 'Q', + '\x2', '\x2', '\x365', '\x366', '\a', 'U', '\x2', '\x2', '\x366', '\x9C', + '\x3', '\x2', '\x2', '\x2', '\x367', '\x368', '\a', 'k', '\x2', '\x2', + '\x368', '\x369', '\a', 'Q', '\x2', '\x2', '\x369', '\x36A', '\a', 'U', + '\x2', '\x2', '\x36A', '\x36B', '\a', '\x43', '\x2', '\x2', '\x36B', '\x36C', + '\a', 'r', '\x2', '\x2', '\x36C', '\x36D', '\a', 'r', '\x2', '\x2', '\x36D', + '\x36E', '\a', 'n', '\x2', '\x2', '\x36E', '\x36F', '\a', 'k', '\x2', + '\x2', '\x36F', '\x370', '\a', '\x65', '\x2', '\x2', '\x370', '\x371', + '\a', '\x63', '\x2', '\x2', '\x371', '\x372', '\a', 'v', '\x2', '\x2', + '\x372', '\x373', '\a', 'k', '\x2', '\x2', '\x373', '\x374', '\a', 'q', + '\x2', '\x2', '\x374', '\x375', '\a', 'p', '\x2', '\x2', '\x375', '\x376', + '\a', 'G', '\x2', '\x2', '\x376', '\x377', '\a', 'z', '\x2', '\x2', '\x377', + '\x378', '\a', 'v', '\x2', '\x2', '\x378', '\x379', '\a', 'g', '\x2', + '\x2', '\x379', '\x37A', '\a', 'p', '\x2', '\x2', '\x37A', '\x37B', '\a', + 'u', '\x2', '\x2', '\x37B', '\x37C', '\a', 'k', '\x2', '\x2', '\x37C', + '\x37D', '\a', 'q', '\x2', '\x2', '\x37D', '\x37E', '\a', 'p', '\x2', + '\x2', '\x37E', '\x9E', '\x3', '\x2', '\x2', '\x2', '\x37F', '\x380', + '\a', 'n', '\x2', '\x2', '\x380', '\x381', '\a', 'k', '\x2', '\x2', '\x381', + '\x382', '\a', 'p', '\x2', '\x2', '\x382', '\x383', '\a', 'g', '\x2', + '\x2', '\x383', '\xA0', '\x3', '\x2', '\x2', '\x2', '\x384', '\x385', + '\a', 'o', '\x2', '\x2', '\x385', '\x386', '\a', '\x63', '\x2', '\x2', + '\x386', '\x387', '\a', '\x65', '\x2', '\x2', '\x387', '\x388', '\a', + 'Q', '\x2', '\x2', '\x388', '\x389', '\a', 'U', '\x2', '\x2', '\x389', + '\xA2', '\x3', '\x2', '\x2', '\x2', '\x38A', '\x38B', '\a', 'o', '\x2', + '\x2', '\x38B', '\x38C', '\a', '\x63', '\x2', '\x2', '\x38C', '\x38D', + '\a', '\x65', '\x2', '\x2', '\x38D', '\x38E', '\a', 'Q', '\x2', '\x2', + '\x38E', '\x38F', '\a', 'U', '\x2', '\x2', '\x38F', '\x390', '\a', '\x43', + '\x2', '\x2', '\x390', '\x391', '\a', 'r', '\x2', '\x2', '\x391', '\x392', + '\a', 'r', '\x2', '\x2', '\x392', '\x393', '\a', 'n', '\x2', '\x2', '\x393', + '\x394', '\a', 'k', '\x2', '\x2', '\x394', '\x395', '\a', '\x65', '\x2', + '\x2', '\x395', '\x396', '\a', '\x63', '\x2', '\x2', '\x396', '\x397', + '\a', 'v', '\x2', '\x2', '\x397', '\x398', '\a', 'k', '\x2', '\x2', '\x398', + '\x399', '\a', 'q', '\x2', '\x2', '\x399', '\x39A', '\a', 'p', '\x2', + '\x2', '\x39A', '\x39B', '\a', 'G', '\x2', '\x2', '\x39B', '\x39C', '\a', + 'z', '\x2', '\x2', '\x39C', '\x39D', '\a', 'v', '\x2', '\x2', '\x39D', + '\x39E', '\a', 'g', '\x2', '\x2', '\x39E', '\x39F', '\a', 'p', '\x2', + '\x2', '\x39F', '\x3A0', '\a', 'u', '\x2', '\x2', '\x3A0', '\x3A1', '\a', + 'k', '\x2', '\x2', '\x3A1', '\x3A2', '\a', 'q', '\x2', '\x2', '\x3A2', + '\x3A3', '\a', 'p', '\x2', '\x2', '\x3A3', '\xA4', '\x3', '\x2', '\x2', + '\x2', '\x3A4', '\x3A5', '\a', 'q', '\x2', '\x2', '\x3A5', '\x3A6', '\a', + 'h', '\x2', '\x2', '\x3A6', '\xA6', '\x3', '\x2', '\x2', '\x2', '\x3A7', + '\x3A8', '\a', 'q', '\x2', '\x2', '\x3A8', '\x3A9', '\a', 'u', '\x2', + '\x2', '\x3A9', '\xA8', '\x3', '\x2', '\x2', '\x2', '\x3AA', '\x3AB', + '\a', 'r', '\x2', '\x2', '\x3AB', '\x3AC', '\a', 't', '\x2', '\x2', '\x3AC', + '\x3AD', '\a', 'g', '\x2', '\x2', '\x3AD', '\x3AE', '\a', '\x65', '\x2', + '\x2', '\x3AE', '\x3AF', '\a', 'g', '\x2', '\x2', '\x3AF', '\x3B0', '\a', + '\x66', '\x2', '\x2', '\x3B0', '\x3B1', '\a', 'g', '\x2', '\x2', '\x3B1', + '\x3B2', '\a', 'p', '\x2', '\x2', '\x3B2', '\x3B3', '\a', '\x65', '\x2', + '\x2', '\x3B3', '\x3B4', '\a', 'g', '\x2', '\x2', '\x3B4', '\xAA', '\x3', + '\x2', '\x2', '\x2', '\x3B5', '\x3B6', '\a', 't', '\x2', '\x2', '\x3B6', + '\x3B7', '\a', 'g', '\x2', '\x2', '\x3B7', '\x3B8', '\a', '\x66', '\x2', + '\x2', '\x3B8', '\xAC', '\x3', '\x2', '\x2', '\x2', '\x3B9', '\x3BA', + '\a', 't', '\x2', '\x2', '\x3BA', '\x3BB', '\a', 'g', '\x2', '\x2', '\x3BB', + '\x3BC', '\a', 'u', '\x2', '\x2', '\x3BC', '\x3BD', '\a', 'q', '\x2', + '\x2', '\x3BD', '\x3BE', '\a', 'w', '\x2', '\x2', '\x3BE', '\x3BF', '\a', + 't', '\x2', '\x2', '\x3BF', '\x3C0', '\a', '\x65', '\x2', '\x2', '\x3C0', + '\x3C1', '\a', 'g', '\x2', '\x2', '\x3C1', '\x3C2', '\a', 'P', '\x2', + '\x2', '\x3C2', '\x3C3', '\a', '\x63', '\x2', '\x2', '\x3C3', '\x3C4', + '\a', 'o', '\x2', '\x2', '\x3C4', '\x3C5', '\a', 'g', '\x2', '\x2', '\x3C5', + '\xAE', '\x3', '\x2', '\x2', '\x2', '\x3C6', '\x3C7', '\a', 'u', '\x2', + '\x2', '\x3C7', '\x3C8', '\a', 'y', '\x2', '\x2', '\x3C8', '\x3C9', '\a', + 'k', '\x2', '\x2', '\x3C9', '\x3CA', '\a', 'h', '\x2', '\x2', '\x3CA', + '\x3CB', '\a', 'v', '\x2', '\x2', '\x3CB', '\xB0', '\x3', '\x2', '\x2', + '\x2', '\x3CC', '\x3CD', '\a', 'v', '\x2', '\x2', '\x3CD', '\x3CE', '\a', + 'x', '\x2', '\x2', '\x3CE', '\x3CF', '\a', 'Q', '\x2', '\x2', '\x3CF', + '\x3D0', '\a', 'U', '\x2', '\x2', '\x3D0', '\xB2', '\x3', '\x2', '\x2', + '\x2', '\x3D1', '\x3D2', '\a', 'v', '\x2', '\x2', '\x3D2', '\x3D3', '\a', + '{', '\x2', '\x2', '\x3D3', '\x3D4', '\a', 'r', '\x2', '\x2', '\x3D4', + '\x3D5', '\a', 'g', '\x2', '\x2', '\x3D5', '\xB4', '\x3', '\x2', '\x2', + '\x2', '\x3D6', '\x3D7', '\a', 'y', '\x2', '\x2', '\x3D7', '\x3D8', '\a', + '\x63', '\x2', '\x2', '\x3D8', '\x3D9', '\a', 'v', '\x2', '\x2', '\x3D9', + '\x3DA', '\a', '\x65', '\x2', '\x2', '\x3DA', '\x3DB', '\a', 'j', '\x2', + '\x2', '\x3DB', '\x3DC', '\a', 'Q', '\x2', '\x2', '\x3DC', '\x3DD', '\a', + 'U', '\x2', '\x2', '\x3DD', '\xB6', '\x3', '\x2', '\x2', '\x2', '\x3DE', + '\x3DF', '\a', 'y', '\x2', '\x2', '\x3DF', '\x3E0', '\a', 'k', '\x2', + '\x2', '\x3E0', '\x3E1', '\a', 'n', '\x2', '\x2', '\x3E1', '\x3E2', '\a', + 'n', '\x2', '\x2', '\x3E2', '\x3E3', '\a', 'U', '\x2', '\x2', '\x3E3', + '\x3E4', '\a', 'g', '\x2', '\x2', '\x3E4', '\x3E5', '\a', 'v', '\x2', + '\x2', '\x3E5', '\xB8', '\x3', '\x2', '\x2', '\x2', '\x3E6', '\x3E7', + '\a', 'z', '\x2', '\x2', '\x3E7', '\x3E8', '\a', ':', '\x2', '\x2', '\x3E8', + '\x3E9', '\a', '\x38', '\x2', '\x2', '\x3E9', '\x3EA', '\a', '\x61', '\x2', + '\x2', '\x3EA', '\x3EB', '\a', '\x38', '\x2', '\x2', '\x3EB', '\x3EC', + '\a', '\x36', '\x2', '\x2', '\x3EC', '\xBA', '\x3', '\x2', '\x2', '\x2', + '\x3ED', '\x3EE', '\a', '\x64', '\x2', '\x2', '\x3EE', '\x3EF', '\a', + 't', '\x2', '\x2', '\x3EF', '\x3F0', '\a', 'g', '\x2', '\x2', '\x3F0', + '\x3F1', '\a', '\x63', '\x2', '\x2', '\x3F1', '\x3F2', '\a', 'm', '\x2', + '\x2', '\x3F2', '\xBC', '\x3', '\x2', '\x2', '\x2', '\x3F3', '\x3F4', + '\a', '\x65', '\x2', '\x2', '\x3F4', '\x3F5', '\a', '\x63', '\x2', '\x2', + '\x3F5', '\x3F6', '\a', 'v', '\x2', '\x2', '\x3F6', '\x3F7', '\a', '\x65', + '\x2', '\x2', '\x3F7', '\x3F8', '\a', 'j', '\x2', '\x2', '\x3F8', '\xBE', + '\x3', '\x2', '\x2', '\x2', '\x3F9', '\x3FA', '\a', '\x65', '\x2', '\x2', + '\x3FA', '\x3FB', '\a', 'q', '\x2', '\x2', '\x3FB', '\x3FC', '\a', 'p', + '\x2', '\x2', '\x3FC', '\x3FD', '\a', 'v', '\x2', '\x2', '\x3FD', '\x3FE', + '\a', 'k', '\x2', '\x2', '\x3FE', '\x3FF', '\a', 'p', '\x2', '\x2', '\x3FF', + '\x400', '\a', 'w', '\x2', '\x2', '\x400', '\x401', '\a', 'g', '\x2', + '\x2', '\x401', '\xC0', '\x3', '\x2', '\x2', '\x2', '\x402', '\x403', + '\a', '\x66', '\x2', '\x2', '\x403', '\x404', '\a', 'g', '\x2', '\x2', + '\x404', '\x405', '\a', 'h', '\x2', '\x2', '\x405', '\x406', '\a', '\x63', + '\x2', '\x2', '\x406', '\x407', '\a', 'w', '\x2', '\x2', '\x407', '\x408', + '\a', 'n', '\x2', '\x2', '\x408', '\x409', '\a', 'v', '\x2', '\x2', '\x409', + '\xC2', '\x3', '\x2', '\x2', '\x2', '\x40A', '\x40B', '\a', '\x66', '\x2', + '\x2', '\x40B', '\x40C', '\a', 'g', '\x2', '\x2', '\x40C', '\x40D', '\a', + 'h', '\x2', '\x2', '\x40D', '\x40E', '\a', 'g', '\x2', '\x2', '\x40E', + '\x40F', '\a', 't', '\x2', '\x2', '\x40F', '\xC4', '\x3', '\x2', '\x2', + '\x2', '\x410', '\x411', '\a', '\x66', '\x2', '\x2', '\x411', '\x412', + '\a', 'q', '\x2', '\x2', '\x412', '\xC6', '\x3', '\x2', '\x2', '\x2', + '\x413', '\x414', '\a', 'g', '\x2', '\x2', '\x414', '\x415', '\a', 'n', + '\x2', '\x2', '\x415', '\x416', '\a', 'u', '\x2', '\x2', '\x416', '\x417', + '\a', 'g', '\x2', '\x2', '\x417', '\xC8', '\x3', '\x2', '\x2', '\x2', + '\x418', '\x419', '\a', 'h', '\x2', '\x2', '\x419', '\x41A', '\a', '\x63', + '\x2', '\x2', '\x41A', '\x41B', '\a', 'n', '\x2', '\x2', '\x41B', '\x41C', + '\a', 'n', '\x2', '\x2', '\x41C', '\x41D', '\a', 'v', '\x2', '\x2', '\x41D', + '\x41E', '\a', 'j', '\x2', '\x2', '\x41E', '\x41F', '\a', 't', '\x2', + '\x2', '\x41F', '\x420', '\a', 'q', '\x2', '\x2', '\x420', '\x421', '\a', + 'w', '\x2', '\x2', '\x421', '\x422', '\a', 'i', '\x2', '\x2', '\x422', + '\x423', '\a', 'j', '\x2', '\x2', '\x423', '\xCA', '\x3', '\x2', '\x2', + '\x2', '\x424', '\x425', '\a', 'h', '\x2', '\x2', '\x425', '\x426', '\a', + 'q', '\x2', '\x2', '\x426', '\x427', '\a', 't', '\x2', '\x2', '\x427', + '\xCC', '\x3', '\x2', '\x2', '\x2', '\x428', '\x429', '\a', 'i', '\x2', + '\x2', '\x429', '\x42A', '\a', 'w', '\x2', '\x2', '\x42A', '\x42B', '\a', + '\x63', '\x2', '\x2', '\x42B', '\x42C', '\a', 't', '\x2', '\x2', '\x42C', + '\x42D', '\a', '\x66', '\x2', '\x2', '\x42D', '\xCE', '\x3', '\x2', '\x2', + '\x2', '\x42E', '\x42F', '\a', 'k', '\x2', '\x2', '\x42F', '\x430', '\a', + 'h', '\x2', '\x2', '\x430', '\xD0', '\x3', '\x2', '\x2', '\x2', '\x431', + '\x432', '\a', 'k', '\x2', '\x2', '\x432', '\x433', '\a', 'p', '\x2', + '\x2', '\x433', '\xD2', '\x3', '\x2', '\x2', '\x2', '\x434', '\x435', + '\a', 't', '\x2', '\x2', '\x435', '\x436', '\a', 'g', '\x2', '\x2', '\x436', + '\x437', '\a', 'r', '\x2', '\x2', '\x437', '\x438', '\a', 'g', '\x2', + '\x2', '\x438', '\x439', '\a', '\x63', '\x2', '\x2', '\x439', '\x43A', + '\a', 'v', '\x2', '\x2', '\x43A', '\xD4', '\x3', '\x2', '\x2', '\x2', + '\x43B', '\x43C', '\a', 't', '\x2', '\x2', '\x43C', '\x43D', '\a', 'g', + '\x2', '\x2', '\x43D', '\x43E', '\a', 'v', '\x2', '\x2', '\x43E', '\x43F', + '\a', 'w', '\x2', '\x2', '\x43F', '\x440', '\a', 't', '\x2', '\x2', '\x440', + '\x441', '\a', 'p', '\x2', '\x2', '\x441', '\xD6', '\x3', '\x2', '\x2', + '\x2', '\x442', '\x443', '\a', 'u', '\x2', '\x2', '\x443', '\x444', '\a', + 'g', '\x2', '\x2', '\x444', '\x445', '\a', 'n', '\x2', '\x2', '\x445', + '\x446', '\a', 'h', '\x2', '\x2', '\x446', '\xD8', '\x3', '\x2', '\x2', + '\x2', '\x447', '\x448', '\a', 'u', '\x2', '\x2', '\x448', '\x449', '\a', + 'w', '\x2', '\x2', '\x449', '\x44A', '\a', 'r', '\x2', '\x2', '\x44A', + '\x44B', '\a', 'g', '\x2', '\x2', '\x44B', '\x44C', '\a', 't', '\x2', + '\x2', '\x44C', '\xDA', '\x3', '\x2', '\x2', '\x2', '\x44D', '\x44E', + '\a', 'u', '\x2', '\x2', '\x44E', '\x44F', '\a', 'y', '\x2', '\x2', '\x44F', + '\x450', '\a', 'k', '\x2', '\x2', '\x450', '\x451', '\a', 'v', '\x2', + '\x2', '\x451', '\x452', '\a', '\x65', '\x2', '\x2', '\x452', '\x453', + '\a', 'j', '\x2', '\x2', '\x453', '\xDC', '\x3', '\x2', '\x2', '\x2', + '\x454', '\x455', '\a', 'v', '\x2', '\x2', '\x455', '\x456', '\a', 'j', + '\x2', '\x2', '\x456', '\x457', '\a', 't', '\x2', '\x2', '\x457', '\x458', + '\a', 'q', '\x2', '\x2', '\x458', '\x459', '\a', 'y', '\x2', '\x2', '\x459', + '\xDE', '\x3', '\x2', '\x2', '\x2', '\x45A', '\x45B', '\a', 'v', '\x2', + '\x2', '\x45B', '\x45C', '\a', 't', '\x2', '\x2', '\x45C', '\x45D', '\a', + '{', '\x2', '\x2', '\x45D', '\xE0', '\x3', '\x2', '\x2', '\x2', '\x45E', + '\x45F', '\a', 'y', '\x2', '\x2', '\x45F', '\x460', '\a', 'j', '\x2', + '\x2', '\x460', '\x461', '\a', 'k', '\x2', '\x2', '\x461', '\x462', '\a', + 'n', '\x2', '\x2', '\x462', '\x463', '\a', 'g', '\x2', '\x2', '\x463', + '\xE2', '\x3', '\x2', '\x2', '\x2', '\x464', '\x465', '\a', '\x32', '\x2', + '\x2', '\x465', '\x466', '\a', '\x64', '\x2', '\x2', '\x466', '\x467', + '\x3', '\x2', '\x2', '\x2', '\x467', '\x469', '\x5', '\xE5', 's', '\x2', + '\x468', '\x46A', '\x5', '\xE9', 'u', '\x2', '\x469', '\x468', '\x3', + '\x2', '\x2', '\x2', '\x469', '\x46A', '\x3', '\x2', '\x2', '\x2', '\x46A', + '\xE4', '\x3', '\x2', '\x2', '\x2', '\x46B', '\x46C', '\t', '\x2', '\x2', + '\x2', '\x46C', '\xE6', '\x3', '\x2', '\x2', '\x2', '\x46D', '\x470', + '\x5', '\xE5', 's', '\x2', '\x46E', '\x470', '\x5', '\x131', '\x99', '\x2', + '\x46F', '\x46D', '\x3', '\x2', '\x2', '\x2', '\x46F', '\x46E', '\x3', + '\x2', '\x2', '\x2', '\x470', '\xE8', '\x3', '\x2', '\x2', '\x2', '\x471', + '\x473', '\x5', '\xE7', 't', '\x2', '\x472', '\x471', '\x3', '\x2', '\x2', + '\x2', '\x473', '\x474', '\x3', '\x2', '\x2', '\x2', '\x474', '\x472', + '\x3', '\x2', '\x2', '\x2', '\x474', '\x475', '\x3', '\x2', '\x2', '\x2', + '\x475', '\xEA', '\x3', '\x2', '\x2', '\x2', '\x476', '\x477', '\a', '\x32', + '\x2', '\x2', '\x477', '\x478', '\a', 'q', '\x2', '\x2', '\x478', '\x479', + '\x3', '\x2', '\x2', '\x2', '\x479', '\x47B', '\x5', '\xED', 'w', '\x2', + '\x47A', '\x47C', '\x5', '\xF1', 'y', '\x2', '\x47B', '\x47A', '\x3', + '\x2', '\x2', '\x2', '\x47B', '\x47C', '\x3', '\x2', '\x2', '\x2', '\x47C', + '\xEC', '\x3', '\x2', '\x2', '\x2', '\x47D', '\x47E', '\t', '\x3', '\x2', + '\x2', '\x47E', '\xEE', '\x3', '\x2', '\x2', '\x2', '\x47F', '\x482', + '\x5', '\xED', 'w', '\x2', '\x480', '\x482', '\x5', '\x131', '\x99', '\x2', + '\x481', '\x47F', '\x3', '\x2', '\x2', '\x2', '\x481', '\x480', '\x3', + '\x2', '\x2', '\x2', '\x482', '\xF0', '\x3', '\x2', '\x2', '\x2', '\x483', + '\x485', '\x5', '\xEF', 'x', '\x2', '\x484', '\x483', '\x3', '\x2', '\x2', + '\x2', '\x485', '\x486', '\x3', '\x2', '\x2', '\x2', '\x486', '\x484', + '\x3', '\x2', '\x2', '\x2', '\x486', '\x487', '\x3', '\x2', '\x2', '\x2', + '\x487', '\xF2', '\x3', '\x2', '\x2', '\x2', '\x488', '\x48C', '\t', '\x4', + '\x2', '\x2', '\x489', '\x48B', '\t', '\x5', '\x2', '\x2', '\x48A', '\x489', + '\x3', '\x2', '\x2', '\x2', '\x48B', '\x48E', '\x3', '\x2', '\x2', '\x2', + '\x48C', '\x48A', '\x3', '\x2', '\x2', '\x2', '\x48C', '\x48D', '\x3', + '\x2', '\x2', '\x2', '\x48D', '\xF4', '\x3', '\x2', '\x2', '\x2', '\x48E', + '\x48C', '\x3', '\x2', '\x2', '\x2', '\x48F', '\x491', '\t', '\x4', '\x2', + '\x2', '\x490', '\x48F', '\x3', '\x2', '\x2', '\x2', '\x491', '\x492', + '\x3', '\x2', '\x2', '\x2', '\x492', '\x490', '\x3', '\x2', '\x2', '\x2', + '\x492', '\x493', '\x3', '\x2', '\x2', '\x2', '\x493', '\xF6', '\x3', + '\x2', '\x2', '\x2', '\x494', '\x495', '\a', '\x32', '\x2', '\x2', '\x495', + '\x496', '\a', 'z', '\x2', '\x2', '\x496', '\x497', '\x3', '\x2', '\x2', + '\x2', '\x497', '\x499', '\x5', '\xF9', '}', '\x2', '\x498', '\x49A', + '\x5', '\xFD', '\x7F', '\x2', '\x499', '\x498', '\x3', '\x2', '\x2', '\x2', + '\x499', '\x49A', '\x3', '\x2', '\x2', '\x2', '\x49A', '\xF8', '\x3', + '\x2', '\x2', '\x2', '\x49B', '\x49C', '\t', '\x3', '\x2', '\x2', '\x49C', + '\xFA', '\x3', '\x2', '\x2', '\x2', '\x49D', '\x4A0', '\x5', '\xF9', '}', + '\x2', '\x49E', '\x4A0', '\x5', '\x131', '\x99', '\x2', '\x49F', '\x49D', + '\x3', '\x2', '\x2', '\x2', '\x49F', '\x49E', '\x3', '\x2', '\x2', '\x2', + '\x4A0', '\xFC', '\x3', '\x2', '\x2', '\x2', '\x4A1', '\x4A3', '\x5', + '\xFB', '~', '\x2', '\x4A2', '\x4A1', '\x3', '\x2', '\x2', '\x2', '\x4A3', + '\x4A4', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A2', '\x3', '\x2', '\x2', + '\x2', '\x4A4', '\x4A5', '\x3', '\x2', '\x2', '\x2', '\x4A5', '\xFE', + '\x3', '\x2', '\x2', '\x2', '\x4A6', '\x4A8', '\a', '$', '\x2', '\x2', + '\x4A7', '\x4A9', '\x5', '\x101', '\x81', '\x2', '\x4A8', '\x4A7', '\x3', + '\x2', '\x2', '\x2', '\x4A8', '\x4A9', '\x3', '\x2', '\x2', '\x2', '\x4A9', + '\x4AA', '\x3', '\x2', '\x2', '\x2', '\x4AA', '\x4AB', '\a', '$', '\x2', + '\x2', '\x4AB', '\x100', '\x3', '\x2', '\x2', '\x2', '\x4AC', '\x4AE', + '\x5', '\x103', '\x82', '\x2', '\x4AD', '\x4AC', '\x3', '\x2', '\x2', + '\x2', '\x4AE', '\x4AF', '\x3', '\x2', '\x2', '\x2', '\x4AF', '\x4AD', + '\x3', '\x2', '\x2', '\x2', '\x4AF', '\x4B0', '\x3', '\x2', '\x2', '\x2', + '\x4B0', '\x102', '\x3', '\x2', '\x2', '\x2', '\x4B1', '\x4B4', '\x5', + '\x105', '\x83', '\x2', '\x4B2', '\x4B4', '\n', '\x6', '\x2', '\x2', '\x4B3', + '\x4B1', '\x3', '\x2', '\x2', '\x2', '\x4B3', '\x4B2', '\x3', '\x2', '\x2', + '\x2', '\x4B4', '\x104', '\x3', '\x2', '\x2', '\x2', '\x4B5', '\x4B6', + '\a', '^', '\x2', '\x2', '\x4B6', '\x4D6', '\t', '\a', '\x2', '\x2', '\x4B7', + '\x4B8', '\a', '^', '\x2', '\x2', '\x4B8', '\x4B9', '\a', 'z', '\x2', + '\x2', '\x4B9', '\x4BA', '\x3', '\x2', '\x2', '\x2', '\x4BA', '\x4BB', + '\x5', '\xF9', '}', '\x2', '\x4BB', '\x4BC', '\x5', '\xF9', '}', '\x2', + '\x4BC', '\x4D6', '\x3', '\x2', '\x2', '\x2', '\x4BD', '\x4BE', '\a', + '^', '\x2', '\x2', '\x4BE', '\x4BF', '\a', 'w', '\x2', '\x2', '\x4BF', + '\x4C0', '\x3', '\x2', '\x2', '\x2', '\x4C0', '\x4C1', '\x5', '\x13B', + '\x9E', '\x2', '\x4C1', '\x4C2', '\x5', '\xF9', '}', '\x2', '\x4C2', '\x4C3', + '\x5', '\xF9', '}', '\x2', '\x4C3', '\x4C4', '\x5', '\xF9', '}', '\x2', + '\x4C4', '\x4C5', '\x5', '\xF9', '}', '\x2', '\x4C5', '\x4C6', '\x5', + '\x13D', '\x9F', '\x2', '\x4C6', '\x4D6', '\x3', '\x2', '\x2', '\x2', + '\x4C7', '\x4C8', '\a', '^', '\x2', '\x2', '\x4C8', '\x4C9', '\a', 'w', + '\x2', '\x2', '\x4C9', '\x4CA', '\x3', '\x2', '\x2', '\x2', '\x4CA', '\x4CB', + '\x5', '\x13B', '\x9E', '\x2', '\x4CB', '\x4CC', '\x5', '\xF9', '}', '\x2', + '\x4CC', '\x4CD', '\x5', '\xF9', '}', '\x2', '\x4CD', '\x4CE', '\x5', + '\xF9', '}', '\x2', '\x4CE', '\x4CF', '\x5', '\xF9', '}', '\x2', '\x4CF', + '\x4D0', '\x5', '\xF9', '}', '\x2', '\x4D0', '\x4D1', '\x5', '\xF9', '}', + '\x2', '\x4D1', '\x4D2', '\x5', '\xF9', '}', '\x2', '\x4D2', '\x4D3', + '\x5', '\xF9', '}', '\x2', '\x4D3', '\x4D4', '\x5', '\x13D', '\x9F', '\x2', + '\x4D4', '\x4D6', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4B5', '\x3', + '\x2', '\x2', '\x2', '\x4D5', '\x4B7', '\x3', '\x2', '\x2', '\x2', '\x4D5', + '\x4BD', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4C7', '\x3', '\x2', '\x2', + '\x2', '\x4D6', '\x106', '\x3', '\x2', '\x2', '\x2', '\x4D7', '\x4D9', + '\x5', '\x109', '\x85', '\x2', '\x4D8', '\x4DA', '\x5', '\x10D', '\x87', + '\x2', '\x4D9', '\x4D8', '\x3', '\x2', '\x2', '\x2', '\x4D9', '\x4DA', + '\x3', '\x2', '\x2', '\x2', '\x4DA', '\x4E4', '\x3', '\x2', '\x2', '\x2', + '\x4DB', '\x4DC', '\x5', '\x12F', '\x98', '\x2', '\x4DC', '\x4DE', '\x5', + '\x109', '\x85', '\x2', '\x4DD', '\x4DF', '\x5', '\x10D', '\x87', '\x2', + '\x4DE', '\x4DD', '\x3', '\x2', '\x2', '\x2', '\x4DE', '\x4DF', '\x3', + '\x2', '\x2', '\x2', '\x4DF', '\x4E0', '\x3', '\x2', '\x2', '\x2', '\x4E0', + '\x4E1', '\x5', '\x12F', '\x98', '\x2', '\x4E1', '\x4E4', '\x3', '\x2', + '\x2', '\x2', '\x4E2', '\x4E4', '\x5', '\x10F', '\x88', '\x2', '\x4E3', + '\x4D7', '\x3', '\x2', '\x2', '\x2', '\x4E3', '\x4DB', '\x3', '\x2', '\x2', + '\x2', '\x4E3', '\x4E2', '\x3', '\x2', '\x2', '\x2', '\x4E4', '\x108', + '\x3', '\x2', '\x2', '\x2', '\x4E5', '\x4E7', '\t', '\r', '\x2', '\x2', + '\x4E6', '\x4E5', '\x3', '\x2', '\x2', '\x2', '\x4E7', '\x10A', '\x3', + '\x2', '\x2', '\x2', '\x4E8', '\x4EB', '\t', '\b', '\x2', '\x2', '\x4E9', + '\x4EB', '\x5', '\x109', '\x85', '\x2', '\x4EA', '\x4E8', '\x3', '\x2', + '\x2', '\x2', '\x4EA', '\x4E9', '\x3', '\x2', '\x2', '\x2', '\x4EB', '\x10C', + '\x3', '\x2', '\x2', '\x2', '\x4EC', '\x4EE', '\x5', '\x10B', '\x86', + '\x2', '\x4ED', '\x4EC', '\x3', '\x2', '\x2', '\x2', '\x4EE', '\x4EF', + '\x3', '\x2', '\x2', '\x2', '\x4EF', '\x4ED', '\x3', '\x2', '\x2', '\x2', + '\x4EF', '\x4F0', '\x3', '\x2', '\x2', '\x2', '\x4F0', '\x10E', '\x3', + '\x2', '\x2', '\x2', '\x4F1', '\x4F2', '\a', '&', '\x2', '\x2', '\x4F2', + '\x4F3', '\x5', '\x13F', '\xA0', '\x2', '\x4F3', '\x110', '\x3', '\x2', + '\x2', '\x2', '\x4F4', '\x4F6', '\t', '\t', '\x2', '\x2', '\x4F5', '\x4F4', + '\x3', '\x2', '\x2', '\x2', '\x4F6', '\x4F7', '\x3', '\x2', '\x2', '\x2', + '\x4F7', '\x4F5', '\x3', '\x2', '\x2', '\x2', '\x4F7', '\x4F8', '\x3', + '\x2', '\x2', '\x2', '\x4F8', '\x4F9', '\x3', '\x2', '\x2', '\x2', '\x4F9', + '\x4FA', '\b', '\x89', '\x2', '\x2', '\x4FA', '\x112', '\x3', '\x2', '\x2', + '\x2', '\x4FB', '\x4FC', '\a', '-', '\x2', '\x2', '\x4FC', '\x114', '\x3', + '\x2', '\x2', '\x2', '\x4FD', '\x4FE', '\a', '/', '\x2', '\x2', '\x4FE', + '\x116', '\x3', '\x2', '\x2', '\x2', '\x4FF', '\x500', '\a', '?', '\x2', + '\x2', '\x500', '\x118', '\x3', '\x2', '\x2', '\x2', '\x501', '\x502', + '\a', '(', '\x2', '\x2', '\x502', '\x11A', '\x3', '\x2', '\x2', '\x2', + '\x503', '\x504', '\a', '\x41', '\x2', '\x2', '\x504', '\x11C', '\x3', + '\x2', '\x2', '\x2', '\x505', '\x506', '\a', '>', '\x2', '\x2', '\x506', + '\x11E', '\x3', '\x2', '\x2', '\x2', '\x507', '\x508', '\a', '#', '\x2', + '\x2', '\x508', '\x120', '\x3', '\x2', '\x2', '\x2', '\x509', '\x50A', + '\a', '\x30', '\x2', '\x2', '\x50A', '\x122', '\x3', '\x2', '\x2', '\x2', + '\x50B', '\x50C', '\a', '.', '\x2', '\x2', '\x50C', '\x124', '\x3', '\x2', + '\x2', '\x2', '\x50D', '\x50E', '\a', '\x80', '\x2', '\x2', '\x50E', '\x126', + '\x3', '\x2', '\x2', '\x2', '\x50F', '\x510', '\a', '<', '\x2', '\x2', + '\x510', '\x128', '\x3', '\x2', '\x2', '\x2', '\x511', '\x512', '\a', + '=', '\x2', '\x2', '\x512', '\x12A', '\x3', '\x2', '\x2', '\x2', '\x513', + '\x514', '\a', '\x42', '\x2', '\x2', '\x514', '\x12C', '\x3', '\x2', '\x2', + '\x2', '\x515', '\x516', '\a', '%', '\x2', '\x2', '\x516', '\x12E', '\x3', + '\x2', '\x2', '\x2', '\x517', '\x518', '\a', '\x62', '\x2', '\x2', '\x518', + '\x130', '\x3', '\x2', '\x2', '\x2', '\x519', '\x51A', '\a', '\x61', '\x2', + '\x2', '\x51A', '\x132', '\x3', '\x2', '\x2', '\x2', '\x51B', '\x51C', + '\a', '*', '\x2', '\x2', '\x51C', '\x134', '\x3', '\x2', '\x2', '\x2', + '\x51D', '\x51E', '\a', '+', '\x2', '\x2', '\x51E', '\x136', '\x3', '\x2', + '\x2', '\x2', '\x51F', '\x520', '\a', ']', '\x2', '\x2', '\x520', '\x138', + '\x3', '\x2', '\x2', '\x2', '\x521', '\x522', '\a', '_', '\x2', '\x2', + '\x522', '\x13A', '\x3', '\x2', '\x2', '\x2', '\x523', '\x524', '\a', + '}', '\x2', '\x2', '\x524', '\x13C', '\x3', '\x2', '\x2', '\x2', '\x525', + '\x526', '\a', '\x7F', '\x2', '\x2', '\x526', '\x13E', '\x3', '\x2', '\x2', + '\x2', '\x527', '\x529', '\t', '\x4', '\x2', '\x2', '\x528', '\x527', + '\x3', '\x2', '\x2', '\x2', '\x529', '\x52A', '\x3', '\x2', '\x2', '\x2', + '\x52A', '\x528', '\x3', '\x2', '\x2', '\x2', '\x52A', '\x52B', '\x3', + '\x2', '\x2', '\x2', '\x52B', '\x140', '\x3', '\x2', '\x2', '\x2', '\x52C', + '\x52E', '\x5', '\x145', '\xA3', '\x2', '\x52D', '\x52F', '\x5', '\x147', + '\xA4', '\x2', '\x52E', '\x52D', '\x3', '\x2', '\x2', '\x2', '\x52E', + '\x52F', '\x3', '\x2', '\x2', '\x2', '\x52F', '\x541', '\x3', '\x2', '\x2', + '\x2', '\x530', '\x531', '\x5', '\x143', '\xA2', '\x2', '\x531', '\x532', + '\x5', '\x149', '\xA5', '\x2', '\x532', '\x541', '\x3', '\x2', '\x2', + '\x2', '\x533', '\x534', '\x5', '\x143', '\xA2', '\x2', '\x534', '\x536', + '\x5', '\x149', '\xA5', '\x2', '\x535', '\x537', '\x5', '\x14B', '\xA6', + '\x2', '\x536', '\x535', '\x3', '\x2', '\x2', '\x2', '\x537', '\x538', + '\x3', '\x2', '\x2', '\x2', '\x538', '\x536', '\x3', '\x2', '\x2', '\x2', + '\x538', '\x539', '\x3', '\x2', '\x2', '\x2', '\x539', '\x541', '\x3', + '\x2', '\x2', '\x2', '\x53A', '\x53C', '\x5', '\x14D', '\xA7', '\x2', + '\x53B', '\x53D', '\x5', '\x14F', '\xA8', '\x2', '\x53C', '\x53B', '\x3', + '\x2', '\x2', '\x2', '\x53D', '\x53E', '\x3', '\x2', '\x2', '\x2', '\x53E', + '\x53C', '\x3', '\x2', '\x2', '\x2', '\x53E', '\x53F', '\x3', '\x2', '\x2', + '\x2', '\x53F', '\x541', '\x3', '\x2', '\x2', '\x2', '\x540', '\x52C', + '\x3', '\x2', '\x2', '\x2', '\x540', '\x530', '\x3', '\x2', '\x2', '\x2', + '\x540', '\x533', '\x3', '\x2', '\x2', '\x2', '\x540', '\x53A', '\x3', + '\x2', '\x2', '\x2', '\x541', '\x142', '\x3', '\x2', '\x2', '\x2', '\x542', + '\x544', '\t', '\n', '\x2', '\x2', '\x543', '\x542', '\x3', '\x2', '\x2', + '\x2', '\x544', '\x144', '\x3', '\x2', '\x2', '\x2', '\x545', '\x547', + '\t', '\v', '\x2', '\x2', '\x546', '\x545', '\x3', '\x2', '\x2', '\x2', + '\x547', '\x146', '\x3', '\x2', '\x2', '\x2', '\x548', '\x54A', '\x5', + '\x14B', '\xA6', '\x2', '\x549', '\x548', '\x3', '\x2', '\x2', '\x2', + '\x54A', '\x54B', '\x3', '\x2', '\x2', '\x2', '\x54B', '\x549', '\x3', + '\x2', '\x2', '\x2', '\x54B', '\x54C', '\x3', '\x2', '\x2', '\x2', '\x54C', + '\x148', '\x3', '\x2', '\x2', '\x2', '\x54D', '\x54F', '\t', '\xE', '\x2', + '\x2', '\x54E', '\x54D', '\x3', '\x2', '\x2', '\x2', '\x54F', '\x14A', + '\x3', '\x2', '\x2', '\x2', '\x550', '\x552', '\t', '\xF', '\x2', '\x2', + '\x551', '\x550', '\x3', '\x2', '\x2', '\x2', '\x552', '\x14C', '\x3', + '\x2', '\x2', '\x2', '\x553', '\x554', '\x5', '\x121', '\x91', '\x2', + '\x554', '\x14E', '\x3', '\x2', '\x2', '\x2', '\x555', '\x558', '\x5', + '\x145', '\xA3', '\x2', '\x556', '\x558', '\x5', '\x14B', '\xA6', '\x2', + '\x557', '\x555', '\x3', '\x2', '\x2', '\x2', '\x557', '\x556', '\x3', + '\x2', '\x2', '\x2', '\x558', '\x150', '\x3', '\x2', '\x2', '\x2', '\x559', + '\x55A', '\a', '?', '\x2', '\x2', '\x55A', '\x55B', '\a', '?', '\x2', + '\x2', '\x55B', '\x152', '\x3', '\x2', '\x2', '\x2', '\x55C', '\x55D', + '\a', '\x31', '\x2', '\x2', '\x55D', '\x55E', '\a', '\x31', '\x2', '\x2', + '\x55E', '\x562', '\x3', '\x2', '\x2', '\x2', '\x55F', '\x561', '\n', + '\f', '\x2', '\x2', '\x560', '\x55F', '\x3', '\x2', '\x2', '\x2', '\x561', + '\x564', '\x3', '\x2', '\x2', '\x2', '\x562', '\x560', '\x3', '\x2', '\x2', + '\x2', '\x562', '\x563', '\x3', '\x2', '\x2', '\x2', '\x563', '\x154', + '\x3', '\x2', '\x2', '\x2', '\x564', '\x562', '\x3', '\x2', '\x2', '\x2', + '%', '\x2', '\x469', '\x46F', '\x474', '\x47B', '\x481', '\x486', '\x48C', + '\x492', '\x499', '\x49F', '\x4A4', '\x4A8', '\x4AF', '\x4B3', '\x4D5', + '\x4D9', '\x4DE', '\x4E3', '\x4E6', '\x4EA', '\x4EF', '\x4F7', '\x52A', + '\x52E', '\x538', '\x53E', '\x540', '\x543', '\x546', '\x54B', '\x54E', + '\x551', '\x557', '\x562', '\x3', '\x2', '\x3', '\x2', + }; + + public static readonly ATN _ATN = + new ATNDeserializer().Deserialize(_serializedATN); + + +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs new file mode 100644 index 000000000000..cc5a5524278f --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs @@ -0,0 +1,1771 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// ANTLR Version: 4.9.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// Generated from SwiftInterface.g4 by ANTLR 4.9.1 + +// Unreachable code detected +#pragma warning disable 0162 +// The variable '...' is assigned but its value is never used +#pragma warning disable 0219 +// Missing XML comment for publicly visible type or member '...' +#pragma warning disable 1591 +// Ambiguous reference in cref attribute +#pragma warning disable 419 + +using Antlr4.Runtime.Misc; +using IParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener; +using IToken = Antlr4.Runtime.IToken; + +/// +/// This interface defines a complete listener for a parse tree produced by +/// . +/// +[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] +// [System.CLSCompliant(false)] +public interface ISwiftInterfaceListener : IParseTreeListener { + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterStatement([NotNull] SwiftInterfaceParser.StatementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitStatement([NotNull] SwiftInterfaceParser.StatementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterComment([NotNull] SwiftInterfaceParser.CommentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitComment([NotNull] SwiftInterfaceParser.CommentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterParameter([NotNull] SwiftInterfaceParser.ParameterContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitParameter([NotNull] SwiftInterfaceParser.ParameterContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAttribute([NotNull] SwiftInterfaceParser.AttributeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAttribute([NotNull] SwiftInterfaceParser.AttributeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAttributes([NotNull] SwiftInterfaceParser.AttributesContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAttributes([NotNull] SwiftInterfaceParser.AttributesContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterPattern([NotNull] SwiftInterfaceParser.PatternContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitPattern([NotNull] SwiftInterfaceParser.PatternContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context); + /// + /// Enter a parse tree produced by the dict_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context); + /// + /// Exit a parse tree produced by the dict_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context); + /// + /// Enter a parse tree produced by the any_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context); + /// + /// Exit a parse tree produced by the any_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context); + /// + /// Enter a parse tree produced by the identifier_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context); + /// + /// Exit a parse tree produced by the identifier_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context); + /// + /// Enter a parse tree produced by the func_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context); + /// + /// Exit a parse tree produced by the func_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context); + /// + /// Enter a parse tree produced by the arr_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context); + /// + /// Exit a parse tree produced by the arr_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context); + /// + /// Enter a parse tree produced by the meta_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context); + /// + /// Exit a parse tree produced by the meta_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context); + /// + /// Enter a parse tree produced by the boxed_protocol_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context); + /// + /// Exit a parse tree produced by the boxed_protocol_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context); + /// + /// Enter a parse tree produced by the optional_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context); + /// + /// Exit a parse tree produced by the optional_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context); + /// + /// Enter a parse tree produced by the self_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context); + /// + /// Exit a parse tree produced by the self_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context); + /// + /// Enter a parse tree produced by the unwrapped_optional_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context); + /// + /// Exit a parse tree produced by the unwrapped_optional_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context); + /// + /// Enter a parse tree produced by the proto_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context); + /// + /// Exit a parse tree produced by the proto_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context); + /// + /// Enter a parse tree produced by the tup_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context); + /// + /// Exit a parse tree produced by the tup_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context); + /// + /// Enter a parse tree produced by the self_long + /// labeled alternative in . + /// + /// The parse tree. + void EnterSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context); + /// + /// Exit a parse tree produced by the self_long + /// labeled alternative in . + /// + /// The parse tree. + void ExitSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context); + /// + /// Enter a parse tree produced by the proto_comp_type + /// labeled alternative in . + /// + /// The parse tree. + void EnterProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context); + /// + /// Exit a parse tree produced by the proto_comp_type + /// labeled alternative in . + /// + /// The parse tree. + void ExitProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterType_name([NotNull] SwiftInterfaceParser.Type_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitType_name([NotNull] SwiftInterfaceParser.Type_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterLiteral([NotNull] SwiftInterfaceParser.LiteralContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitLiteral([NotNull] SwiftInterfaceParser.LiteralContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterString_literal([NotNull] SwiftInterfaceParser.String_literalContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitString_literal([NotNull] SwiftInterfaceParser.String_literalContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRequirement([NotNull] SwiftInterfaceParser.RequirementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRequirement([NotNull] SwiftInterfaceParser.RequirementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterOperator([NotNull] SwiftInterfaceParser.OperatorContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitOperator([NotNull] SwiftInterfaceParser.OperatorContext context); + /// + /// Enter a parse tree produced by . + /// + /// The parse tree. + void EnterOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context); + /// + /// Exit a parse tree produced by . + /// + /// The parse tree. + void ExitOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context); +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs new file mode 100644 index 000000000000..4b6a57425975 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs @@ -0,0 +1,13120 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// ANTLR Version: 4.9.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// Generated from SwiftInterface.g4 by ANTLR 4.9.1 + +// Unreachable code detected +#pragma warning disable 0162 +// The variable '...' is assigned but its value is never used +#pragma warning disable 0219 +// Missing XML comment for publicly visible type or member '...' +#pragma warning disable 1591 +// Ambiguous reference in cref attribute +#pragma warning disable 419 + +using System; +using System.IO; +using System.Text; +using System.Diagnostics; +using System.Collections.Generic; +using Antlr4.Runtime; +using Antlr4.Runtime.Atn; +using Antlr4.Runtime.Misc; +using Antlr4.Runtime.Tree; +using DFA = Antlr4.Runtime.Dfa.DFA; + +[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] +// [System.CLSCompliant(false)] +public partial class SwiftInterfaceParser : Parser { + protected static DFA[] decisionToDFA; + protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); + public const int + T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, + T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, + T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24, + T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31, + T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, T__37=38, + T__38=39, T__39=40, T__40=41, T__41=42, T__42=43, T__43=44, T__44=45, + T__45=46, T__46=47, T__47=48, T__48=49, T__49=50, T__50=51, T__51=52, + T__52=53, T__53=54, T__54=55, T__55=56, T__56=57, T__57=58, T__58=59, + T__59=60, T__60=61, T__61=62, T__62=63, T__63=64, T__64=65, T__65=66, + T__66=67, T__67=68, T__68=69, T__69=70, T__70=71, T__71=72, T__72=73, + T__73=74, T__74=75, T__75=76, T__76=77, T__77=78, T__78=79, T__79=80, + T__80=81, T__81=82, T__82=83, T__83=84, T__84=85, T__85=86, T__86=87, + T__87=88, T__88=89, T__89=90, T__90=91, T__91=92, T__92=93, T__93=94, + T__94=95, T__95=96, T__96=97, T__97=98, T__98=99, T__99=100, T__100=101, + T__101=102, T__102=103, T__103=104, T__104=105, T__105=106, T__106=107, + T__107=108, T__108=109, T__109=110, T__110=111, T__111=112, Binary_literal=113, + Octal_literal=114, Decimal_literal=115, Pure_decimal_digits=116, Hexadecimal_literal=117, + Static_string_literal=118, Identifier=119, Implicit_parameter_name=120, + WS=121, OpPlus=122, OpMinus=123, OpAssign=124, OpAmp=125, OpQuestion=126, + OpLess=127, OpBang=128, OpDot=129, OpComma=130, OpTilde=131, OpColon=132, + OpSemi=133, OpAt=134, OpPound=135, OpBackTick=136, OpUnder=137, OpLParen=138, + OpRParen=139, OpLBracket=140, OpRBracket=141, OpLBrace=142, OpRBrace=143, + Decimal_digits=144, Operator=145, DotOperatorHead=146, DotOperatorFollow=147, + OpEqEq=148, Comment_line=149, OpGreater=150; + public const int + RULE_swiftinterface = 0, RULE_statement = 1, RULE_comment = 2, RULE_declaration = 3, + RULE_nominal_declaration = 4, RULE_import_statement = 5, RULE_import_kind = 6, + RULE_import_path = 7, RULE_import_path_identifier = 8, RULE_variable_declaration = 9, + RULE_variable_declaration_head = 10, RULE_variable_declaration_tail = 11, + RULE_variable_name = 12, RULE_var_clause = 13, RULE_let_clause = 14, RULE_getter_setter_keyword_block = 15, + RULE_getter_keyword_clause = 16, RULE_setter_keyword_clause = 17, RULE_new_value_name = 18, + RULE_typealias_declaration = 19, RULE_typealias_name = 20, RULE_typealias_assignment = 21, + RULE_enum_declaration = 22, RULE_union_style_enum = 23, RULE_union_style_enum_members = 24, + RULE_union_style_enum_member = 25, RULE_union_style_enum_case_clause = 26, + RULE_union_style_enum_case_list = 27, RULE_union_style_enum_case = 28, + RULE_enum_name = 29, RULE_enum_case_name = 30, RULE_raw_value_style_enum = 31, + RULE_raw_value_style_enum_members = 32, RULE_raw_value_style_enum_member = 33, + RULE_raw_value_style_enum_case_clause = 34, RULE_raw_value_style_enum_case_list = 35, + RULE_raw_value_style_enum_case = 36, RULE_raw_value_assignment = 37, RULE_raw_value_literal = 38, + RULE_struct_declaration = 39, RULE_struct_name = 40, RULE_struct_body = 41, + RULE_struct_member = 42, RULE_class_declaration = 43, RULE_class_name = 44, + RULE_class_body = 45, RULE_class_member = 46, RULE_final_clause = 47, + RULE_protocol_declaration = 48, RULE_protocol_name = 49, RULE_protocol_body = 50, + RULE_protocol_member = 51, RULE_protocol_member_declaration = 52, RULE_operator_declaration = 53, + RULE_prefix_operator_declaration = 54, RULE_postfix_operator_declaration = 55, + RULE_infix_operator_declaration = 56, RULE_infix_operator_group = 57, + RULE_precedence_group_declaration = 58, RULE_precedence_group_attribute = 59, + RULE_precedence_group_relation = 60, RULE_precedence_group_assignment = 61, + RULE_precedence_group_associativity = 62, RULE_associativity = 63, RULE_precedence_group_names = 64, + RULE_precedence_group_name = 65, RULE_extension_declaration = 66, RULE_extension_body = 67, + RULE_extension_member = 68, RULE_subscript_declaration = 69, RULE_subscript_head = 70, + RULE_subscript_result = 71, RULE_protocol_associated_type_declaration = 72, + RULE_function_declaration = 73, RULE_function_head = 74, RULE_function_name = 75, + RULE_function_body = 76, RULE_operator_name = 77, RULE_function_signature = 78, + RULE_async_clause = 79, RULE_throws_clause = 80, RULE_rethrows_clause = 81, + RULE_function_result = 82, RULE_initializer_declaration = 83, RULE_initializer_head = 84, + RULE_deinitializer_declaration = 85, RULE_parameter_clause = 86, RULE_parameter_list = 87, + RULE_parameter = 88, RULE_external_parameter_name = 89, RULE_local_parameter_name = 90, + RULE_defaultInitializer = 91, RULE_dyckExpression = 92, RULE_dyckSubExpression = 93, + RULE_any_other_things_for_dyck_expression = 94, RULE_dotSymbol = 95, RULE_declaration_identifier = 96, + RULE_type_inheritance_clause = 97, RULE_type_inheritance_list = 98, RULE_class_requirement = 99, + RULE_attribute = 100, RULE_attribute_name = 101, RULE_attribute_argument_clause = 102, + RULE_attributes = 103, RULE_balanced_tokens = 104, RULE_balanced_token = 105, + RULE_any_punctuation_for_balanced_token = 106, RULE_declaration_modifier = 107, + RULE_declaration_modifiers = 108, RULE_access_level_modifier = 109, RULE_mutation_modifier = 110, + RULE_pattern = 111, RULE_wildcard_pattern = 112, RULE_identifier_pattern = 113, + RULE_function_type = 114, RULE_function_type_argument_clause = 115, RULE_function_type_argument_list = 116, + RULE_function_type_argument = 117, RULE_argument_label = 118, RULE_type = 119, + RULE_type_annotation = 120, RULE_any_clause = 121, RULE_inout_clause = 122, + RULE_type_identifier = 123, RULE_type_name = 124, RULE_tuple_type = 125, + RULE_tuple_type_element_list = 126, RULE_tuple_type_element = 127, RULE_element_name = 128, + RULE_array_type = 129, RULE_dictionary_type = 130, RULE_protocol_composition_type = 131, + RULE_protocol_identifier = 132, RULE_literal = 133, RULE_nil_literal = 134, + RULE_boolean_literal = 135, RULE_numeric_literal = 136, RULE_integer_literal = 137, + RULE_string_literal = 138, RULE_label_identifier = 139, RULE_generic_parameter_clause = 140, + RULE_generic_parameter_list = 141, RULE_generic_parameter = 142, RULE_generic_where_clause = 143, + RULE_requirement_list = 144, RULE_requirement = 145, RULE_conformance_requirement = 146, + RULE_same_type_requirement = 147, RULE_generic_argument_clause = 148, + RULE_generic_argument_list = 149, RULE_generic_argument = 150, RULE_opGreater = 151, + RULE_arrow_operator = 152, RULE_range_operator = 153, RULE_keyword_as_identifier_in_declarations = 154, + RULE_keyword_as_identifier_in_labels = 155, RULE_operator = 156, RULE_operator_angles = 157; + public static readonly string[] ruleNames = { + "swiftinterface", "statement", "comment", "declaration", "nominal_declaration", + "import_statement", "import_kind", "import_path", "import_path_identifier", + "variable_declaration", "variable_declaration_head", "variable_declaration_tail", + "variable_name", "var_clause", "let_clause", "getter_setter_keyword_block", + "getter_keyword_clause", "setter_keyword_clause", "new_value_name", "typealias_declaration", + "typealias_name", "typealias_assignment", "enum_declaration", "union_style_enum", + "union_style_enum_members", "union_style_enum_member", "union_style_enum_case_clause", + "union_style_enum_case_list", "union_style_enum_case", "enum_name", "enum_case_name", + "raw_value_style_enum", "raw_value_style_enum_members", "raw_value_style_enum_member", + "raw_value_style_enum_case_clause", "raw_value_style_enum_case_list", + "raw_value_style_enum_case", "raw_value_assignment", "raw_value_literal", + "struct_declaration", "struct_name", "struct_body", "struct_member", "class_declaration", + "class_name", "class_body", "class_member", "final_clause", "protocol_declaration", + "protocol_name", "protocol_body", "protocol_member", "protocol_member_declaration", + "operator_declaration", "prefix_operator_declaration", "postfix_operator_declaration", + "infix_operator_declaration", "infix_operator_group", "precedence_group_declaration", + "precedence_group_attribute", "precedence_group_relation", "precedence_group_assignment", + "precedence_group_associativity", "associativity", "precedence_group_names", + "precedence_group_name", "extension_declaration", "extension_body", "extension_member", + "subscript_declaration", "subscript_head", "subscript_result", "protocol_associated_type_declaration", + "function_declaration", "function_head", "function_name", "function_body", + "operator_name", "function_signature", "async_clause", "throws_clause", + "rethrows_clause", "function_result", "initializer_declaration", "initializer_head", + "deinitializer_declaration", "parameter_clause", "parameter_list", "parameter", + "external_parameter_name", "local_parameter_name", "defaultInitializer", + "dyckExpression", "dyckSubExpression", "any_other_things_for_dyck_expression", + "dotSymbol", "declaration_identifier", "type_inheritance_clause", "type_inheritance_list", + "class_requirement", "attribute", "attribute_name", "attribute_argument_clause", + "attributes", "balanced_tokens", "balanced_token", "any_punctuation_for_balanced_token", + "declaration_modifier", "declaration_modifiers", "access_level_modifier", + "mutation_modifier", "pattern", "wildcard_pattern", "identifier_pattern", + "function_type", "function_type_argument_clause", "function_type_argument_list", + "function_type_argument", "argument_label", "type", "type_annotation", + "any_clause", "inout_clause", "type_identifier", "type_name", "tuple_type", + "tuple_type_element_list", "tuple_type_element", "element_name", "array_type", + "dictionary_type", "protocol_composition_type", "protocol_identifier", + "literal", "nil_literal", "boolean_literal", "numeric_literal", "integer_literal", + "string_literal", "label_identifier", "generic_parameter_clause", "generic_parameter_list", + "generic_parameter", "generic_where_clause", "requirement_list", "requirement", + "conformance_requirement", "same_type_requirement", "generic_argument_clause", + "generic_argument_list", "generic_argument", "opGreater", "arrow_operator", + "range_operator", "keyword_as_identifier_in_declarations", "keyword_as_identifier_in_labels", + "operator", "operator_angles" + }; + + private static readonly string[] _LiteralNames = { + null, "'import'", "'typealias'", "'struct'", "'class'", "'enum'", "'protocol'", + "'var'", "'func'", "'let'", "'get'", "'set'", "'indirect'", "'case'", + "'final'", "'prefix'", "'operator'", "'postfix'", "'infix'", "'precedencegroup'", + "'higherThan'", "'lowerThan'", "'assignment'", "'associativity'", "'left'", + "'right'", "'none'", "'extension'", "'subscript'", "'associatedtype'", + "'async'", "'throws'", "'rethrows'", "'init'", "'deinit'", "'convenience'", + "'dynamic'", "'lazy'", "'optional'", "'override'", "'required'", "'static'", + "'unowned'", "'safe'", "'unsafe'", "'weak'", "'private'", "'fileprivate'", + "'internal'", "'public'", "'open'", "'mutating'", "'nonmutating'", "'is'", + "'as'", "'Type'", "'Protocol'", "'Any'", "'Self'", "'any'", "'inout'", + "'nil'", "'true'", "'false'", "'where'", "'>'", "'->'", "'...'", "'alpha'", + "'arch'", "'arm'", "'arm64'", "'blue'", "'didSet'", "'file'", "'green'", + "'i386'", "'iOS'", "'iOSApplicationExtension'", "'line'", "'macOS'", "'macOSApplicationExtension'", + "'of'", "'os'", "'precedence'", "'red'", "'resourceName'", "'swift'", + "'tvOS'", "'type'", "'watchOS'", "'willSet'", "'x86_64'", "'break'", "'catch'", + "'continue'", "'default'", "'defer'", "'do'", "'else'", "'fallthrough'", + "'for'", "'guard'", "'if'", "'in'", "'repeat'", "'return'", "'self'", + "'super'", "'switch'", "'throw'", "'try'", "'while'", null, null, null, + null, null, null, null, null, null, "'+'", "'-'", "'='", "'&'", "'?'", + "'<'", "'!'", "'.'", "','", "'~'", "':'", "';'", "'@'", "'#'", "'`'", + "'_'", "'('", "')'", "'['", "']'", "'{'", "'}'", null, null, null, null, + "'=='" + }; + private static readonly string[] _SymbolicNames = { + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, "Binary_literal", "Octal_literal", "Decimal_literal", + "Pure_decimal_digits", "Hexadecimal_literal", "Static_string_literal", + "Identifier", "Implicit_parameter_name", "WS", "OpPlus", "OpMinus", "OpAssign", + "OpAmp", "OpQuestion", "OpLess", "OpBang", "OpDot", "OpComma", "OpTilde", + "OpColon", "OpSemi", "OpAt", "OpPound", "OpBackTick", "OpUnder", "OpLParen", + "OpRParen", "OpLBracket", "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", + "Operator", "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line", + "OpGreater" + }; + public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); + + [NotNull] + public override IVocabulary Vocabulary + { + get + { + return DefaultVocabulary; + } + } + + public override string GrammarFileName { get { return "SwiftInterface.g4"; } } + + public override string[] RuleNames { get { return ruleNames; } } + + public override string SerializedAtn { get { return new string(_serializedATN); } } + + static SwiftInterfaceParser() { + decisionToDFA = new DFA[_ATN.NumberOfDecisions]; + for (int i = 0; i < _ATN.NumberOfDecisions; i++) { + decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); + } + } + + public SwiftInterfaceParser(ITokenStream input) : this(input, Console.Out, Console.Error) { } + + public SwiftInterfaceParser(ITokenStream input, TextWriter output, TextWriter errorOutput) + : base(input, output, errorOutput) + { + Interpreter = new ParserATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); + } + + public partial class SwiftinterfaceContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public StatementContext[] statement() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public StatementContext statement(int i) { + return GetRuleContext(i); + } + public SwiftinterfaceContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_swiftinterface; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSwiftinterface(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSwiftinterface(this); + } + } + + [RuleVersion(0)] + public SwiftinterfaceContext swiftinterface() { + SwiftinterfaceContext _localctx = new SwiftinterfaceContext(Context, State); + EnterRule(_localctx, 0, RULE_swiftinterface); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 319; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt || _la==Comment_line) { + { + { + State = 316; + statement(); + } + } + State = 321; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class StatementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Import_statementContext import_statement() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public DeclarationContext declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public CommentContext comment() { + return GetRuleContext(0); + } + public StatementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_statement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterStatement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitStatement(this); + } + } + + [RuleVersion(0)] + public StatementContext statement() { + StatementContext _localctx = new StatementContext(Context, State); + EnterRule(_localctx, 2, RULE_statement); + try { + State = 325; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,1,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 322; + import_statement(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 323; + declaration(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 324; + comment(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class CommentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Comment_line() { return GetToken(SwiftInterfaceParser.Comment_line, 0); } + public CommentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_comment; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterComment(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitComment(this); + } + } + + [RuleVersion(0)] + public CommentContext comment() { + CommentContext _localctx = new CommentContext(Context, State); + EnterRule(_localctx, 4, RULE_comment); + try { + EnterOuterAlt(_localctx, 1); + { + State = 327; + Match(Comment_line); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class DeclarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Enum_declarationContext enum_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Struct_declarationContext struct_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Class_declarationContext class_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_declarationContext protocol_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Extension_declarationContext extension_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Operator_declarationContext operator_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_declarationContext precedence_group_declaration() { + return GetRuleContext(0); + } + public DeclarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDeclaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDeclaration(this); + } + } + + [RuleVersion(0)] + public DeclarationContext declaration() { + DeclarationContext _localctx = new DeclarationContext(Context, State); + EnterRule(_localctx, 6, RULE_declaration); + try { + State = 340; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,2,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 329; + variable_declaration(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 330; + typealias_declaration(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 331; + function_declaration(); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 332; + enum_declaration(); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 333; + struct_declaration(); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 334; + class_declaration(); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 335; + protocol_declaration(); + } + break; + case 8: + EnterOuterAlt(_localctx, 8); + { + State = 336; + extension_declaration(); + } + break; + case 9: + EnterOuterAlt(_localctx, 9); + { + State = 337; + subscript_declaration(); + } + break; + case 10: + EnterOuterAlt(_localctx, 10); + { + State = 338; + operator_declaration(); + } + break; + case 11: + EnterOuterAlt(_localctx, 11); + { + State = 339; + precedence_group_declaration(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Nominal_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Enum_declarationContext enum_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Struct_declarationContext struct_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Class_declarationContext class_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_declarationContext protocol_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Initializer_declarationContext initializer_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Deinitializer_declarationContext deinitializer_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Extension_declarationContext extension_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Operator_declarationContext operator_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_declarationContext precedence_group_declaration() { + return GetRuleContext(0); + } + public Nominal_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_nominal_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterNominal_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitNominal_declaration(this); + } + } + + [RuleVersion(0)] + public Nominal_declarationContext nominal_declaration() { + Nominal_declarationContext _localctx = new Nominal_declarationContext(Context, State); + EnterRule(_localctx, 8, RULE_nominal_declaration); + try { + State = 355; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,3,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 342; + variable_declaration(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 343; + typealias_declaration(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 344; + function_declaration(); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 345; + enum_declaration(); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 346; + struct_declaration(); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 347; + class_declaration(); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 348; + protocol_declaration(); + } + break; + case 8: + EnterOuterAlt(_localctx, 8); + { + State = 349; + initializer_declaration(); + } + break; + case 9: + EnterOuterAlt(_localctx, 9); + { + State = 350; + deinitializer_declaration(); + } + break; + case 10: + EnterOuterAlt(_localctx, 10); + { + State = 351; + extension_declaration(); + } + break; + case 11: + EnterOuterAlt(_localctx, 11); + { + State = 352; + subscript_declaration(); + } + break; + case 12: + EnterOuterAlt(_localctx, 12); + { + State = 353; + operator_declaration(); + } + break; + case 13: + EnterOuterAlt(_localctx, 13); + { + State = 354; + precedence_group_declaration(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Import_statementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Import_pathContext import_path() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Import_kindContext import_kind() { + return GetRuleContext(0); + } + public Import_statementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_import_statement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterImport_statement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitImport_statement(this); + } + } + + [RuleVersion(0)] + public Import_statementContext import_statement() { + Import_statementContext _localctx = new Import_statementContext(Context, State); + EnterRule(_localctx, 10, RULE_import_statement); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 358; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 357; + attributes(); + } + } + + State = 360; + Match(T__0); + State = 362; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7))) != 0)) { + { + State = 361; + import_kind(); + } + } + + State = 364; + import_path(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Import_kindContext : ParserRuleContext { + public Import_kindContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_import_kind; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterImport_kind(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitImport_kind(this); + } + } + + [RuleVersion(0)] + public Import_kindContext import_kind() { + Import_kindContext _localctx = new Import_kindContext(Context, State); + EnterRule(_localctx, 12, RULE_import_kind); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 366; + _la = TokenStream.LA(1); + if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Import_pathContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Import_path_identifierContext[] import_path_identifier() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Import_path_identifierContext import_path_identifier(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpDot() { return GetTokens(SwiftInterfaceParser.OpDot); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot(int i) { + return GetToken(SwiftInterfaceParser.OpDot, i); + } + public Import_pathContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_import_path; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterImport_path(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitImport_path(this); + } + } + + [RuleVersion(0)] + public Import_pathContext import_path() { + Import_pathContext _localctx = new Import_pathContext(Context, State); + EnterRule(_localctx, 14, RULE_import_path); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 368; + import_path_identifier(); + State = 373; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpDot) { + { + { + State = 369; + Match(OpDot); + State = 370; + import_path_identifier(); + } + } + State = 375; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Import_path_identifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Import_path_identifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_import_path_identifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterImport_path_identifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitImport_path_identifier(this); + } + } + + [RuleVersion(0)] + public Import_path_identifierContext import_path_identifier() { + Import_path_identifierContext _localctx = new Import_path_identifierContext(Context, State); + EnterRule(_localctx, 16, RULE_import_path_identifier); + try { + EnterOuterAlt(_localctx, 1); + { + State = 376; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Variable_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_headContext variable_declaration_head() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_tailContext[] variable_declaration_tail() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_tailContext variable_declaration_tail(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Variable_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_variable_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterVariable_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitVariable_declaration(this); + } + } + + [RuleVersion(0)] + public Variable_declarationContext variable_declaration() { + Variable_declarationContext _localctx = new Variable_declarationContext(Context, State); + EnterRule(_localctx, 18, RULE_variable_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 378; + variable_declaration_head(); + State = 379; + variable_declaration_tail(); + State = 384; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 380; + Match(OpComma); + State = 381; + variable_declaration_tail(); + } + } + State = 386; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Variable_declaration_headContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Var_clauseContext var_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Let_clauseContext let_clause() { + return GetRuleContext(0); + } + public Variable_declaration_headContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_variable_declaration_head; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterVariable_declaration_head(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitVariable_declaration_head(this); + } + } + + [RuleVersion(0)] + public Variable_declaration_headContext variable_declaration_head() { + Variable_declaration_headContext _localctx = new Variable_declaration_headContext(Context, State); + EnterRule(_localctx, 20, RULE_variable_declaration_head); + int _la; + try { + State = 401; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,12,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 388; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 387; + attributes(); + } + } + + State = 391; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 390; + declaration_modifiers(); + } + } + + State = 393; + var_clause(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 395; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 394; + attributes(); + } + } + + State = 398; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 397; + declaration_modifiers(); + } + } + + State = 400; + let_clause(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Variable_declaration_tailContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Variable_nameContext variable_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Getter_setter_keyword_blockContext getter_setter_keyword_block() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public DefaultInitializerContext defaultInitializer() { + return GetRuleContext(0); + } + public Variable_declaration_tailContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_variable_declaration_tail; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterVariable_declaration_tail(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitVariable_declaration_tail(this); + } + } + + [RuleVersion(0)] + public Variable_declaration_tailContext variable_declaration_tail() { + Variable_declaration_tailContext _localctx = new Variable_declaration_tailContext(Context, State); + EnterRule(_localctx, 22, RULE_variable_declaration_tail); + int _la; + try { + State = 413; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,15,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 403; + variable_name(); + State = 404; + type_annotation(); + State = 406; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLBrace) { + { + State = 405; + getter_setter_keyword_block(); + } + } + + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 408; + variable_name(); + State = 409; + type_annotation(); + State = 411; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAssign) { + { + State = 410; + defaultInitializer(); + } + } + + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Variable_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Variable_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_variable_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterVariable_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitVariable_name(this); + } + } + + [RuleVersion(0)] + public Variable_nameContext variable_name() { + Variable_nameContext _localctx = new Variable_nameContext(Context, State); + EnterRule(_localctx, 24, RULE_variable_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 415; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Var_clauseContext : ParserRuleContext { + public Var_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_var_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterVar_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitVar_clause(this); + } + } + + [RuleVersion(0)] + public Var_clauseContext var_clause() { + Var_clauseContext _localctx = new Var_clauseContext(Context, State); + EnterRule(_localctx, 26, RULE_var_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 417; + Match(T__6); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Let_clauseContext : ParserRuleContext { + public Let_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_let_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterLet_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitLet_clause(this); + } + } + + [RuleVersion(0)] + public Let_clauseContext let_clause() { + Let_clauseContext _localctx = new Let_clauseContext(Context, State); + EnterRule(_localctx, 28, RULE_let_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 419; + Match(T__8); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Getter_setter_keyword_blockContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Getter_keyword_clauseContext getter_keyword_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Setter_keyword_clauseContext setter_keyword_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + public Getter_setter_keyword_blockContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_getter_setter_keyword_block; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGetter_setter_keyword_block(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGetter_setter_keyword_block(this); + } + } + + [RuleVersion(0)] + public Getter_setter_keyword_blockContext getter_setter_keyword_block() { + Getter_setter_keyword_blockContext _localctx = new Getter_setter_keyword_blockContext(Context, State); + EnterRule(_localctx, 30, RULE_getter_setter_keyword_block); + try { + State = 435; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,16,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 421; + Match(OpLBrace); + State = 422; + getter_keyword_clause(); + State = 423; + setter_keyword_clause(); + State = 424; + Match(OpRBrace); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 426; + Match(OpLBrace); + State = 427; + setter_keyword_clause(); + State = 428; + getter_keyword_clause(); + State = 429; + Match(OpRBrace); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 431; + Match(OpLBrace); + State = 432; + getter_keyword_clause(); + State = 433; + Match(OpRBrace); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Getter_keyword_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Async_clauseContext async_clause() { + return GetRuleContext(0); + } + public Getter_keyword_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_getter_keyword_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGetter_keyword_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGetter_keyword_clause(this); + } + } + + [RuleVersion(0)] + public Getter_keyword_clauseContext getter_keyword_clause() { + Getter_keyword_clauseContext _localctx = new Getter_keyword_clauseContext(Context, State); + EnterRule(_localctx, 32, RULE_getter_keyword_clause); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 438; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 437; + attributes(); + } + } + + State = 441; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__50 || _la==T__51) { + { + State = 440; + mutation_modifier(); + } + } + + State = 443; + Match(T__9); + State = 445; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__29) { + { + State = 444; + async_clause(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Setter_keyword_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public New_value_nameContext new_value_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + public Setter_keyword_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_setter_keyword_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSetter_keyword_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSetter_keyword_clause(this); + } + } + + [RuleVersion(0)] + public Setter_keyword_clauseContext setter_keyword_clause() { + Setter_keyword_clauseContext _localctx = new Setter_keyword_clauseContext(Context, State); + EnterRule(_localctx, 34, RULE_setter_keyword_clause); + int _la; + try { + State = 465; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,24,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 448; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 447; + attributes(); + } + } + + State = 451; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__50 || _la==T__51) { + { + State = 450; + mutation_modifier(); + } + } + + State = 453; + Match(T__10); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 455; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 454; + attributes(); + } + } + + State = 458; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__50 || _la==T__51) { + { + State = 457; + mutation_modifier(); + } + } + + State = 460; + Match(T__10); + State = 461; + Match(OpLParen); + State = 462; + new_value_name(); + State = 463; + Match(OpRParen); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class New_value_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public New_value_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_new_value_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterNew_value_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitNew_value_name(this); + } + } + + [RuleVersion(0)] + public New_value_nameContext new_value_name() { + New_value_nameContext _localctx = new New_value_nameContext(Context, State); + EnterRule(_localctx, 36, RULE_new_value_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 467; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Typealias_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Typealias_nameContext typealias_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Typealias_assignmentContext typealias_assignment() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + public Typealias_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_typealias_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTypealias_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTypealias_declaration(this); + } + } + + [RuleVersion(0)] + public Typealias_declarationContext typealias_declaration() { + Typealias_declarationContext _localctx = new Typealias_declarationContext(Context, State); + EnterRule(_localctx, 38, RULE_typealias_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 470; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 469; + attributes(); + } + } + + State = 473; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 472; + access_level_modifier(); + } + } + + State = 475; + Match(T__1); + State = 476; + typealias_name(); + State = 478; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 477; + generic_parameter_clause(); + } + } + + State = 480; + typealias_assignment(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Typealias_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Typealias_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_typealias_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTypealias_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTypealias_name(this); + } + } + + [RuleVersion(0)] + public Typealias_nameContext typealias_name() { + Typealias_nameContext _localctx = new Typealias_nameContext(Context, State); + EnterRule(_localctx, 40, RULE_typealias_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 482; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Typealias_assignmentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + public Typealias_assignmentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_typealias_assignment; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTypealias_assignment(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTypealias_assignment(this); + } + } + + [RuleVersion(0)] + public Typealias_assignmentContext typealias_assignment() { + Typealias_assignmentContext _localctx = new Typealias_assignmentContext(Context, State); + EnterRule(_localctx, 42, RULE_typealias_assignment); + try { + EnterOuterAlt(_localctx, 1); + { + State = 484; + Match(OpAssign); + State = 485; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Enum_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enumContext union_style_enum() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enumContext raw_value_style_enum() { + return GetRuleContext(0); + } + public Enum_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_enum_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterEnum_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitEnum_declaration(this); + } + } + + [RuleVersion(0)] + public Enum_declarationContext enum_declaration() { + Enum_declarationContext _localctx = new Enum_declarationContext(Context, State); + EnterRule(_localctx, 44, RULE_enum_declaration); + int _la; + try { + State = 501; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,32,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 488; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 487; + attributes(); + } + } + + State = 491; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 490; + access_level_modifier(); + } + } + + State = 493; + union_style_enum(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 495; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 494; + attributes(); + } + } + + State = 498; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 497; + access_level_modifier(); + } + } + + State = 500; + raw_value_style_enum(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enumContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Enum_nameContext enum_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_membersContext union_style_enum_members() { + return GetRuleContext(0); + } + public Union_style_enumContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum(this); + } + } + + [RuleVersion(0)] + public Union_style_enumContext union_style_enum() { + Union_style_enumContext _localctx = new Union_style_enumContext(Context, State); + EnterRule(_localctx, 46, RULE_union_style_enum); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 504; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__11) { + { + State = 503; + Match(T__11); + } + } + + State = 506; + Match(T__4); + State = 507; + enum_name(); + State = 509; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 508; + generic_parameter_clause(); + } + } + + State = 512; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 511; + type_inheritance_clause(); + } + } + + State = 515; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 514; + generic_where_clause(); + } + } + + State = 517; + Match(OpLBrace); + State = 519; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + State = 518; + union_style_enum_members(); + } + } + + State = 521; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enum_membersContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_memberContext union_style_enum_member() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_membersContext union_style_enum_members() { + return GetRuleContext(0); + } + public Union_style_enum_membersContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum_members; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum_members(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum_members(this); + } + } + + [RuleVersion(0)] + public Union_style_enum_membersContext union_style_enum_members() { + Union_style_enum_membersContext _localctx = new Union_style_enum_membersContext(Context, State); + EnterRule(_localctx, 48, RULE_union_style_enum_members); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 523; + union_style_enum_member(); + State = 525; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + State = 524; + union_style_enum_members(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enum_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_clauseContext union_style_enum_case_clause() { + return GetRuleContext(0); + } + public Union_style_enum_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum_member(this); + } + } + + [RuleVersion(0)] + public Union_style_enum_memberContext union_style_enum_member() { + Union_style_enum_memberContext _localctx = new Union_style_enum_memberContext(Context, State); + EnterRule(_localctx, 50, RULE_union_style_enum_member); + try { + State = 529; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,39,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 527; + nominal_declaration(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 528; + union_style_enum_case_clause(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enum_case_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_listContext union_style_enum_case_list() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + public Union_style_enum_case_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum_case_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum_case_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum_case_clause(this); + } + } + + [RuleVersion(0)] + public Union_style_enum_case_clauseContext union_style_enum_case_clause() { + Union_style_enum_case_clauseContext _localctx = new Union_style_enum_case_clauseContext(Context, State); + EnterRule(_localctx, 52, RULE_union_style_enum_case_clause); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 532; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 531; + attributes(); + } + } + + State = 535; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__11) { + { + State = 534; + Match(T__11); + } + } + + State = 537; + Match(T__12); + State = 538; + union_style_enum_case_list(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enum_case_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_caseContext union_style_enum_case() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_listContext union_style_enum_case_list() { + return GetRuleContext(0); + } + public Union_style_enum_case_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum_case_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum_case_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum_case_list(this); + } + } + + [RuleVersion(0)] + public Union_style_enum_case_listContext union_style_enum_case_list() { + Union_style_enum_case_listContext _localctx = new Union_style_enum_case_listContext(Context, State); + EnterRule(_localctx, 54, RULE_union_style_enum_case_list); + try { + State = 545; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,42,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 540; + union_style_enum_case(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 541; + union_style_enum_case(); + State = 542; + Match(OpComma); + State = 543; + union_style_enum_case_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Union_style_enum_caseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Enum_case_nameContext enum_case_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Tuple_typeContext tuple_type() { + return GetRuleContext(0); + } + public Union_style_enum_caseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_union_style_enum_case; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnion_style_enum_case(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnion_style_enum_case(this); + } + } + + [RuleVersion(0)] + public Union_style_enum_caseContext union_style_enum_case() { + Union_style_enum_caseContext _localctx = new Union_style_enum_caseContext(Context, State); + EnterRule(_localctx, 56, RULE_union_style_enum_case); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 547; + enum_case_name(); + State = 549; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLParen) { + { + State = 548; + tuple_type(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Enum_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Enum_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_enum_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterEnum_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitEnum_name(this); + } + } + + [RuleVersion(0)] + public Enum_nameContext enum_name() { + Enum_nameContext _localctx = new Enum_nameContext(Context, State); + EnterRule(_localctx, 58, RULE_enum_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 551; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Enum_case_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Enum_case_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_enum_case_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterEnum_case_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitEnum_case_name(this); + } + } + + [RuleVersion(0)] + public Enum_case_nameContext enum_case_name() { + Enum_case_nameContext _localctx = new Enum_case_nameContext(Context, State); + EnterRule(_localctx, 60, RULE_enum_case_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 553; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enumContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Enum_nameContext enum_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_membersContext raw_value_style_enum_members() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + public Raw_value_style_enumContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enumContext raw_value_style_enum() { + Raw_value_style_enumContext _localctx = new Raw_value_style_enumContext(Context, State); + EnterRule(_localctx, 62, RULE_raw_value_style_enum); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 555; + Match(T__4); + State = 556; + enum_name(); + State = 558; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 557; + generic_parameter_clause(); + } + } + + State = 560; + type_inheritance_clause(); + State = 562; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 561; + generic_where_clause(); + } + } + + State = 564; + Match(OpLBrace); + State = 565; + raw_value_style_enum_members(); + State = 566; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enum_membersContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_memberContext raw_value_style_enum_member() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_membersContext raw_value_style_enum_members() { + return GetRuleContext(0); + } + public Raw_value_style_enum_membersContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum_members; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum_members(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum_members(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enum_membersContext raw_value_style_enum_members() { + Raw_value_style_enum_membersContext _localctx = new Raw_value_style_enum_membersContext(Context, State); + EnterRule(_localctx, 64, RULE_raw_value_style_enum_members); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 568; + raw_value_style_enum_member(); + State = 570; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + State = 569; + raw_value_style_enum_members(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enum_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_clauseContext raw_value_style_enum_case_clause() { + return GetRuleContext(0); + } + public Raw_value_style_enum_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum_member(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enum_memberContext raw_value_style_enum_member() { + Raw_value_style_enum_memberContext _localctx = new Raw_value_style_enum_memberContext(Context, State); + EnterRule(_localctx, 66, RULE_raw_value_style_enum_member); + try { + State = 574; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,47,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 572; + nominal_declaration(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 573; + raw_value_style_enum_case_clause(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enum_case_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + public Raw_value_style_enum_case_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum_case_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum_case_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum_case_clause(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enum_case_clauseContext raw_value_style_enum_case_clause() { + Raw_value_style_enum_case_clauseContext _localctx = new Raw_value_style_enum_case_clauseContext(Context, State); + EnterRule(_localctx, 68, RULE_raw_value_style_enum_case_clause); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 577; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 576; + attributes(); + } + } + + State = 579; + Match(T__12); + State = 580; + raw_value_style_enum_case_list(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enum_case_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_caseContext raw_value_style_enum_case() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { + return GetRuleContext(0); + } + public Raw_value_style_enum_case_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum_case_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum_case_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum_case_list(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { + Raw_value_style_enum_case_listContext _localctx = new Raw_value_style_enum_case_listContext(Context, State); + EnterRule(_localctx, 70, RULE_raw_value_style_enum_case_list); + try { + State = 587; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,49,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 582; + raw_value_style_enum_case(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 583; + raw_value_style_enum_case(); + State = 584; + Match(OpComma); + State = 585; + raw_value_style_enum_case_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_style_enum_caseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Enum_case_nameContext enum_case_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_assignmentContext raw_value_assignment() { + return GetRuleContext(0); + } + public Raw_value_style_enum_caseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_style_enum_case; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_style_enum_case(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_style_enum_case(this); + } + } + + [RuleVersion(0)] + public Raw_value_style_enum_caseContext raw_value_style_enum_case() { + Raw_value_style_enum_caseContext _localctx = new Raw_value_style_enum_caseContext(Context, State); + EnterRule(_localctx, 72, RULE_raw_value_style_enum_case); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 589; + enum_case_name(); + State = 591; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAssign) { + { + State = 590; + raw_value_assignment(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_assignmentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Raw_value_literalContext raw_value_literal() { + return GetRuleContext(0); + } + public Raw_value_assignmentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_assignment; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_assignment(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_assignment(this); + } + } + + [RuleVersion(0)] + public Raw_value_assignmentContext raw_value_assignment() { + Raw_value_assignmentContext _localctx = new Raw_value_assignmentContext(Context, State); + EnterRule(_localctx, 74, RULE_raw_value_assignment); + try { + EnterOuterAlt(_localctx, 1); + { + State = 593; + Match(OpAssign); + State = 594; + raw_value_literal(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Raw_value_literalContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Numeric_literalContext numeric_literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Static_string_literal() { return GetToken(SwiftInterfaceParser.Static_string_literal, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { + return GetRuleContext(0); + } + public Raw_value_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_raw_value_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRaw_value_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRaw_value_literal(this); + } + } + + [RuleVersion(0)] + public Raw_value_literalContext raw_value_literal() { + Raw_value_literalContext _localctx = new Raw_value_literalContext(Context, State); + EnterRule(_localctx, 76, RULE_raw_value_literal); + try { + State = 599; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case Binary_literal: + case Octal_literal: + case Decimal_literal: + case Pure_decimal_digits: + case Hexadecimal_literal: + case OpPlus: + case OpMinus: + EnterOuterAlt(_localctx, 1); + { + State = 596; + numeric_literal(); + } + break; + case Static_string_literal: + EnterOuterAlt(_localctx, 2); + { + State = 597; + Match(Static_string_literal); + } + break; + case T__61: + case T__62: + EnterOuterAlt(_localctx, 3); + { + State = 598; + boolean_literal(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Struct_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Struct_nameContext struct_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Struct_bodyContext struct_body() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + public Struct_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_struct_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterStruct_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitStruct_declaration(this); + } + } + + [RuleVersion(0)] + public Struct_declarationContext struct_declaration() { + Struct_declarationContext _localctx = new Struct_declarationContext(Context, State); + EnterRule(_localctx, 78, RULE_struct_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 602; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 601; + attributes(); + } + } + + State = 605; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 604; + access_level_modifier(); + } + } + + State = 607; + Match(T__2); + State = 608; + struct_name(); + State = 610; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 609; + generic_parameter_clause(); + } + } + + State = 613; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 612; + type_inheritance_clause(); + } + } + + State = 616; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 615; + generic_where_clause(); + } + } + + State = 618; + struct_body(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Struct_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Struct_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_struct_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterStruct_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitStruct_name(this); + } + } + + [RuleVersion(0)] + public Struct_nameContext struct_name() { + Struct_nameContext _localctx = new Struct_nameContext(Context, State); + EnterRule(_localctx, 80, RULE_struct_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 620; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Struct_bodyContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Struct_memberContext[] struct_member() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Struct_memberContext struct_member(int i) { + return GetRuleContext(i); + } + public Struct_bodyContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_struct_body; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterStruct_body(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitStruct_body(this); + } + } + + [RuleVersion(0)] + public Struct_bodyContext struct_body() { + Struct_bodyContext _localctx = new Struct_bodyContext(Context, State); + EnterRule(_localctx, 82, RULE_struct_body); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 622; + Match(OpLBrace); + State = 626; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + { + State = 623; + struct_member(); + } + } + State = 628; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 629; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Struct_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { + return GetRuleContext(0); + } + public Struct_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_struct_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterStruct_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitStruct_member(this); + } + } + + [RuleVersion(0)] + public Struct_memberContext struct_member() { + Struct_memberContext _localctx = new Struct_memberContext(Context, State); + EnterRule(_localctx, 84, RULE_struct_member); + try { + EnterOuterAlt(_localctx, 1); + { + State = 631; + nominal_declaration(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Class_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Class_nameContext class_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Class_bodyContext class_body() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Final_clauseContext final_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + public Class_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_class_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterClass_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitClass_declaration(this); + } + } + + [RuleVersion(0)] + public Class_declarationContext class_declaration() { + Class_declarationContext _localctx = new Class_declarationContext(Context, State); + EnterRule(_localctx, 86, RULE_class_declaration); + int _la; + try { + State = 675; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,69,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 634; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 633; + attributes(); + } + } + + State = 637; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 636; + access_level_modifier(); + } + } + + State = 640; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__13) { + { + State = 639; + final_clause(); + } + } + + State = 642; + Match(T__3); + State = 643; + class_name(); + State = 645; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 644; + generic_parameter_clause(); + } + } + + State = 648; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 647; + type_inheritance_clause(); + } + } + + State = 651; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 650; + generic_where_clause(); + } + } + + State = 653; + class_body(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 656; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 655; + attributes(); + } + } + + State = 658; + final_clause(); + State = 660; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 659; + access_level_modifier(); + } + } + + State = 662; + Match(T__3); + State = 663; + class_name(); + State = 665; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 664; + generic_parameter_clause(); + } + } + + State = 668; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 667; + type_inheritance_clause(); + } + } + + State = 671; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 670; + generic_where_clause(); + } + } + + State = 673; + class_body(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Class_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Class_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_class_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterClass_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitClass_name(this); + } + } + + [RuleVersion(0)] + public Class_nameContext class_name() { + Class_nameContext _localctx = new Class_nameContext(Context, State); + EnterRule(_localctx, 88, RULE_class_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 677; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Class_bodyContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Class_memberContext[] class_member() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Class_memberContext class_member(int i) { + return GetRuleContext(i); + } + public Class_bodyContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_class_body; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterClass_body(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitClass_body(this); + } + } + + [RuleVersion(0)] + public Class_bodyContext class_body() { + Class_bodyContext _localctx = new Class_bodyContext(Context, State); + EnterRule(_localctx, 90, RULE_class_body); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 679; + Match(OpLBrace); + State = 683; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + { + State = 680; + class_member(); + } + } + State = 685; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 686; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Class_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { + return GetRuleContext(0); + } + public Class_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_class_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterClass_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitClass_member(this); + } + } + + [RuleVersion(0)] + public Class_memberContext class_member() { + Class_memberContext _localctx = new Class_memberContext(Context, State); + EnterRule(_localctx, 92, RULE_class_member); + try { + EnterOuterAlt(_localctx, 1); + { + State = 688; + nominal_declaration(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Final_clauseContext : ParserRuleContext { + public Final_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_final_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFinal_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFinal_clause(this); + } + } + + [RuleVersion(0)] + public Final_clauseContext final_clause() { + Final_clauseContext _localctx = new Final_clauseContext(Context, State); + EnterRule(_localctx, 94, RULE_final_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 690; + Match(T__13); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Protocol_nameContext protocol_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_bodyContext protocol_body() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + public Protocol_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_declaration(this); + } + } + + [RuleVersion(0)] + public Protocol_declarationContext protocol_declaration() { + Protocol_declarationContext _localctx = new Protocol_declarationContext(Context, State); + EnterRule(_localctx, 96, RULE_protocol_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 693; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 692; + attributes(); + } + } + + State = 696; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 695; + access_level_modifier(); + } + } + + State = 698; + Match(T__5); + State = 699; + protocol_name(); + State = 701; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 700; + type_inheritance_clause(); + } + } + + State = 703; + protocol_body(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Protocol_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_name(this); + } + } + + [RuleVersion(0)] + public Protocol_nameContext protocol_name() { + Protocol_nameContext _localctx = new Protocol_nameContext(Context, State); + EnterRule(_localctx, 98, RULE_protocol_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 705; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_bodyContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_memberContext[] protocol_member() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_memberContext protocol_member(int i) { + return GetRuleContext(i); + } + public Protocol_bodyContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_body; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_body(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_body(this); + } + } + + [RuleVersion(0)] + public Protocol_bodyContext protocol_body() { + Protocol_bodyContext _localctx = new Protocol_bodyContext(Context, State); + EnterRule(_localctx, 100, RULE_protocol_body); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 707; + Match(OpLBrace); + State = 711; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__3) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__27) | (1L << T__28) | (1L << T__32) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + { + State = 708; + protocol_member(); + } + } + State = 713; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 714; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Protocol_member_declarationContext protocol_member_declaration() { + return GetRuleContext(0); + } + public Protocol_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_member(this); + } + } + + [RuleVersion(0)] + public Protocol_memberContext protocol_member() { + Protocol_memberContext _localctx = new Protocol_memberContext(Context, State); + EnterRule(_localctx, 102, RULE_protocol_member); + try { + EnterOuterAlt(_localctx, 1); + { + State = 716; + protocol_member_declaration(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_member_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Initializer_declarationContext initializer_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_associated_type_declarationContext protocol_associated_type_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { + return GetRuleContext(0); + } + public Protocol_member_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_member_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_member_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_member_declaration(this); + } + } + + [RuleVersion(0)] + public Protocol_member_declarationContext protocol_member_declaration() { + Protocol_member_declarationContext _localctx = new Protocol_member_declarationContext(Context, State); + EnterRule(_localctx, 104, RULE_protocol_member_declaration); + try { + State = 724; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,75,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 718; + variable_declaration(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 719; + function_declaration(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 720; + initializer_declaration(); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 721; + subscript_declaration(); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 722; + protocol_associated_type_declaration(); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 723; + typealias_declaration(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Operator_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Prefix_operator_declarationContext prefix_operator_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Postfix_operator_declarationContext postfix_operator_declaration() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Infix_operator_declarationContext infix_operator_declaration() { + return GetRuleContext(0); + } + public Operator_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_operator_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOperator_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOperator_declaration(this); + } + } + + [RuleVersion(0)] + public Operator_declarationContext operator_declaration() { + Operator_declarationContext _localctx = new Operator_declarationContext(Context, State); + EnterRule(_localctx, 106, RULE_operator_declaration); + try { + State = 729; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__14: + EnterOuterAlt(_localctx, 1); + { + State = 726; + prefix_operator_declaration(); + } + break; + case T__16: + EnterOuterAlt(_localctx, 2); + { + State = 727; + postfix_operator_declaration(); + } + break; + case T__17: + EnterOuterAlt(_localctx, 3); + { + State = 728; + infix_operator_declaration(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Prefix_operator_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + public Prefix_operator_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_prefix_operator_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrefix_operator_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrefix_operator_declaration(this); + } + } + + [RuleVersion(0)] + public Prefix_operator_declarationContext prefix_operator_declaration() { + Prefix_operator_declarationContext _localctx = new Prefix_operator_declarationContext(Context, State); + EnterRule(_localctx, 108, RULE_prefix_operator_declaration); + try { + EnterOuterAlt(_localctx, 1); + { + State = 731; + Match(T__14); + State = 732; + Match(T__15); + State = 733; + @operator(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Postfix_operator_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + public Postfix_operator_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_postfix_operator_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPostfix_operator_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPostfix_operator_declaration(this); + } + } + + [RuleVersion(0)] + public Postfix_operator_declarationContext postfix_operator_declaration() { + Postfix_operator_declarationContext _localctx = new Postfix_operator_declarationContext(Context, State); + EnterRule(_localctx, 110, RULE_postfix_operator_declaration); + try { + EnterOuterAlt(_localctx, 1); + { + State = 735; + Match(T__16); + State = 736; + Match(T__15); + State = 737; + @operator(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Infix_operator_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Infix_operator_groupContext infix_operator_group() { + return GetRuleContext(0); + } + public Infix_operator_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_infix_operator_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInfix_operator_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInfix_operator_declaration(this); + } + } + + [RuleVersion(0)] + public Infix_operator_declarationContext infix_operator_declaration() { + Infix_operator_declarationContext _localctx = new Infix_operator_declarationContext(Context, State); + EnterRule(_localctx, 112, RULE_infix_operator_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 739; + Match(T__17); + State = 740; + Match(T__15); + State = 741; + @operator(); + State = 743; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 742; + infix_operator_group(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Infix_operator_groupContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name() { + return GetRuleContext(0); + } + public Infix_operator_groupContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_infix_operator_group; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInfix_operator_group(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInfix_operator_group(this); + } + } + + [RuleVersion(0)] + public Infix_operator_groupContext infix_operator_group() { + Infix_operator_groupContext _localctx = new Infix_operator_groupContext(Context, State); + EnterRule(_localctx, 114, RULE_infix_operator_group); + try { + EnterOuterAlt(_localctx, 1); + { + State = 745; + Match(OpColon); + State = 746; + precedence_group_name(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_attributeContext[] precedence_group_attribute() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_attributeContext precedence_group_attribute(int i) { + return GetRuleContext(i); + } + public Precedence_group_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_declaration(this); + } + } + + [RuleVersion(0)] + public Precedence_group_declarationContext precedence_group_declaration() { + Precedence_group_declarationContext _localctx = new Precedence_group_declarationContext(Context, State); + EnterRule(_localctx, 116, RULE_precedence_group_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 748; + Match(T__18); + State = 749; + precedence_group_name(); + State = 750; + Match(OpLBrace); + State = 754; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22))) != 0)) { + { + { + State = 751; + precedence_group_attribute(); + } + } + State = 756; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 757; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_attributeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_relationContext precedence_group_relation() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_assignmentContext precedence_group_assignment() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_associativityContext precedence_group_associativity() { + return GetRuleContext(0); + } + public Precedence_group_attributeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_attribute; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_attribute(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_attribute(this); + } + } + + [RuleVersion(0)] + public Precedence_group_attributeContext precedence_group_attribute() { + Precedence_group_attributeContext _localctx = new Precedence_group_attributeContext(Context, State); + EnterRule(_localctx, 118, RULE_precedence_group_attribute); + try { + State = 762; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__19: + case T__20: + EnterOuterAlt(_localctx, 1); + { + State = 759; + precedence_group_relation(); + } + break; + case T__21: + EnterOuterAlt(_localctx, 2); + { + State = 760; + precedence_group_assignment(); + } + break; + case T__22: + EnterOuterAlt(_localctx, 3); + { + State = 761; + precedence_group_associativity(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_relationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_namesContext precedence_group_names() { + return GetRuleContext(0); + } + public Precedence_group_relationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_relation; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_relation(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_relation(this); + } + } + + [RuleVersion(0)] + public Precedence_group_relationContext precedence_group_relation() { + Precedence_group_relationContext _localctx = new Precedence_group_relationContext(Context, State); + EnterRule(_localctx, 120, RULE_precedence_group_relation); + try { + State = 770; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__19: + EnterOuterAlt(_localctx, 1); + { + State = 764; + Match(T__19); + State = 765; + Match(OpColon); + State = 766; + precedence_group_names(); + } + break; + case T__20: + EnterOuterAlt(_localctx, 2); + { + State = 767; + Match(T__20); + State = 768; + Match(OpColon); + State = 769; + precedence_group_names(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_assignmentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { + return GetRuleContext(0); + } + public Precedence_group_assignmentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_assignment; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_assignment(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_assignment(this); + } + } + + [RuleVersion(0)] + public Precedence_group_assignmentContext precedence_group_assignment() { + Precedence_group_assignmentContext _localctx = new Precedence_group_assignmentContext(Context, State); + EnterRule(_localctx, 122, RULE_precedence_group_assignment); + try { + EnterOuterAlt(_localctx, 1); + { + State = 772; + Match(T__21); + State = 773; + Match(OpColon); + State = 774; + boolean_literal(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_associativityContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public AssociativityContext associativity() { + return GetRuleContext(0); + } + public Precedence_group_associativityContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_associativity; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_associativity(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_associativity(this); + } + } + + [RuleVersion(0)] + public Precedence_group_associativityContext precedence_group_associativity() { + Precedence_group_associativityContext _localctx = new Precedence_group_associativityContext(Context, State); + EnterRule(_localctx, 124, RULE_precedence_group_associativity); + try { + EnterOuterAlt(_localctx, 1); + { + State = 776; + Match(T__22); + State = 777; + Match(OpColon); + State = 778; + associativity(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class AssociativityContext : ParserRuleContext { + public AssociativityContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_associativity; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAssociativity(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAssociativity(this); + } + } + + [RuleVersion(0)] + public AssociativityContext associativity() { + AssociativityContext _localctx = new AssociativityContext(Context, State); + EnterRule(_localctx, 126, RULE_associativity); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 780; + _la = TokenStream.LA(1); + if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__23) | (1L << T__24) | (1L << T__25))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_namesContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext[] precedence_group_name() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Precedence_group_namesContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_names; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_names(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_names(this); + } + } + + [RuleVersion(0)] + public Precedence_group_namesContext precedence_group_names() { + Precedence_group_namesContext _localctx = new Precedence_group_namesContext(Context, State); + EnterRule(_localctx, 128, RULE_precedence_group_names); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 782; + precedence_group_name(); + State = 787; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 783; + Match(OpComma); + State = 784; + precedence_group_name(); + } + } + State = 789; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Precedence_group_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Precedence_group_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_precedence_group_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPrecedence_group_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPrecedence_group_name(this); + } + } + + [RuleVersion(0)] + public Precedence_group_nameContext precedence_group_name() { + Precedence_group_nameContext _localctx = new Precedence_group_nameContext(Context, State); + EnterRule(_localctx, 130, RULE_precedence_group_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 790; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Extension_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Extension_bodyContext extension_body() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + public Extension_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_extension_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterExtension_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitExtension_declaration(this); + } + } + + [RuleVersion(0)] + public Extension_declarationContext extension_declaration() { + Extension_declarationContext _localctx = new Extension_declarationContext(Context, State); + EnterRule(_localctx, 132, RULE_extension_declaration); + int _la; + try { + State = 816; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,87,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 793; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 792; + attributes(); + } + } + + State = 796; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 795; + access_level_modifier(); + } + } + + State = 798; + Match(T__26); + State = 799; + type_identifier(); + State = 801; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 800; + type_inheritance_clause(); + } + } + + State = 803; + extension_body(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 806; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 805; + attributes(); + } + } + + State = 809; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 808; + access_level_modifier(); + } + } + + State = 811; + Match(T__26); + State = 812; + type_identifier(); + State = 813; + generic_where_clause(); + State = 814; + extension_body(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Extension_bodyContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Extension_memberContext[] extension_member() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Extension_memberContext extension_member(int i) { + return GetRuleContext(i); + } + public Extension_bodyContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_extension_body; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterExtension_body(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitExtension_body(this); + } + } + + [RuleVersion(0)] + public Extension_bodyContext extension_body() { + Extension_bodyContext _localctx = new Extension_bodyContext(Context, State); + EnterRule(_localctx, 134, RULE_extension_body); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 818; + Match(OpLBrace); + State = 822; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { + { + { + State = 819; + extension_member(); + } + } + State = 824; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 825; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Extension_memberContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public DeclarationContext declaration() { + return GetRuleContext(0); + } + public Extension_memberContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_extension_member; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterExtension_member(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitExtension_member(this); + } + } + + [RuleVersion(0)] + public Extension_memberContext extension_member() { + Extension_memberContext _localctx = new Extension_memberContext(Context, State); + EnterRule(_localctx, 136, RULE_extension_member); + try { + EnterOuterAlt(_localctx, 1); + { + State = 827; + declaration(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Subscript_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Subscript_headContext subscript_head() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Subscript_resultContext subscript_result() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Getter_setter_keyword_blockContext getter_setter_keyword_block() { + return GetRuleContext(0); + } + public Subscript_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_subscript_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSubscript_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSubscript_declaration(this); + } + } + + [RuleVersion(0)] + public Subscript_declarationContext subscript_declaration() { + Subscript_declarationContext _localctx = new Subscript_declarationContext(Context, State); + EnterRule(_localctx, 138, RULE_subscript_declaration); + try { + State = 836; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,89,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 829; + subscript_head(); + State = 830; + subscript_result(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 832; + subscript_head(); + State = 833; + subscript_result(); + State = 834; + getter_setter_keyword_block(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Subscript_headContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { + return GetRuleContext(0); + } + public Subscript_headContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_subscript_head; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSubscript_head(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSubscript_head(this); + } + } + + [RuleVersion(0)] + public Subscript_headContext subscript_head() { + Subscript_headContext _localctx = new Subscript_headContext(Context, State); + EnterRule(_localctx, 140, RULE_subscript_head); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 839; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 838; + attributes(); + } + } + + State = 842; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 841; + declaration_modifiers(); + } + } + + State = 844; + Match(T__27); + State = 845; + parameter_clause(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Subscript_resultContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + public Subscript_resultContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_subscript_result; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSubscript_result(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSubscript_result(this); + } + } + + [RuleVersion(0)] + public Subscript_resultContext subscript_result() { + Subscript_resultContext _localctx = new Subscript_resultContext(Context, State); + EnterRule(_localctx, 142, RULE_subscript_result); + try { + EnterOuterAlt(_localctx, 1); + { + State = 847; + arrow_operator(); + State = 849; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,92,Context) ) { + case 1: + { + State = 848; + attributes(); + } + break; + } + State = 851; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_associated_type_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Typealias_nameContext typealias_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Typealias_assignmentContext typealias_assignment() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + public Protocol_associated_type_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_associated_type_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_associated_type_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_associated_type_declaration(this); + } + } + + [RuleVersion(0)] + public Protocol_associated_type_declarationContext protocol_associated_type_declaration() { + Protocol_associated_type_declarationContext _localctx = new Protocol_associated_type_declarationContext(Context, State); + EnterRule(_localctx, 144, RULE_protocol_associated_type_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 854; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 853; + attributes(); + } + } + + State = 857; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { + { + State = 856; + access_level_modifier(); + } + } + + State = 859; + Match(T__28); + State = 860; + typealias_name(); + State = 862; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpColon) { + { + State = 861; + type_inheritance_clause(); + } + } + + State = 865; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAssign) { + { + State = 864; + typealias_assignment(); + } + } + + State = 868; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 867; + generic_where_clause(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Function_headContext function_head() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_nameContext function_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_signatureContext function_signature() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_bodyContext function_body() { + return GetRuleContext(0); + } + public Function_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_declaration(this); + } + } + + [RuleVersion(0)] + public Function_declarationContext function_declaration() { + Function_declarationContext _localctx = new Function_declarationContext(Context, State); + EnterRule(_localctx, 146, RULE_function_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 870; + function_head(); + State = 871; + function_name(); + State = 873; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 872; + generic_parameter_clause(); + } + } + + State = 875; + function_signature(); + State = 877; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 876; + generic_where_clause(); + } + } + + State = 880; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLBrace) { + { + State = 879; + function_body(); + } + } + + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_headContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { + return GetRuleContext(0); + } + public Function_headContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_head; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_head(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_head(this); + } + } + + [RuleVersion(0)] + public Function_headContext function_head() { + Function_headContext _localctx = new Function_headContext(Context, State); + EnterRule(_localctx, 148, RULE_function_head); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 883; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 882; + attributes(); + } + } + + State = 886; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 885; + declaration_modifiers(); + } + } + + State = 888; + Match(T__7); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Operator_nameContext operator_name() { + return GetRuleContext(0); + } + public Function_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_name(this); + } + } + + [RuleVersion(0)] + public Function_nameContext function_name() { + Function_nameContext _localctx = new Function_nameContext(Context, State); + EnterRule(_localctx, 150, RULE_function_name); + try { + State = 892; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__9: + case T__10: + case T__11: + case T__13: + case T__14: + case T__16: + case T__17: + case T__19: + case T__20: + case T__21: + case T__22: + case T__23: + case T__24: + case T__25: + case T__34: + case T__35: + case T__36: + case T__37: + case T__38: + case T__39: + case T__41: + case T__42: + case T__43: + case T__44: + case T__49: + case T__50: + case T__51: + case T__54: + case T__55: + case T__67: + case T__68: + case T__69: + case T__70: + case T__71: + case T__72: + case T__73: + case T__74: + case T__75: + case T__76: + case T__77: + case T__78: + case T__79: + case T__80: + case T__81: + case T__82: + case T__83: + case T__84: + case T__85: + case T__86: + case T__87: + case T__88: + case T__89: + case T__90: + case T__91: + case Identifier: + EnterOuterAlt(_localctx, 1); + { + State = 890; + declaration_identifier(); + } + break; + case T__64: + case Operator: + EnterOuterAlt(_localctx, 2); + { + State = 891; + operator_name(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_bodyContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext[] dyckSubExpression() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext dyckSubExpression(int i) { + return GetRuleContext(i); + } + public Function_bodyContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_body; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_body(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_body(this); + } + } + + [RuleVersion(0)] + public Function_bodyContext function_body() { + Function_bodyContext _localctx = new Function_bodyContext(Context, State); + EnterRule(_localctx, 152, RULE_function_body); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 894; + Match(OpLBrace); + State = 898; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { + { + { + State = 895; + dyckSubExpression(); + } + } + State = 900; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 901; + Match(OpRBrace); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Operator_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + public Operator_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_operator_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOperator_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOperator_name(this); + } + } + + [RuleVersion(0)] + public Operator_nameContext operator_name() { + Operator_nameContext _localctx = new Operator_nameContext(Context, State); + EnterRule(_localctx, 154, RULE_operator_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 903; + @operator(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_signatureContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Async_clauseContext async_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Throws_clauseContext throws_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Function_resultContext function_result() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Rethrows_clauseContext rethrows_clause() { + return GetRuleContext(0); + } + public Function_signatureContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_signature; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_signature(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_signature(this); + } + } + + [RuleVersion(0)] + public Function_signatureContext function_signature() { + Function_signatureContext _localctx = new Function_signatureContext(Context, State); + EnterRule(_localctx, 156, RULE_function_signature); + int _la; + try { + State = 923; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,110,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 905; + parameter_clause(); + State = 907; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__29) { + { + State = 906; + async_clause(); + } + } + + State = 910; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__30) { + { + State = 909; + throws_clause(); + } + } + + State = 913; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__65) { + { + State = 912; + function_result(); + } + } + + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 915; + parameter_clause(); + State = 917; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__29) { + { + State = 916; + async_clause(); + } + } + + State = 919; + rethrows_clause(); + State = 921; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__65) { + { + State = 920; + function_result(); + } + } + + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Async_clauseContext : ParserRuleContext { + public Async_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_async_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAsync_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAsync_clause(this); + } + } + + [RuleVersion(0)] + public Async_clauseContext async_clause() { + Async_clauseContext _localctx = new Async_clauseContext(Context, State); + EnterRule(_localctx, 158, RULE_async_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 925; + Match(T__29); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Throws_clauseContext : ParserRuleContext { + public Throws_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_throws_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterThrows_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitThrows_clause(this); + } + } + + [RuleVersion(0)] + public Throws_clauseContext throws_clause() { + Throws_clauseContext _localctx = new Throws_clauseContext(Context, State); + EnterRule(_localctx, 160, RULE_throws_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 927; + Match(T__30); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Rethrows_clauseContext : ParserRuleContext { + public Rethrows_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_rethrows_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRethrows_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRethrows_clause(this); + } + } + + [RuleVersion(0)] + public Rethrows_clauseContext rethrows_clause() { + Rethrows_clauseContext _localctx = new Rethrows_clauseContext(Context, State); + EnterRule(_localctx, 162, RULE_rethrows_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 929; + Match(T__31); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_resultContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + public Function_resultContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_result; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_result(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_result(this); + } + } + + [RuleVersion(0)] + public Function_resultContext function_result() { + Function_resultContext _localctx = new Function_resultContext(Context, State); + EnterRule(_localctx, 164, RULE_function_result); + try { + EnterOuterAlt(_localctx, 1); + { + State = 931; + arrow_operator(); + State = 933; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,111,Context) ) { + case 1: + { + State = 932; + attributes(); + } + break; + } + State = 935; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Initializer_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Initializer_headContext initializer_head() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Throws_clauseContext throws_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Rethrows_clauseContext rethrows_clause() { + return GetRuleContext(0); + } + public Initializer_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_initializer_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInitializer_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInitializer_declaration(this); + } + } + + [RuleVersion(0)] + public Initializer_declarationContext initializer_declaration() { + Initializer_declarationContext _localctx = new Initializer_declarationContext(Context, State); + EnterRule(_localctx, 166, RULE_initializer_declaration); + int _la; + try { + State = 957; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,117,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 937; + initializer_head(); + State = 939; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 938; + generic_parameter_clause(); + } + } + + State = 941; + parameter_clause(); + State = 943; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__30) { + { + State = 942; + throws_clause(); + } + } + + State = 946; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 945; + generic_where_clause(); + } + } + + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 948; + initializer_head(); + State = 950; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpLess) { + { + State = 949; + generic_parameter_clause(); + } + } + + State = 952; + parameter_clause(); + State = 953; + rethrows_clause(); + State = 955; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__63) { + { + State = 954; + generic_where_clause(); + } + } + + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Initializer_headContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } + public Initializer_headContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_initializer_head; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInitializer_head(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInitializer_head(this); + } + } + + [RuleVersion(0)] + public Initializer_headContext initializer_head() { + Initializer_headContext _localctx = new Initializer_headContext(Context, State); + EnterRule(_localctx, 168, RULE_initializer_head); + int _la; + try { + State = 982; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,124,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 960; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 959; + attributes(); + } + } + + State = 963; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 962; + declaration_modifiers(); + } + } + + State = 965; + Match(T__32); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 967; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 966; + attributes(); + } + } + + State = 970; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 969; + declaration_modifiers(); + } + } + + State = 972; + Match(T__32); + State = 973; + Match(OpQuestion); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 975; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 974; + attributes(); + } + } + + State = 978; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 977; + declaration_modifiers(); + } + } + + State = 980; + Match(T__32); + State = 981; + Match(OpBang); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Deinitializer_declarationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { + return GetRuleContext(0); + } + public Deinitializer_declarationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_deinitializer_declaration; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDeinitializer_declaration(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDeinitializer_declaration(this); + } + } + + [RuleVersion(0)] + public Deinitializer_declarationContext deinitializer_declaration() { + Deinitializer_declarationContext _localctx = new Deinitializer_declarationContext(Context, State); + EnterRule(_localctx, 170, RULE_deinitializer_declaration); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 985; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 984; + attributes(); + } + } + + State = 988; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { + { + State = 987; + declaration_modifiers(); + } + } + + State = 990; + Match(T__33); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Parameter_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Parameter_listContext parameter_list() { + return GetRuleContext(0); + } + public Parameter_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_parameter_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterParameter_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitParameter_clause(this); + } + } + + [RuleVersion(0)] + public Parameter_clauseContext parameter_clause() { + Parameter_clauseContext _localctx = new Parameter_clauseContext(Context, State); + EnterRule(_localctx, 172, RULE_parameter_clause); + try { + State = 998; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,127,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 992; + Match(OpLParen); + State = 993; + Match(OpRParen); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 994; + Match(OpLParen); + State = 995; + parameter_list(); + State = 996; + Match(OpRParen); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Parameter_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ParameterContext[] parameter() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public ParameterContext parameter(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Parameter_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_parameter_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterParameter_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitParameter_list(this); + } + } + + [RuleVersion(0)] + public Parameter_listContext parameter_list() { + Parameter_listContext _localctx = new Parameter_listContext(Context, State); + EnterRule(_localctx, 174, RULE_parameter_list); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1000; + parameter(); + State = 1005; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 1001; + Match(OpComma); + State = 1002; + parameter(); + } + } + State = 1007; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class ParameterContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Local_parameter_nameContext local_parameter_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public External_parameter_nameContext external_parameter_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public DefaultInitializerContext defaultInitializer() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Range_operatorContext range_operator() { + return GetRuleContext(0); + } + public ParameterContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_parameter; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterParameter(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitParameter(this); + } + } + + [RuleVersion(0)] + public ParameterContext parameter() { + ParameterContext _localctx = new ParameterContext(Context, State); + EnterRule(_localctx, 176, RULE_parameter); + int _la; + try { + State = 1023; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,132,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1009; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,129,Context) ) { + case 1: + { + State = 1008; + external_parameter_name(); + } + break; + } + State = 1011; + local_parameter_name(); + State = 1012; + type_annotation(); + State = 1014; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAssign) { + { + State = 1013; + defaultInitializer(); + } + } + + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1017; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,131,Context) ) { + case 1: + { + State = 1016; + external_parameter_name(); + } + break; + } + State = 1019; + local_parameter_name(); + State = 1020; + type_annotation(); + State = 1021; + range_operator(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class External_parameter_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { + return GetRuleContext(0); + } + public External_parameter_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_external_parameter_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterExternal_parameter_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitExternal_parameter_name(this); + } + } + + [RuleVersion(0)] + public External_parameter_nameContext external_parameter_name() { + External_parameter_nameContext _localctx = new External_parameter_nameContext(Context, State); + EnterRule(_localctx, 178, RULE_external_parameter_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1025; + label_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Local_parameter_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { + return GetRuleContext(0); + } + public Local_parameter_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_local_parameter_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterLocal_parameter_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitLocal_parameter_name(this); + } + } + + [RuleVersion(0)] + public Local_parameter_nameContext local_parameter_name() { + Local_parameter_nameContext _localctx = new Local_parameter_nameContext(Context, State); + EnterRule(_localctx, 180, RULE_local_parameter_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1027; + label_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class DefaultInitializerContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } + [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext[] dyckExpression() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext dyckExpression(int i) { + return GetRuleContext(i); + } + public DefaultInitializerContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_defaultInitializer; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDefaultInitializer(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDefaultInitializer(this); + } + } + + [RuleVersion(0)] + public DefaultInitializerContext defaultInitializer() { + DefaultInitializerContext _localctx = new DefaultInitializerContext(Context, State); + EnterRule(_localctx, 182, RULE_defaultInitializer); + try { + int _alt; + EnterOuterAlt(_localctx, 1); + { + State = 1029; + Match(OpAssign); + State = 1031; + ErrorHandler.Sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + State = 1030; + dyckExpression(); + } + } + break; + default: + throw new NoViableAltException(this); + } + State = 1033; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,133,Context); + } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class DyckExpressionContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext[] dyckSubExpression() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext dyckSubExpression(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public LiteralContext literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public DotSymbolContext dotSymbol() { + return GetRuleContext(0); + } + public DyckExpressionContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_dyckExpression; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDyckExpression(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDyckExpression(this); + } + } + + [RuleVersion(0)] + public DyckExpressionContext dyckExpression() { + DyckExpressionContext _localctx = new DyckExpressionContext(Context, State); + EnterRule(_localctx, 184, RULE_dyckExpression); + int _la; + try { + State = 1063; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,137,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1035; + Match(OpLParen); + State = 1039; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { + { + { + State = 1036; + dyckSubExpression(); + } + } + State = 1041; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 1042; + Match(OpRParen); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1043; + Match(OpLBracket); + State = 1047; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { + { + { + State = 1044; + dyckSubExpression(); + } + } + State = 1049; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 1050; + Match(OpRBracket); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1051; + Match(OpLBrace); + State = 1055; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { + { + { + State = 1052; + dyckSubExpression(); + } + } + State = 1057; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + State = 1058; + Match(OpRBrace); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 1059; + label_identifier(); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 1060; + literal(); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 1061; + @operator(); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 1062; + dotSymbol(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class DyckSubExpressionContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext dyckExpression() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Any_other_things_for_dyck_expressionContext any_other_things_for_dyck_expression() { + return GetRuleContext(0); + } + public DyckSubExpressionContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_dyckSubExpression; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDyckSubExpression(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDyckSubExpression(this); + } + } + + [RuleVersion(0)] + public DyckSubExpressionContext dyckSubExpression() { + DyckSubExpressionContext _localctx = new DyckSubExpressionContext(Context, State); + EnterRule(_localctx, 186, RULE_dyckSubExpression); + try { + State = 1067; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,138,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1065; + dyckExpression(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1066; + any_other_things_for_dyck_expression(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Any_other_things_for_dyck_expressionContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpSemi() { return GetToken(SwiftInterfaceParser.OpSemi, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPound() { return GetToken(SwiftInterfaceParser.OpPound, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBackTick() { return GetToken(SwiftInterfaceParser.OpBackTick, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpUnder() { return GetToken(SwiftInterfaceParser.OpUnder, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPlus() { return GetToken(SwiftInterfaceParser.OpPlus, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpMinus() { return GetToken(SwiftInterfaceParser.OpMinus, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAmp() { return GetToken(SwiftInterfaceParser.OpAmp, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpTilde() { return GetToken(SwiftInterfaceParser.OpTilde, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpGreater() { return GetToken(SwiftInterfaceParser.OpGreater, 0); } + [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { + return GetRuleContext(0); + } + public Any_other_things_for_dyck_expressionContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_any_other_things_for_dyck_expression; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAny_other_things_for_dyck_expression(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAny_other_things_for_dyck_expression(this); + } + } + + [RuleVersion(0)] + public Any_other_things_for_dyck_expressionContext any_other_things_for_dyck_expression() { + Any_other_things_for_dyck_expressionContext _localctx = new Any_other_things_for_dyck_expressionContext(Context, State); + EnterRule(_localctx, 188, RULE_any_other_things_for_dyck_expression); + try { + State = 1089; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__64: + case OpPlus: + case OpMinus: + case OpAssign: + case OpAmp: + case OpQuestion: + case OpBang: + case OpDot: + case OpComma: + case OpTilde: + case OpColon: + case OpSemi: + case OpAt: + case OpPound: + case OpBackTick: + case OpUnder: + case OpGreater: + EnterOuterAlt(_localctx, 1); + { + State = 1086; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case OpDot: + { + State = 1069; + Match(OpDot); + } + break; + case OpComma: + { + State = 1070; + Match(OpComma); + } + break; + case OpColon: + { + State = 1071; + Match(OpColon); + } + break; + case OpSemi: + { + State = 1072; + Match(OpSemi); + } + break; + case OpAssign: + { + State = 1073; + Match(OpAssign); + } + break; + case OpAt: + { + State = 1074; + Match(OpAt); + } + break; + case OpPound: + { + State = 1075; + Match(OpPound); + } + break; + case OpBackTick: + { + State = 1076; + Match(OpBackTick); + } + break; + case OpQuestion: + { + State = 1077; + Match(OpQuestion); + } + break; + case OpUnder: + { + State = 1078; + Match(OpUnder); + } + break; + case OpPlus: + { + State = 1079; + Match(OpPlus); + } + break; + case OpMinus: + { + State = 1080; + Match(OpMinus); + } + break; + case OpAmp: + { + State = 1081; + Match(OpAmp); + } + break; + case OpBang: + { + State = 1082; + Match(OpBang); + } + break; + case OpTilde: + { + State = 1083; + Match(OpTilde); + } + break; + case OpGreater: + { + State = 1084; + Match(OpGreater); + } + break; + case T__64: + { + State = 1085; + opGreater(); + } + break; + default: + throw new NoViableAltException(this); + } + } + break; + case T__65: + EnterOuterAlt(_localctx, 2); + { + State = 1088; + arrow_operator(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class DotSymbolContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public DotSymbolContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_dotSymbol; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDotSymbol(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDotSymbol(this); + } + } + + [RuleVersion(0)] + public DotSymbolContext dotSymbol() { + DotSymbolContext _localctx = new DotSymbolContext(Context, State); + EnterRule(_localctx, 190, RULE_dotSymbol); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1091; + Match(OpDot); + State = 1092; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Declaration_identifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Identifier() { return GetToken(SwiftInterfaceParser.Identifier, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Keyword_as_identifier_in_declarationsContext keyword_as_identifier_in_declarations() { + return GetRuleContext(0); + } + public Declaration_identifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_declaration_identifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDeclaration_identifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDeclaration_identifier(this); + } + } + + [RuleVersion(0)] + public Declaration_identifierContext declaration_identifier() { + Declaration_identifierContext _localctx = new Declaration_identifierContext(Context, State); + EnterRule(_localctx, 192, RULE_declaration_identifier); + try { + State = 1096; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case Identifier: + EnterOuterAlt(_localctx, 1); + { + State = 1094; + Match(Identifier); + } + break; + case T__9: + case T__10: + case T__11: + case T__13: + case T__14: + case T__16: + case T__17: + case T__19: + case T__20: + case T__21: + case T__22: + case T__23: + case T__24: + case T__25: + case T__34: + case T__35: + case T__36: + case T__37: + case T__38: + case T__39: + case T__41: + case T__42: + case T__43: + case T__44: + case T__49: + case T__50: + case T__51: + case T__54: + case T__55: + case T__67: + case T__68: + case T__69: + case T__70: + case T__71: + case T__72: + case T__73: + case T__74: + case T__75: + case T__76: + case T__77: + case T__78: + case T__79: + case T__80: + case T__81: + case T__82: + case T__83: + case T__84: + case T__85: + case T__86: + case T__87: + case T__88: + case T__89: + case T__90: + case T__91: + EnterOuterAlt(_localctx, 2); + { + State = 1095; + keyword_as_identifier_in_declarations(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Type_inheritance_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Class_requirementContext class_requirement() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_listContext type_inheritance_list() { + return GetRuleContext(0); + } + public Type_inheritance_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type_inheritance_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterType_inheritance_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitType_inheritance_clause(this); + } + } + + [RuleVersion(0)] + public Type_inheritance_clauseContext type_inheritance_clause() { + Type_inheritance_clauseContext _localctx = new Type_inheritance_clauseContext(Context, State); + EnterRule(_localctx, 194, RULE_type_inheritance_clause); + try { + State = 1107; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,142,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1098; + Match(OpColon); + State = 1099; + class_requirement(); + State = 1100; + Match(OpComma); + State = 1101; + type_inheritance_list(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1103; + Match(OpColon); + State = 1104; + class_requirement(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1105; + Match(OpColon); + State = 1106; + type_inheritance_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Type_inheritance_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_listContext type_inheritance_list() { + return GetRuleContext(0); + } + public Type_inheritance_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type_inheritance_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterType_inheritance_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitType_inheritance_list(this); + } + } + + [RuleVersion(0)] + public Type_inheritance_listContext type_inheritance_list() { + Type_inheritance_listContext _localctx = new Type_inheritance_listContext(Context, State); + EnterRule(_localctx, 196, RULE_type_inheritance_list); + try { + State = 1114; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,143,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1109; + type_identifier(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1110; + type_identifier(); + State = 1111; + Match(OpComma); + State = 1112; + type_inheritance_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Class_requirementContext : ParserRuleContext { + public Class_requirementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_class_requirement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterClass_requirement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitClass_requirement(this); + } + } + + [RuleVersion(0)] + public Class_requirementContext class_requirement() { + Class_requirementContext _localctx = new Class_requirementContext(Context, State); + EnterRule(_localctx, 198, RULE_class_requirement); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1116; + Match(T__3); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class AttributeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Attribute_nameContext attribute_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Attribute_argument_clauseContext attribute_argument_clause() { + return GetRuleContext(0); + } + public AttributeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_attribute; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAttribute(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAttribute(this); + } + } + + [RuleVersion(0)] + public AttributeContext attribute() { + AttributeContext _localctx = new AttributeContext(Context, State); + EnterRule(_localctx, 200, RULE_attribute); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1118; + Match(OpAt); + State = 1119; + attribute_name(); + State = 1121; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,144,Context) ) { + case 1: + { + State = 1120; + attribute_argument_clause(); + } + break; + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Attribute_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + public Attribute_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_attribute_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAttribute_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAttribute_name(this); + } + } + + [RuleVersion(0)] + public Attribute_nameContext attribute_name() { + Attribute_nameContext _localctx = new Attribute_nameContext(Context, State); + EnterRule(_localctx, 202, RULE_attribute_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1123; + type_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Attribute_argument_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokensContext balanced_tokens() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + public Attribute_argument_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_attribute_argument_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAttribute_argument_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAttribute_argument_clause(this); + } + } + + [RuleVersion(0)] + public Attribute_argument_clauseContext attribute_argument_clause() { + Attribute_argument_clauseContext _localctx = new Attribute_argument_clauseContext(Context, State); + EnterRule(_localctx, 204, RULE_attribute_argument_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1125; + Match(OpLParen); + State = 1126; + balanced_tokens(); + State = 1127; + Match(OpRParen); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class AttributesContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public AttributeContext[] attribute() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributeContext attribute(int i) { + return GetRuleContext(i); + } + public AttributesContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_attributes; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAttributes(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAttributes(this); + } + } + + [RuleVersion(0)] + public AttributesContext attributes() { + AttributesContext _localctx = new AttributesContext(Context, State); + EnterRule(_localctx, 206, RULE_attributes); + try { + int _alt; + EnterOuterAlt(_localctx, 1); + { + State = 1130; + ErrorHandler.Sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + State = 1129; + attribute(); + } + } + break; + default: + throw new NoViableAltException(this); + } + State = 1132; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,145,Context); + } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Balanced_tokensContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokenContext[] balanced_token() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokenContext balanced_token(int i) { + return GetRuleContext(i); + } + public Balanced_tokensContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_balanced_tokens; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterBalanced_tokens(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitBalanced_tokens(this); + } + } + + [RuleVersion(0)] + public Balanced_tokensContext balanced_tokens() { + Balanced_tokensContext _localctx = new Balanced_tokensContext(Context, State); + EnterRule(_localctx, 208, RULE_balanced_tokens); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1137; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 129)) & ~0x3f) == 0 && ((1L << (_la - 129)) & ((1L << (OpDot - 129)) | (1L << (OpComma - 129)) | (1L << (OpColon - 129)) | (1L << (OpSemi - 129)) | (1L << (OpAt - 129)) | (1L << (OpPound - 129)) | (1L << (OpBackTick - 129)) | (1L << (OpLParen - 129)) | (1L << (OpLBracket - 129)) | (1L << (OpLBrace - 129)) | (1L << (Operator - 129)))) != 0)) { + { + { + State = 1134; + balanced_token(); + } + } + State = 1139; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Balanced_tokenContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokensContext balanced_tokens() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public LiteralContext literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Any_punctuation_for_balanced_tokenContext any_punctuation_for_balanced_token() { + return GetRuleContext(0); + } + public Balanced_tokenContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_balanced_token; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterBalanced_token(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitBalanced_token(this); + } + } + + [RuleVersion(0)] + public Balanced_tokenContext balanced_token() { + Balanced_tokenContext _localctx = new Balanced_tokenContext(Context, State); + EnterRule(_localctx, 210, RULE_balanced_token); + try { + State = 1156; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,147,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1140; + Match(OpLParen); + State = 1141; + balanced_tokens(); + State = 1142; + Match(OpRParen); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1144; + Match(OpLBracket); + State = 1145; + balanced_tokens(); + State = 1146; + Match(OpRBracket); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1148; + Match(OpLBrace); + State = 1149; + balanced_tokens(); + State = 1150; + Match(OpRBrace); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 1152; + label_identifier(); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 1153; + literal(); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 1154; + @operator(); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 1155; + any_punctuation_for_balanced_token(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Any_punctuation_for_balanced_tokenContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpSemi() { return GetToken(SwiftInterfaceParser.OpSemi, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPound() { return GetToken(SwiftInterfaceParser.OpPound, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBackTick() { return GetToken(SwiftInterfaceParser.OpBackTick, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { + return GetRuleContext(0); + } + public Any_punctuation_for_balanced_tokenContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_any_punctuation_for_balanced_token; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAny_punctuation_for_balanced_token(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAny_punctuation_for_balanced_token(this); + } + } + + [RuleVersion(0)] + public Any_punctuation_for_balanced_tokenContext any_punctuation_for_balanced_token() { + Any_punctuation_for_balanced_tokenContext _localctx = new Any_punctuation_for_balanced_tokenContext(Context, State); + EnterRule(_localctx, 212, RULE_any_punctuation_for_balanced_token); + int _la; + try { + State = 1160; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case OpAssign: + case OpQuestion: + case OpDot: + case OpComma: + case OpColon: + case OpSemi: + case OpAt: + case OpPound: + case OpBackTick: + EnterOuterAlt(_localctx, 1); + { + State = 1158; + _la = TokenStream.LA(1); + if ( !(((((_la - 124)) & ~0x3f) == 0 && ((1L << (_la - 124)) & ((1L << (OpAssign - 124)) | (1L << (OpQuestion - 124)) | (1L << (OpDot - 124)) | (1L << (OpComma - 124)) | (1L << (OpColon - 124)) | (1L << (OpSemi - 124)) | (1L << (OpAt - 124)) | (1L << (OpPound - 124)) | (1L << (OpBackTick - 124)))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + break; + case T__65: + EnterOuterAlt(_localctx, 2); + { + State = 1159; + arrow_operator(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Declaration_modifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { + return GetRuleContext(0); + } + public Declaration_modifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_declaration_modifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDeclaration_modifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDeclaration_modifier(this); + } + } + + [RuleVersion(0)] + public Declaration_modifierContext declaration_modifier() { + Declaration_modifierContext _localctx = new Declaration_modifierContext(Context, State); + EnterRule(_localctx, 214, RULE_declaration_modifier); + try { + State = 1186; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,149,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1162; + Match(T__3); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1163; + Match(T__34); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1164; + Match(T__35); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 1165; + Match(T__13); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 1166; + Match(T__17); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 1167; + Match(T__36); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 1168; + Match(T__37); + } + break; + case 8: + EnterOuterAlt(_localctx, 8); + { + State = 1169; + Match(T__38); + } + break; + case 9: + EnterOuterAlt(_localctx, 9); + { + State = 1170; + Match(T__16); + } + break; + case 10: + EnterOuterAlt(_localctx, 10); + { + State = 1171; + Match(T__14); + } + break; + case 11: + EnterOuterAlt(_localctx, 11); + { + State = 1172; + Match(T__39); + } + break; + case 12: + EnterOuterAlt(_localctx, 12); + { + State = 1173; + Match(T__40); + } + break; + case 13: + EnterOuterAlt(_localctx, 13); + { + State = 1174; + Match(T__41); + } + break; + case 14: + EnterOuterAlt(_localctx, 14); + { + State = 1175; + Match(T__41); + State = 1176; + Match(OpLParen); + State = 1177; + Match(T__42); + State = 1178; + Match(OpRParen); + } + break; + case 15: + EnterOuterAlt(_localctx, 15); + { + State = 1179; + Match(T__41); + State = 1180; + Match(OpLParen); + State = 1181; + Match(T__43); + State = 1182; + Match(OpRParen); + } + break; + case 16: + EnterOuterAlt(_localctx, 16); + { + State = 1183; + Match(T__44); + } + break; + case 17: + EnterOuterAlt(_localctx, 17); + { + State = 1184; + access_level_modifier(); + } + break; + case 18: + EnterOuterAlt(_localctx, 18); + { + State = 1185; + mutation_modifier(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Declaration_modifiersContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifierContext[] declaration_modifier() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifierContext declaration_modifier(int i) { + return GetRuleContext(i); + } + public Declaration_modifiersContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_declaration_modifiers; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDeclaration_modifiers(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDeclaration_modifiers(this); + } + } + + [RuleVersion(0)] + public Declaration_modifiersContext declaration_modifiers() { + Declaration_modifiersContext _localctx = new Declaration_modifiersContext(Context, State); + EnterRule(_localctx, 216, RULE_declaration_modifiers); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1189; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + do { + { + { + State = 1188; + declaration_modifier(); + } + } + State = 1191; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) ); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Access_level_modifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + public Access_level_modifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_access_level_modifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAccess_level_modifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAccess_level_modifier(this); + } + } + + [RuleVersion(0)] + public Access_level_modifierContext access_level_modifier() { + Access_level_modifierContext _localctx = new Access_level_modifierContext(Context, State); + EnterRule(_localctx, 218, RULE_access_level_modifier); + try { + State = 1218; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,151,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1193; + Match(T__45); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1194; + Match(T__45); + State = 1195; + Match(OpLParen); + State = 1196; + Match(T__10); + State = 1197; + Match(OpRParen); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1198; + Match(T__46); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 1199; + Match(T__46); + State = 1200; + Match(OpLParen); + State = 1201; + Match(T__10); + State = 1202; + Match(OpRParen); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 1203; + Match(T__47); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 1204; + Match(T__47); + State = 1205; + Match(OpLParen); + State = 1206; + Match(T__10); + State = 1207; + Match(OpRParen); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 1208; + Match(T__48); + } + break; + case 8: + EnterOuterAlt(_localctx, 8); + { + State = 1209; + Match(T__48); + State = 1210; + Match(OpLParen); + State = 1211; + Match(T__10); + State = 1212; + Match(OpRParen); + } + break; + case 9: + EnterOuterAlt(_localctx, 9); + { + State = 1213; + Match(T__49); + } + break; + case 10: + EnterOuterAlt(_localctx, 10); + { + State = 1214; + Match(T__49); + State = 1215; + Match(OpLParen); + State = 1216; + Match(T__10); + State = 1217; + Match(OpRParen); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Mutation_modifierContext : ParserRuleContext { + public Mutation_modifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_mutation_modifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterMutation_modifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitMutation_modifier(this); + } + } + + [RuleVersion(0)] + public Mutation_modifierContext mutation_modifier() { + Mutation_modifierContext _localctx = new Mutation_modifierContext(Context, State); + EnterRule(_localctx, 220, RULE_mutation_modifier); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1220; + _la = TokenStream.LA(1); + if ( !(_la==T__50 || _la==T__51) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class PatternContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Wildcard_patternContext wildcard_pattern() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Identifier_patternContext identifier_pattern() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public PatternContext pattern() { + return GetRuleContext(0); + } + public PatternContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_pattern; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterPattern(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitPattern(this); + } + } + + [RuleVersion(0)] + public PatternContext pattern() { + return pattern(0); + } + + private PatternContext pattern(int _p) { + ParserRuleContext _parentctx = Context; + int _parentState = State; + PatternContext _localctx = new PatternContext(Context, _parentState); + PatternContext _prevctx = _localctx; + int _startState = 222; + EnterRecursionRule(_localctx, 222, RULE_pattern, _p); + try { + int _alt; + EnterOuterAlt(_localctx, 1); + { + State = 1233; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case OpUnder: + { + State = 1223; + wildcard_pattern(); + State = 1225; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,152,Context) ) { + case 1: + { + State = 1224; + type_annotation(); + } + break; + } + } + break; + case T__9: + case T__10: + case T__11: + case T__13: + case T__14: + case T__16: + case T__17: + case T__19: + case T__20: + case T__21: + case T__22: + case T__23: + case T__24: + case T__25: + case T__34: + case T__35: + case T__36: + case T__37: + case T__38: + case T__39: + case T__41: + case T__42: + case T__43: + case T__44: + case T__49: + case T__50: + case T__51: + case T__54: + case T__55: + case T__67: + case T__68: + case T__69: + case T__70: + case T__71: + case T__72: + case T__73: + case T__74: + case T__75: + case T__76: + case T__77: + case T__78: + case T__79: + case T__80: + case T__81: + case T__82: + case T__83: + case T__84: + case T__85: + case T__86: + case T__87: + case T__88: + case T__89: + case T__90: + case T__91: + case Identifier: + { + State = 1227; + identifier_pattern(); + State = 1229; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,153,Context) ) { + case 1: + { + State = 1228; + type_annotation(); + } + break; + } + } + break; + case T__52: + { + State = 1231; + Match(T__52); + State = 1232; + type(0); + } + break; + default: + throw new NoViableAltException(this); + } + Context.Stop = TokenStream.LT(-1); + State = 1240; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,155,Context); + while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) { + if ( _alt==1 ) { + if ( ParseListeners!=null ) + TriggerExitRuleEvent(); + _prevctx = _localctx; + { + { + _localctx = new PatternContext(_parentctx, _parentState); + PushNewRecursionContext(_localctx, _startState, RULE_pattern); + State = 1235; + if (!(Precpred(Context, 1))) throw new FailedPredicateException(this, "Precpred(Context, 1)"); + State = 1236; + Match(T__53); + State = 1237; + type(0); + } + } + } + State = 1242; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,155,Context); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + UnrollRecursionContexts(_parentctx); + } + return _localctx; + } + + public partial class Wildcard_patternContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpUnder() { return GetToken(SwiftInterfaceParser.OpUnder, 0); } + public Wildcard_patternContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_wildcard_pattern; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterWildcard_pattern(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitWildcard_pattern(this); + } + } + + [RuleVersion(0)] + public Wildcard_patternContext wildcard_pattern() { + Wildcard_patternContext _localctx = new Wildcard_patternContext(Context, State); + EnterRule(_localctx, 224, RULE_wildcard_pattern); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1243; + Match(OpUnder); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Identifier_patternContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Identifier_patternContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_identifier_pattern; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterIdentifier_pattern(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitIdentifier_pattern(this); + } + } + + [RuleVersion(0)] + public Identifier_patternContext identifier_pattern() { + Identifier_patternContext _localctx = new Identifier_patternContext(Context, State); + EnterRule(_localctx, 226, RULE_identifier_pattern); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1245; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_typeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_clauseContext function_type_argument_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + public Function_typeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_type; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_type(this); + } + } + + [RuleVersion(0)] + public Function_typeContext function_type() { + Function_typeContext _localctx = new Function_typeContext(Context, State); + EnterRule(_localctx, 228, RULE_function_type); + int _la; + try { + State = 1265; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,159,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1248; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 1247; + attributes(); + } + } + + State = 1250; + function_type_argument_clause(); + State = 1252; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__30) { + { + State = 1251; + Match(T__30); + } + } + + State = 1254; + arrow_operator(); + State = 1255; + type(0); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1258; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpAt) { + { + State = 1257; + attributes(); + } + } + + State = 1260; + function_type_argument_clause(); + State = 1261; + Match(T__31); + State = 1262; + arrow_operator(); + State = 1263; + type(0); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_type_argument_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_listContext function_type_argument_list() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Range_operatorContext range_operator() { + return GetRuleContext(0); + } + public Function_type_argument_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_type_argument_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_type_argument_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_type_argument_clause(this); + } + } + + [RuleVersion(0)] + public Function_type_argument_clauseContext function_type_argument_clause() { + Function_type_argument_clauseContext _localctx = new Function_type_argument_clauseContext(Context, State); + EnterRule(_localctx, 230, RULE_function_type_argument_clause); + int _la; + try { + State = 1276; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,161,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1267; + Match(OpLParen); + State = 1268; + Match(OpRParen); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1269; + Match(OpLParen); + State = 1270; + function_type_argument_list(); + State = 1272; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__66) { + { + State = 1271; + range_operator(); + } + } + + State = 1274; + Match(OpRParen); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_type_argument_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Function_type_argumentContext function_type_argument() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_listContext function_type_argument_list() { + return GetRuleContext(0); + } + public Function_type_argument_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_type_argument_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_type_argument_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_type_argument_list(this); + } + } + + [RuleVersion(0)] + public Function_type_argument_listContext function_type_argument_list() { + Function_type_argument_listContext _localctx = new Function_type_argument_listContext(Context, State); + EnterRule(_localctx, 232, RULE_function_type_argument_list); + try { + State = 1283; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,162,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1278; + function_type_argument(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1279; + function_type_argument(); + State = 1280; + Match(OpComma); + State = 1281; + function_type_argument_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Function_type_argumentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Inout_clauseContext inout_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Argument_labelContext argument_label() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { + return GetRuleContext(0); + } + public Function_type_argumentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_function_type_argument; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunction_type_argument(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunction_type_argument(this); + } + } + + [RuleVersion(0)] + public Function_type_argumentContext function_type_argument() { + Function_type_argumentContext _localctx = new Function_type_argumentContext(Context, State); + EnterRule(_localctx, 234, RULE_function_type_argument); + int _la; + try { + State = 1295; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,165,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1286; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,163,Context) ) { + case 1: + { + State = 1285; + attributes(); + } + break; + } + State = 1289; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__59) { + { + State = 1288; + inout_clause(); + } + } + + State = 1291; + type(0); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1292; + argument_label(); + State = 1293; + type_annotation(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Argument_labelContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext[] label_identifier() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier(int i) { + return GetRuleContext(i); + } + public Argument_labelContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_argument_label; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterArgument_label(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitArgument_label(this); + } + } + + [RuleVersion(0)] + public Argument_labelContext argument_label() { + Argument_labelContext _localctx = new Argument_labelContext(Context, State); + EnterRule(_localctx, 236, RULE_argument_label); + try { + State = 1301; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,166,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1297; + label_identifier(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1298; + label_identifier(); + State = 1299; + label_identifier(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class TypeContext : ParserRuleContext { + public TypeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type; } } + + public TypeContext() { } + public virtual void CopyFrom(TypeContext context) { + base.CopyFrom(context); + } + } + public partial class Dict_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Dictionary_typeContext dictionary_type() { + return GetRuleContext(0); + } + public Dict_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDict_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDict_type(this); + } + } + public partial class Any_typeContext : TypeContext { + public Any_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAny_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAny_type(this); + } + } + public partial class Identifier_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + public Identifier_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterIdentifier_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitIdentifier_type(this); + } + } + public partial class Func_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Function_typeContext function_type() { + return GetRuleContext(0); + } + public Func_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterFunc_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitFunc_type(this); + } + } + public partial class Arr_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Array_typeContext array_type() { + return GetRuleContext(0); + } + public Arr_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterArr_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitArr_type(this); + } + } + public partial class Meta_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + public Meta_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterMeta_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitMeta_type(this); + } + } + public partial class Boxed_protocol_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Any_clauseContext any_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + public Boxed_protocol_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterBoxed_protocol_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitBoxed_protocol_type(this); + } + } + public partial class Optional_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } + public Optional_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOptional_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOptional_type(this); + } + } + public partial class Self_typeContext : TypeContext { + public Self_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSelf_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSelf_type(this); + } + } + public partial class Unwrapped_optional_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } + public Unwrapped_optional_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterUnwrapped_optional_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitUnwrapped_optional_type(this); + } + } + public partial class Proto_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + public Proto_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProto_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProto_type(this); + } + } + public partial class Tup_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Tuple_typeContext tuple_type() { + return GetRuleContext(0); + } + public Tup_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTup_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTup_type(this); + } + } + public partial class Self_longContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + public Self_longContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSelf_long(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSelf_long(this); + } + } + public partial class Proto_comp_typeContext : TypeContext { + [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { + return GetRuleContext(0); + } + public Proto_comp_typeContext(TypeContext context) { CopyFrom(context); } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProto_comp_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProto_comp_type(this); + } + } + + [RuleVersion(0)] + public TypeContext type() { + return type(0); + } + + private TypeContext type(int _p) { + ParserRuleContext _parentctx = Context; + int _parentState = State; + TypeContext _localctx = new TypeContext(Context, _parentState); + TypeContext _prevctx = _localctx; + int _startState = 238; + EnterRecursionRule(_localctx, 238, RULE_type, _p); + try { + int _alt; + EnterOuterAlt(_localctx, 1); + { + State = 1318; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,167,Context) ) { + case 1: + { + _localctx = new Arr_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + + State = 1304; + array_type(); + } + break; + case 2: + { + _localctx = new Dict_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1305; + dictionary_type(); + } + break; + case 3: + { + _localctx = new Func_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1306; + function_type(); + } + break; + case 4: + { + _localctx = new Identifier_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1307; + type_identifier(); + } + break; + case 5: + { + _localctx = new Tup_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1308; + tuple_type(); + } + break; + case 6: + { + _localctx = new Proto_comp_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1309; + protocol_composition_type(); + } + break; + case 7: + { + _localctx = new Boxed_protocol_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1310; + any_clause(); + State = 1311; + type(4); + } + break; + case 8: + { + _localctx = new Any_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1313; + Match(T__56); + } + break; + case 9: + { + _localctx = new Self_typeContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1314; + Match(T__57); + } + break; + case 10: + { + _localctx = new Self_longContext(_localctx); + Context = _localctx; + _prevctx = _localctx; + State = 1315; + Match(T__57); + State = 1316; + Match(OpDot); + State = 1317; + type_identifier(); + } + break; + } + Context.Stop = TokenStream.LT(-1); + State = 1332; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,169,Context); + while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) { + if ( _alt==1 ) { + if ( ParseListeners!=null ) + TriggerExitRuleEvent(); + _prevctx = _localctx; + { + State = 1330; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,168,Context) ) { + case 1: + { + _localctx = new Optional_typeContext(new TypeContext(_parentctx, _parentState)); + PushNewRecursionContext(_localctx, _startState, RULE_type); + State = 1320; + if (!(Precpred(Context, 9))) throw new FailedPredicateException(this, "Precpred(Context, 9)"); + State = 1321; + Match(OpQuestion); + } + break; + case 2: + { + _localctx = new Unwrapped_optional_typeContext(new TypeContext(_parentctx, _parentState)); + PushNewRecursionContext(_localctx, _startState, RULE_type); + State = 1322; + if (!(Precpred(Context, 8))) throw new FailedPredicateException(this, "Precpred(Context, 8)"); + State = 1323; + Match(OpBang); + } + break; + case 3: + { + _localctx = new Meta_typeContext(new TypeContext(_parentctx, _parentState)); + PushNewRecursionContext(_localctx, _startState, RULE_type); + State = 1324; + if (!(Precpred(Context, 6))) throw new FailedPredicateException(this, "Precpred(Context, 6)"); + State = 1325; + Match(OpDot); + State = 1326; + Match(T__54); + } + break; + case 4: + { + _localctx = new Proto_typeContext(new TypeContext(_parentctx, _parentState)); + PushNewRecursionContext(_localctx, _startState, RULE_type); + State = 1327; + if (!(Precpred(Context, 5))) throw new FailedPredicateException(this, "Precpred(Context, 5)"); + State = 1328; + Match(OpDot); + State = 1329; + Match(T__55); + } + break; + } + } + } + State = 1334; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,169,Context); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + UnrollRecursionContexts(_parentctx); + } + return _localctx; + } + + public partial class Type_annotationContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Inout_clauseContext inout_clause() { + return GetRuleContext(0); + } + public Type_annotationContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type_annotation; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterType_annotation(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitType_annotation(this); + } + } + + [RuleVersion(0)] + public Type_annotationContext type_annotation() { + Type_annotationContext _localctx = new Type_annotationContext(Context, State); + EnterRule(_localctx, 240, RULE_type_annotation); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1335; + Match(OpColon); + State = 1337; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,170,Context) ) { + case 1: + { + State = 1336; + attributes(); + } + break; + } + State = 1340; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==T__59) { + { + State = 1339; + inout_clause(); + } + } + + State = 1342; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Any_clauseContext : ParserRuleContext { + public Any_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_any_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterAny_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitAny_clause(this); + } + } + + [RuleVersion(0)] + public Any_clauseContext any_clause() { + Any_clauseContext _localctx = new Any_clauseContext(Context, State); + EnterRule(_localctx, 242, RULE_any_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1344; + Match(T__58); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Inout_clauseContext : ParserRuleContext { + public Inout_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_inout_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInout_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInout_clause(this); + } + } + + [RuleVersion(0)] + public Inout_clauseContext inout_clause() { + Inout_clauseContext _localctx = new Inout_clauseContext(Context, State); + EnterRule(_localctx, 244, RULE_inout_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1346; + Match(T__59); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Type_identifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_nameContext type_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_argument_clauseContext generic_argument_clause() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + public Type_identifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type_identifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterType_identifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitType_identifier(this); + } + } + + [RuleVersion(0)] + public Type_identifierContext type_identifier() { + Type_identifierContext _localctx = new Type_identifierContext(Context, State); + EnterRule(_localctx, 246, RULE_type_identifier); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1348; + type_name(); + State = 1350; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,172,Context) ) { + case 1: + { + State = 1349; + generic_argument_clause(); + } + break; + } + State = 1354; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,173,Context) ) { + case 1: + { + State = 1352; + Match(OpDot); + State = 1353; + type_identifier(); + } + break; + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Type_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { + return GetRuleContext(0); + } + public Type_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_type_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterType_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitType_name(this); + } + } + + [RuleVersion(0)] + public Type_nameContext type_name() { + Type_nameContext _localctx = new Type_nameContext(Context, State); + EnterRule(_localctx, 248, RULE_type_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1356; + declaration_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Tuple_typeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_element_listContext tuple_type_element_list() { + return GetRuleContext(0); + } + public Tuple_typeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_tuple_type; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTuple_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTuple_type(this); + } + } + + [RuleVersion(0)] + public Tuple_typeContext tuple_type() { + Tuple_typeContext _localctx = new Tuple_typeContext(Context, State); + EnterRule(_localctx, 250, RULE_tuple_type); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1358; + Match(OpLParen); + State = 1360; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__58) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Identifier - 64)))) != 0) || ((((_la - 134)) & ~0x3f) == 0 && ((1L << (_la - 134)) & ((1L << (OpAt - 134)) | (1L << (OpLParen - 134)) | (1L << (OpLBracket - 134)))) != 0)) { + { + State = 1359; + tuple_type_element_list(); + } + } + + State = 1362; + Match(OpRParen); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Tuple_type_element_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_elementContext tuple_type_element() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_element_listContext tuple_type_element_list() { + return GetRuleContext(0); + } + public Tuple_type_element_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_tuple_type_element_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTuple_type_element_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTuple_type_element_list(this); + } + } + + [RuleVersion(0)] + public Tuple_type_element_listContext tuple_type_element_list() { + Tuple_type_element_listContext _localctx = new Tuple_type_element_listContext(Context, State); + EnterRule(_localctx, 252, RULE_tuple_type_element_list); + try { + State = 1369; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,175,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1364; + tuple_type_element(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1365; + tuple_type_element(); + State = 1366; + Match(OpComma); + State = 1367; + tuple_type_element_list(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Tuple_type_elementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Element_nameContext element_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + public Tuple_type_elementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_tuple_type_element; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterTuple_type_element(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitTuple_type_element(this); + } + } + + [RuleVersion(0)] + public Tuple_type_elementContext tuple_type_element() { + Tuple_type_elementContext _localctx = new Tuple_type_elementContext(Context, State); + EnterRule(_localctx, 254, RULE_tuple_type_element); + try { + State = 1375; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,176,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1371; + element_name(); + State = 1372; + type_annotation(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1374; + type(0); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Element_nameContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { + return GetRuleContext(0); + } + public Element_nameContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_element_name; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterElement_name(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitElement_name(this); + } + } + + [RuleVersion(0)] + public Element_nameContext element_name() { + Element_nameContext _localctx = new Element_nameContext(Context, State); + EnterRule(_localctx, 256, RULE_element_name); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1377; + label_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Array_typeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } + public Array_typeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_array_type; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterArray_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitArray_type(this); + } + } + + [RuleVersion(0)] + public Array_typeContext array_type() { + Array_typeContext _localctx = new Array_typeContext(Context, State); + EnterRule(_localctx, 258, RULE_array_type); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1379; + Match(OpLBracket); + State = 1380; + type(0); + State = 1381; + Match(OpRBracket); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Dictionary_typeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext[] type() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } + public Dictionary_typeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_dictionary_type; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterDictionary_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitDictionary_type(this); + } + } + + [RuleVersion(0)] + public Dictionary_typeContext dictionary_type() { + Dictionary_typeContext _localctx = new Dictionary_typeContext(Context, State); + EnterRule(_localctx, 260, RULE_dictionary_type); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1383; + Match(OpLBracket); + State = 1384; + type(0); + State = 1385; + Match(OpColon); + State = 1386; + type(0); + State = 1387; + Match(OpRBracket); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_composition_typeContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Protocol_identifierContext[] protocol_identifier() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_identifierContext protocol_identifier(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpAmp() { return GetTokens(SwiftInterfaceParser.OpAmp); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAmp(int i) { + return GetToken(SwiftInterfaceParser.OpAmp, i); + } + public Protocol_composition_typeContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_composition_type; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_composition_type(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_composition_type(this); + } + } + + [RuleVersion(0)] + public Protocol_composition_typeContext protocol_composition_type() { + Protocol_composition_typeContext _localctx = new Protocol_composition_typeContext(Context, State); + EnterRule(_localctx, 262, RULE_protocol_composition_type); + try { + int _alt; + EnterOuterAlt(_localctx, 1); + { + State = 1389; + protocol_identifier(); + State = 1392; + ErrorHandler.Sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + State = 1390; + Match(OpAmp); + State = 1391; + protocol_identifier(); + } + } + break; + default: + throw new NoViableAltException(this); + } + State = 1394; + ErrorHandler.Sync(this); + _alt = Interpreter.AdaptivePredict(TokenStream,177,Context); + } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Protocol_identifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + public Protocol_identifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_protocol_identifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterProtocol_identifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitProtocol_identifier(this); + } + } + + [RuleVersion(0)] + public Protocol_identifierContext protocol_identifier() { + Protocol_identifierContext _localctx = new Protocol_identifierContext(Context, State); + EnterRule(_localctx, 264, RULE_protocol_identifier); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1396; + type_identifier(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class LiteralContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Numeric_literalContext numeric_literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public String_literalContext string_literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Nil_literalContext nil_literal() { + return GetRuleContext(0); + } + public LiteralContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterLiteral(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitLiteral(this); + } + } + + [RuleVersion(0)] + public LiteralContext literal() { + LiteralContext _localctx = new LiteralContext(Context, State); + EnterRule(_localctx, 266, RULE_literal); + try { + State = 1402; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case Binary_literal: + case Octal_literal: + case Decimal_literal: + case Pure_decimal_digits: + case Hexadecimal_literal: + case OpPlus: + case OpMinus: + EnterOuterAlt(_localctx, 1); + { + State = 1398; + numeric_literal(); + } + break; + case Static_string_literal: + EnterOuterAlt(_localctx, 2); + { + State = 1399; + string_literal(); + } + break; + case T__61: + case T__62: + EnterOuterAlt(_localctx, 3); + { + State = 1400; + boolean_literal(); + } + break; + case T__60: + EnterOuterAlt(_localctx, 4); + { + State = 1401; + nil_literal(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Nil_literalContext : ParserRuleContext { + public Nil_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_nil_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterNil_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitNil_literal(this); + } + } + + [RuleVersion(0)] + public Nil_literalContext nil_literal() { + Nil_literalContext _localctx = new Nil_literalContext(Context, State); + EnterRule(_localctx, 268, RULE_nil_literal); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1404; + Match(T__60); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Boolean_literalContext : ParserRuleContext { + public Boolean_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_boolean_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterBoolean_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitBoolean_literal(this); + } + } + + [RuleVersion(0)] + public Boolean_literalContext boolean_literal() { + Boolean_literalContext _localctx = new Boolean_literalContext(Context, State); + EnterRule(_localctx, 270, RULE_boolean_literal); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1406; + _la = TokenStream.LA(1); + if ( !(_la==T__61 || _la==T__62) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Numeric_literalContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Integer_literalContext integer_literal() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPlus() { return GetToken(SwiftInterfaceParser.OpPlus, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpMinus() { return GetToken(SwiftInterfaceParser.OpMinus, 0); } + public Numeric_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_numeric_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterNumeric_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitNumeric_literal(this); + } + } + + [RuleVersion(0)] + public Numeric_literalContext numeric_literal() { + Numeric_literalContext _localctx = new Numeric_literalContext(Context, State); + EnterRule(_localctx, 272, RULE_numeric_literal); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1409; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + if (_la==OpPlus || _la==OpMinus) { + { + State = 1408; + _la = TokenStream.LA(1); + if ( !(_la==OpPlus || _la==OpMinus) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + + State = 1411; + integer_literal(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Integer_literalContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Binary_literal() { return GetToken(SwiftInterfaceParser.Binary_literal, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Octal_literal() { return GetToken(SwiftInterfaceParser.Octal_literal, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Decimal_literal() { return GetToken(SwiftInterfaceParser.Decimal_literal, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Pure_decimal_digits() { return GetToken(SwiftInterfaceParser.Pure_decimal_digits, 0); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Hexadecimal_literal() { return GetToken(SwiftInterfaceParser.Hexadecimal_literal, 0); } + public Integer_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_integer_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterInteger_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitInteger_literal(this); + } + } + + [RuleVersion(0)] + public Integer_literalContext integer_literal() { + Integer_literalContext _localctx = new Integer_literalContext(Context, State); + EnterRule(_localctx, 274, RULE_integer_literal); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1413; + _la = TokenStream.LA(1); + if ( !(((((_la - 113)) & ~0x3f) == 0 && ((1L << (_la - 113)) & ((1L << (Binary_literal - 113)) | (1L << (Octal_literal - 113)) | (1L << (Decimal_literal - 113)) | (1L << (Pure_decimal_digits - 113)) | (1L << (Hexadecimal_literal - 113)))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class String_literalContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Static_string_literal() { return GetToken(SwiftInterfaceParser.Static_string_literal, 0); } + public String_literalContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_string_literal; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterString_literal(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitString_literal(this); + } + } + + [RuleVersion(0)] + public String_literalContext string_literal() { + String_literalContext _localctx = new String_literalContext(Context, State); + EnterRule(_localctx, 276, RULE_string_literal); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1415; + Match(Static_string_literal); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Label_identifierContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Identifier() { return GetToken(SwiftInterfaceParser.Identifier, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Keyword_as_identifier_in_labelsContext keyword_as_identifier_in_labels() { + return GetRuleContext(0); + } + public Label_identifierContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_label_identifier; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterLabel_identifier(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitLabel_identifier(this); + } + } + + [RuleVersion(0)] + public Label_identifierContext label_identifier() { + Label_identifierContext _localctx = new Label_identifierContext(Context, State); + EnterRule(_localctx, 278, RULE_label_identifier); + try { + State = 1419; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case Identifier: + EnterOuterAlt(_localctx, 1); + { + State = 1417; + Match(Identifier); + } + break; + case T__0: + case T__1: + case T__2: + case T__3: + case T__4: + case T__5: + case T__7: + case T__9: + case T__10: + case T__11: + case T__12: + case T__13: + case T__14: + case T__15: + case T__16: + case T__17: + case T__18: + case T__19: + case T__20: + case T__21: + case T__22: + case T__23: + case T__24: + case T__25: + case T__26: + case T__27: + case T__28: + case T__30: + case T__31: + case T__32: + case T__33: + case T__34: + case T__35: + case T__36: + case T__37: + case T__38: + case T__39: + case T__40: + case T__41: + case T__42: + case T__43: + case T__44: + case T__45: + case T__46: + case T__47: + case T__48: + case T__49: + case T__50: + case T__51: + case T__52: + case T__53: + case T__54: + case T__55: + case T__56: + case T__57: + case T__60: + case T__61: + case T__62: + case T__63: + case T__67: + case T__68: + case T__69: + case T__70: + case T__71: + case T__72: + case T__73: + case T__74: + case T__75: + case T__76: + case T__77: + case T__78: + case T__79: + case T__80: + case T__81: + case T__82: + case T__83: + case T__84: + case T__85: + case T__86: + case T__87: + case T__88: + case T__89: + case T__90: + case T__91: + case T__92: + case T__93: + case T__94: + case T__95: + case T__96: + case T__97: + case T__98: + case T__99: + case T__100: + case T__101: + case T__102: + case T__103: + case T__104: + case T__105: + case T__106: + case T__107: + case T__108: + case T__109: + case T__110: + case T__111: + EnterOuterAlt(_localctx, 2); + { + State = 1418; + keyword_as_identifier_in_labels(); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_parameter_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLess() { return GetToken(SwiftInterfaceParser.OpLess, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_listContext generic_parameter_list() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { + return GetRuleContext(0); + } + public Generic_parameter_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_parameter_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_parameter_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_parameter_clause(this); + } + } + + [RuleVersion(0)] + public Generic_parameter_clauseContext generic_parameter_clause() { + Generic_parameter_clauseContext _localctx = new Generic_parameter_clauseContext(Context, State); + EnterRule(_localctx, 280, RULE_generic_parameter_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1421; + Match(OpLess); + State = 1422; + generic_parameter_list(); + State = 1423; + opGreater(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_parameter_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameterContext[] generic_parameter() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_parameterContext generic_parameter(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Generic_parameter_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_parameter_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_parameter_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_parameter_list(this); + } + } + + [RuleVersion(0)] + public Generic_parameter_listContext generic_parameter_list() { + Generic_parameter_listContext _localctx = new Generic_parameter_listContext(Context, State); + EnterRule(_localctx, 282, RULE_generic_parameter_list); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1425; + generic_parameter(); + State = 1430; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 1426; + Match(OpComma); + State = 1427; + generic_parameter(); + } + } + State = 1432; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_parameterContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_nameContext type_name() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { + return GetRuleContext(0); + } + public Generic_parameterContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_parameter; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_parameter(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_parameter(this); + } + } + + [RuleVersion(0)] + public Generic_parameterContext generic_parameter() { + Generic_parameterContext _localctx = new Generic_parameterContext(Context, State); + EnterRule(_localctx, 284, RULE_generic_parameter); + try { + State = 1442; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,182,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1433; + type_name(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1434; + type_name(); + State = 1435; + Match(OpColon); + State = 1436; + type_identifier(); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1438; + type_name(); + State = 1439; + Match(OpColon); + State = 1440; + protocol_composition_type(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_where_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Requirement_listContext requirement_list() { + return GetRuleContext(0); + } + public Generic_where_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_where_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_where_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_where_clause(this); + } + } + + [RuleVersion(0)] + public Generic_where_clauseContext generic_where_clause() { + Generic_where_clauseContext _localctx = new Generic_where_clauseContext(Context, State); + EnterRule(_localctx, 286, RULE_generic_where_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1444; + Match(T__63); + State = 1445; + requirement_list(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Requirement_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public RequirementContext[] requirement() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public RequirementContext requirement(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Requirement_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_requirement_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRequirement_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRequirement_list(this); + } + } + + [RuleVersion(0)] + public Requirement_listContext requirement_list() { + Requirement_listContext _localctx = new Requirement_listContext(Context, State); + EnterRule(_localctx, 288, RULE_requirement_list); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1447; + requirement(); + State = 1452; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 1448; + Match(OpComma); + State = 1449; + requirement(); + } + } + State = 1454; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class RequirementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Conformance_requirementContext conformance_requirement() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public Same_type_requirementContext same_type_requirement() { + return GetRuleContext(0); + } + public RequirementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_requirement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRequirement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRequirement(this); + } + } + + [RuleVersion(0)] + public RequirementContext requirement() { + RequirementContext _localctx = new RequirementContext(Context, State); + EnterRule(_localctx, 290, RULE_requirement); + try { + State = 1457; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,184,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1455; + conformance_requirement(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1456; + same_type_requirement(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Conformance_requirementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext[] type_identifier() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { + return GetRuleContext(0); + } + public Conformance_requirementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_conformance_requirement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterConformance_requirement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitConformance_requirement(this); + } + } + + [RuleVersion(0)] + public Conformance_requirementContext conformance_requirement() { + Conformance_requirementContext _localctx = new Conformance_requirementContext(Context, State); + EnterRule(_localctx, 292, RULE_conformance_requirement); + try { + State = 1467; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,185,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1459; + type_identifier(); + State = 1460; + Match(OpColon); + State = 1461; + type_identifier(); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1463; + type_identifier(); + State = 1464; + Match(OpColon); + State = 1465; + protocol_composition_type(); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Same_type_requirementContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + public Same_type_requirementContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_same_type_requirement; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterSame_type_requirement(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitSame_type_requirement(this); + } + } + + [RuleVersion(0)] + public Same_type_requirementContext same_type_requirement() { + Same_type_requirementContext _localctx = new Same_type_requirementContext(Context, State); + EnterRule(_localctx, 294, RULE_same_type_requirement); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1469; + type_identifier(); + State = 1470; + @operator(); + State = 1471; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_argument_clauseContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLess() { return GetToken(SwiftInterfaceParser.OpLess, 0); } + [System.Diagnostics.DebuggerNonUserCode] public Generic_argument_listContext generic_argument_list() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { + return GetRuleContext(0); + } + public Generic_argument_clauseContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_argument_clause; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_argument_clause(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_argument_clause(this); + } + } + + [RuleVersion(0)] + public Generic_argument_clauseContext generic_argument_clause() { + Generic_argument_clauseContext _localctx = new Generic_argument_clauseContext(Context, State); + EnterRule(_localctx, 296, RULE_generic_argument_clause); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1473; + Match(OpLess); + State = 1474; + generic_argument_list(); + State = 1475; + opGreater(); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_argument_listContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Generic_argumentContext[] generic_argument() { + return GetRuleContexts(); + } + [System.Diagnostics.DebuggerNonUserCode] public Generic_argumentContext generic_argument(int i) { + return GetRuleContext(i); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { + return GetToken(SwiftInterfaceParser.OpComma, i); + } + public Generic_argument_listContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_argument_list; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_argument_list(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_argument_list(this); + } + } + + [RuleVersion(0)] + public Generic_argument_listContext generic_argument_list() { + Generic_argument_listContext _localctx = new Generic_argument_listContext(Context, State); + EnterRule(_localctx, 298, RULE_generic_argument_list); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1477; + generic_argument(); + State = 1482; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + while (_la==OpComma) { + { + { + State = 1478; + Match(OpComma); + State = 1479; + generic_argument(); + } + } + State = 1484; + ErrorHandler.Sync(this); + _la = TokenStream.LA(1); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Generic_argumentContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { + return GetRuleContext(0); + } + public Generic_argumentContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_generic_argument; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterGeneric_argument(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitGeneric_argument(this); + } + } + + [RuleVersion(0)] + public Generic_argumentContext generic_argument() { + Generic_argumentContext _localctx = new Generic_argumentContext(Context, State); + EnterRule(_localctx, 300, RULE_generic_argument); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1485; + type(0); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class OpGreaterContext : ParserRuleContext { + public OpGreaterContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_opGreater; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOpGreater(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOpGreater(this); + } + } + + [RuleVersion(0)] + public OpGreaterContext opGreater() { + OpGreaterContext _localctx = new OpGreaterContext(Context, State); + EnterRule(_localctx, 302, RULE_opGreater); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1487; + Match(T__64); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Arrow_operatorContext : ParserRuleContext { + public Arrow_operatorContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_arrow_operator; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterArrow_operator(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitArrow_operator(this); + } + } + + [RuleVersion(0)] + public Arrow_operatorContext arrow_operator() { + Arrow_operatorContext _localctx = new Arrow_operatorContext(Context, State); + EnterRule(_localctx, 304, RULE_arrow_operator); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1489; + Match(T__65); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Range_operatorContext : ParserRuleContext { + public Range_operatorContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_range_operator; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterRange_operator(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitRange_operator(this); + } + } + + [RuleVersion(0)] + public Range_operatorContext range_operator() { + Range_operatorContext _localctx = new Range_operatorContext(Context, State); + EnterRule(_localctx, 306, RULE_range_operator); + try { + EnterOuterAlt(_localctx, 1); + { + State = 1491; + Match(T__66); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Keyword_as_identifier_in_declarationsContext : ParserRuleContext { + public Keyword_as_identifier_in_declarationsContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_keyword_as_identifier_in_declarations; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterKeyword_as_identifier_in_declarations(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitKeyword_as_identifier_in_declarations(this); + } + } + + [RuleVersion(0)] + public Keyword_as_identifier_in_declarationsContext keyword_as_identifier_in_declarations() { + Keyword_as_identifier_in_declarationsContext _localctx = new Keyword_as_identifier_in_declarationsContext(Context, State); + EnterRule(_localctx, 308, RULE_keyword_as_identifier_in_declarations); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1493; + _la = TokenStream.LA(1); + if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__54) | (1L << T__55))) != 0) || ((((_la - 68)) & ~0x3f) == 0 && ((1L << (_la - 68)) & ((1L << (T__67 - 68)) | (1L << (T__68 - 68)) | (1L << (T__69 - 68)) | (1L << (T__70 - 68)) | (1L << (T__71 - 68)) | (1L << (T__72 - 68)) | (1L << (T__73 - 68)) | (1L << (T__74 - 68)) | (1L << (T__75 - 68)) | (1L << (T__76 - 68)) | (1L << (T__77 - 68)) | (1L << (T__78 - 68)) | (1L << (T__79 - 68)) | (1L << (T__80 - 68)) | (1L << (T__81 - 68)) | (1L << (T__82 - 68)) | (1L << (T__83 - 68)) | (1L << (T__84 - 68)) | (1L << (T__85 - 68)) | (1L << (T__86 - 68)) | (1L << (T__87 - 68)) | (1L << (T__88 - 68)) | (1L << (T__89 - 68)) | (1L << (T__90 - 68)) | (1L << (T__91 - 68)))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Keyword_as_identifier_in_labelsContext : ParserRuleContext { + public Keyword_as_identifier_in_labelsContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_keyword_as_identifier_in_labels; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterKeyword_as_identifier_in_labels(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitKeyword_as_identifier_in_labels(this); + } + } + + [RuleVersion(0)] + public Keyword_as_identifier_in_labelsContext keyword_as_identifier_in_labels() { + Keyword_as_identifier_in_labelsContext _localctx = new Keyword_as_identifier_in_labelsContext(Context, State); + EnterRule(_localctx, 310, RULE_keyword_as_identifier_in_labels); + int _la; + try { + EnterOuterAlt(_localctx, 1); + { + State = 1495; + _la = TokenStream.LA(1); + if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)))) != 0)) ) { + ErrorHandler.RecoverInline(this); + } + else { + ErrorHandler.ReportMatch(this); + Consume(); + } + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class OperatorContext : ParserRuleContext { + [System.Diagnostics.DebuggerNonUserCode] public Operator_anglesContext operator_angles() { + return GetRuleContext(0); + } + [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Operator() { return GetToken(SwiftInterfaceParser.Operator, 0); } + public OperatorContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_operator; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOperator(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOperator(this); + } + } + + [RuleVersion(0)] + public OperatorContext @operator() { + OperatorContext _localctx = new OperatorContext(Context, State); + EnterRule(_localctx, 312, RULE_operator); + try { + State = 1499; + ErrorHandler.Sync(this); + switch (TokenStream.LA(1)) { + case T__64: + EnterOuterAlt(_localctx, 1); + { + State = 1497; + operator_angles(); + } + break; + case Operator: + EnterOuterAlt(_localctx, 2); + { + State = 1498; + Match(Operator); + } + break; + default: + throw new NoViableAltException(this); + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public partial class Operator_anglesContext : ParserRuleContext { + public Operator_anglesContext(ParserRuleContext parent, int invokingState) + : base(parent, invokingState) + { + } + public override int RuleIndex { get { return RULE_operator_angles; } } + [System.Diagnostics.DebuggerNonUserCode] + public override void EnterRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.EnterOperator_angles(this); + } + [System.Diagnostics.DebuggerNonUserCode] + public override void ExitRule(IParseTreeListener listener) { + ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; + if (typedListener != null) typedListener.ExitOperator_angles(this); + } + } + + [RuleVersion(0)] + public Operator_anglesContext operator_angles() { + Operator_anglesContext _localctx = new Operator_anglesContext(Context, State); + EnterRule(_localctx, 314, RULE_operator_angles); + try { + State = 1533; + ErrorHandler.Sync(this); + switch ( Interpreter.AdaptivePredict(TokenStream,188,Context) ) { + case 1: + EnterOuterAlt(_localctx, 1); + { + State = 1501; + Match(T__64); + } + break; + case 2: + EnterOuterAlt(_localctx, 2); + { + State = 1502; + Match(T__64); + State = 1503; + Match(T__64); + } + break; + case 3: + EnterOuterAlt(_localctx, 3); + { + State = 1504; + Match(T__64); + State = 1505; + Match(T__64); + State = 1506; + Match(T__64); + } + break; + case 4: + EnterOuterAlt(_localctx, 4); + { + State = 1507; + Match(T__64); + State = 1508; + Match(T__64); + State = 1509; + Match(T__64); + State = 1510; + Match(T__64); + State = 1511; + Match(T__64); + } + break; + case 5: + EnterOuterAlt(_localctx, 5); + { + State = 1512; + Match(T__64); + State = 1513; + Match(T__64); + State = 1514; + Match(T__64); + State = 1515; + Match(T__64); + State = 1516; + Match(T__64); + State = 1517; + Match(T__64); + } + break; + case 6: + EnterOuterAlt(_localctx, 6); + { + State = 1518; + Match(T__64); + State = 1519; + Match(T__64); + State = 1520; + Match(T__64); + State = 1521; + Match(T__64); + State = 1522; + Match(T__64); + State = 1523; + Match(T__64); + State = 1524; + Match(T__64); + } + break; + case 7: + EnterOuterAlt(_localctx, 7); + { + State = 1525; + Match(T__64); + State = 1526; + Match(T__64); + State = 1527; + Match(T__64); + State = 1528; + Match(T__64); + State = 1529; + Match(T__64); + State = 1530; + Match(T__64); + State = 1531; + Match(T__64); + State = 1532; + Match(T__64); + } + break; + } + } + catch (RecognitionException re) { + _localctx.exception = re; + ErrorHandler.ReportError(this, re); + ErrorHandler.Recover(this, re); + } + finally { + ExitRule(); + } + return _localctx; + } + + public override bool Sempred(RuleContext _localctx, int ruleIndex, int predIndex) { + switch (ruleIndex) { + case 111: return pattern_sempred((PatternContext)_localctx, predIndex); + case 119: return type_sempred((TypeContext)_localctx, predIndex); + } + return true; + } + private bool pattern_sempred(PatternContext _localctx, int predIndex) { + switch (predIndex) { + case 0: return Precpred(Context, 1); + } + return true; + } + private bool type_sempred(TypeContext _localctx, int predIndex) { + switch (predIndex) { + case 1: return Precpred(Context, 9); + case 2: return Precpred(Context, 8); + case 3: return Precpred(Context, 6); + case 4: return Precpred(Context, 5); + } + return true; + } + + private static char[] _serializedATN = { + '\x3', '\x608B', '\xA72A', '\x8133', '\xB9ED', '\x417C', '\x3BE7', '\x7786', + '\x5964', '\x3', '\x98', '\x602', '\x4', '\x2', '\t', '\x2', '\x4', '\x3', + '\t', '\x3', '\x4', '\x4', '\t', '\x4', '\x4', '\x5', '\t', '\x5', '\x4', + '\x6', '\t', '\x6', '\x4', '\a', '\t', '\a', '\x4', '\b', '\t', '\b', + '\x4', '\t', '\t', '\t', '\x4', '\n', '\t', '\n', '\x4', '\v', '\t', '\v', + '\x4', '\f', '\t', '\f', '\x4', '\r', '\t', '\r', '\x4', '\xE', '\t', + '\xE', '\x4', '\xF', '\t', '\xF', '\x4', '\x10', '\t', '\x10', '\x4', + '\x11', '\t', '\x11', '\x4', '\x12', '\t', '\x12', '\x4', '\x13', '\t', + '\x13', '\x4', '\x14', '\t', '\x14', '\x4', '\x15', '\t', '\x15', '\x4', + '\x16', '\t', '\x16', '\x4', '\x17', '\t', '\x17', '\x4', '\x18', '\t', + '\x18', '\x4', '\x19', '\t', '\x19', '\x4', '\x1A', '\t', '\x1A', '\x4', + '\x1B', '\t', '\x1B', '\x4', '\x1C', '\t', '\x1C', '\x4', '\x1D', '\t', + '\x1D', '\x4', '\x1E', '\t', '\x1E', '\x4', '\x1F', '\t', '\x1F', '\x4', + ' ', '\t', ' ', '\x4', '!', '\t', '!', '\x4', '\"', '\t', '\"', '\x4', + '#', '\t', '#', '\x4', '$', '\t', '$', '\x4', '%', '\t', '%', '\x4', '&', + '\t', '&', '\x4', '\'', '\t', '\'', '\x4', '(', '\t', '(', '\x4', ')', + '\t', ')', '\x4', '*', '\t', '*', '\x4', '+', '\t', '+', '\x4', ',', '\t', + ',', '\x4', '-', '\t', '-', '\x4', '.', '\t', '.', '\x4', '/', '\t', '/', + '\x4', '\x30', '\t', '\x30', '\x4', '\x31', '\t', '\x31', '\x4', '\x32', + '\t', '\x32', '\x4', '\x33', '\t', '\x33', '\x4', '\x34', '\t', '\x34', + '\x4', '\x35', '\t', '\x35', '\x4', '\x36', '\t', '\x36', '\x4', '\x37', + '\t', '\x37', '\x4', '\x38', '\t', '\x38', '\x4', '\x39', '\t', '\x39', + '\x4', ':', '\t', ':', '\x4', ';', '\t', ';', '\x4', '<', '\t', '<', '\x4', + '=', '\t', '=', '\x4', '>', '\t', '>', '\x4', '?', '\t', '?', '\x4', '@', + '\t', '@', '\x4', '\x41', '\t', '\x41', '\x4', '\x42', '\t', '\x42', '\x4', + '\x43', '\t', '\x43', '\x4', '\x44', '\t', '\x44', '\x4', '\x45', '\t', + '\x45', '\x4', '\x46', '\t', '\x46', '\x4', 'G', '\t', 'G', '\x4', 'H', + '\t', 'H', '\x4', 'I', '\t', 'I', '\x4', 'J', '\t', 'J', '\x4', 'K', '\t', + 'K', '\x4', 'L', '\t', 'L', '\x4', 'M', '\t', 'M', '\x4', 'N', '\t', 'N', + '\x4', 'O', '\t', 'O', '\x4', 'P', '\t', 'P', '\x4', 'Q', '\t', 'Q', '\x4', + 'R', '\t', 'R', '\x4', 'S', '\t', 'S', '\x4', 'T', '\t', 'T', '\x4', 'U', + '\t', 'U', '\x4', 'V', '\t', 'V', '\x4', 'W', '\t', 'W', '\x4', 'X', '\t', + 'X', '\x4', 'Y', '\t', 'Y', '\x4', 'Z', '\t', 'Z', '\x4', '[', '\t', '[', + '\x4', '\\', '\t', '\\', '\x4', ']', '\t', ']', '\x4', '^', '\t', '^', + '\x4', '_', '\t', '_', '\x4', '`', '\t', '`', '\x4', '\x61', '\t', '\x61', + '\x4', '\x62', '\t', '\x62', '\x4', '\x63', '\t', '\x63', '\x4', '\x64', + '\t', '\x64', '\x4', '\x65', '\t', '\x65', '\x4', '\x66', '\t', '\x66', + '\x4', 'g', '\t', 'g', '\x4', 'h', '\t', 'h', '\x4', 'i', '\t', 'i', '\x4', + 'j', '\t', 'j', '\x4', 'k', '\t', 'k', '\x4', 'l', '\t', 'l', '\x4', 'm', + '\t', 'm', '\x4', 'n', '\t', 'n', '\x4', 'o', '\t', 'o', '\x4', 'p', '\t', + 'p', '\x4', 'q', '\t', 'q', '\x4', 'r', '\t', 'r', '\x4', 's', '\t', 's', + '\x4', 't', '\t', 't', '\x4', 'u', '\t', 'u', '\x4', 'v', '\t', 'v', '\x4', + 'w', '\t', 'w', '\x4', 'x', '\t', 'x', '\x4', 'y', '\t', 'y', '\x4', 'z', + '\t', 'z', '\x4', '{', '\t', '{', '\x4', '|', '\t', '|', '\x4', '}', '\t', + '}', '\x4', '~', '\t', '~', '\x4', '\x7F', '\t', '\x7F', '\x4', '\x80', + '\t', '\x80', '\x4', '\x81', '\t', '\x81', '\x4', '\x82', '\t', '\x82', + '\x4', '\x83', '\t', '\x83', '\x4', '\x84', '\t', '\x84', '\x4', '\x85', + '\t', '\x85', '\x4', '\x86', '\t', '\x86', '\x4', '\x87', '\t', '\x87', + '\x4', '\x88', '\t', '\x88', '\x4', '\x89', '\t', '\x89', '\x4', '\x8A', + '\t', '\x8A', '\x4', '\x8B', '\t', '\x8B', '\x4', '\x8C', '\t', '\x8C', + '\x4', '\x8D', '\t', '\x8D', '\x4', '\x8E', '\t', '\x8E', '\x4', '\x8F', + '\t', '\x8F', '\x4', '\x90', '\t', '\x90', '\x4', '\x91', '\t', '\x91', + '\x4', '\x92', '\t', '\x92', '\x4', '\x93', '\t', '\x93', '\x4', '\x94', + '\t', '\x94', '\x4', '\x95', '\t', '\x95', '\x4', '\x96', '\t', '\x96', + '\x4', '\x97', '\t', '\x97', '\x4', '\x98', '\t', '\x98', '\x4', '\x99', + '\t', '\x99', '\x4', '\x9A', '\t', '\x9A', '\x4', '\x9B', '\t', '\x9B', + '\x4', '\x9C', '\t', '\x9C', '\x4', '\x9D', '\t', '\x9D', '\x4', '\x9E', + '\t', '\x9E', '\x4', '\x9F', '\t', '\x9F', '\x3', '\x2', '\a', '\x2', + '\x140', '\n', '\x2', '\f', '\x2', '\xE', '\x2', '\x143', '\v', '\x2', + '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x5', '\x3', '\x148', '\n', + '\x3', '\x3', '\x4', '\x3', '\x4', '\x3', '\x5', '\x3', '\x5', '\x3', + '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', + '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x5', '\x5', '\x157', + '\n', '\x5', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', + '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', + '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x5', '\x6', '\x166', + '\n', '\x6', '\x3', '\a', '\x5', '\a', '\x169', '\n', '\a', '\x3', '\a', + '\x3', '\a', '\x5', '\a', '\x16D', '\n', '\a', '\x3', '\a', '\x3', '\a', + '\x3', '\b', '\x3', '\b', '\x3', '\t', '\x3', '\t', '\x3', '\t', '\a', + '\t', '\x176', '\n', '\t', '\f', '\t', '\xE', '\t', '\x179', '\v', '\t', + '\x3', '\n', '\x3', '\n', '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', + '\v', '\a', '\v', '\x181', '\n', '\v', '\f', '\v', '\xE', '\v', '\x184', + '\v', '\v', '\x3', '\f', '\x5', '\f', '\x187', '\n', '\f', '\x3', '\f', + '\x5', '\f', '\x18A', '\n', '\f', '\x3', '\f', '\x3', '\f', '\x5', '\f', + '\x18E', '\n', '\f', '\x3', '\f', '\x5', '\f', '\x191', '\n', '\f', '\x3', + '\f', '\x5', '\f', '\x194', '\n', '\f', '\x3', '\r', '\x3', '\r', '\x3', + '\r', '\x5', '\r', '\x199', '\n', '\r', '\x3', '\r', '\x3', '\r', '\x3', + '\r', '\x5', '\r', '\x19E', '\n', '\r', '\x5', '\r', '\x1A0', '\n', '\r', + '\x3', '\xE', '\x3', '\xE', '\x3', '\xF', '\x3', '\xF', '\x3', '\x10', + '\x3', '\x10', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', + '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', + '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', + '\x5', '\x11', '\x1B6', '\n', '\x11', '\x3', '\x12', '\x5', '\x12', '\x1B9', + '\n', '\x12', '\x3', '\x12', '\x5', '\x12', '\x1BC', '\n', '\x12', '\x3', + '\x12', '\x3', '\x12', '\x5', '\x12', '\x1C0', '\n', '\x12', '\x3', '\x13', + '\x5', '\x13', '\x1C3', '\n', '\x13', '\x3', '\x13', '\x5', '\x13', '\x1C6', + '\n', '\x13', '\x3', '\x13', '\x3', '\x13', '\x5', '\x13', '\x1CA', '\n', + '\x13', '\x3', '\x13', '\x5', '\x13', '\x1CD', '\n', '\x13', '\x3', '\x13', + '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x5', '\x13', + '\x1D4', '\n', '\x13', '\x3', '\x14', '\x3', '\x14', '\x3', '\x15', '\x5', + '\x15', '\x1D9', '\n', '\x15', '\x3', '\x15', '\x5', '\x15', '\x1DC', + '\n', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x5', '\x15', + '\x1E1', '\n', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x16', '\x3', + '\x16', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x18', '\x5', + '\x18', '\x1EB', '\n', '\x18', '\x3', '\x18', '\x5', '\x18', '\x1EE', + '\n', '\x18', '\x3', '\x18', '\x3', '\x18', '\x5', '\x18', '\x1F2', '\n', + '\x18', '\x3', '\x18', '\x5', '\x18', '\x1F5', '\n', '\x18', '\x3', '\x18', + '\x5', '\x18', '\x1F8', '\n', '\x18', '\x3', '\x19', '\x5', '\x19', '\x1FB', + '\n', '\x19', '\x3', '\x19', '\x3', '\x19', '\x3', '\x19', '\x5', '\x19', + '\x200', '\n', '\x19', '\x3', '\x19', '\x5', '\x19', '\x203', '\n', '\x19', + '\x3', '\x19', '\x5', '\x19', '\x206', '\n', '\x19', '\x3', '\x19', '\x3', + '\x19', '\x5', '\x19', '\x20A', '\n', '\x19', '\x3', '\x19', '\x3', '\x19', + '\x3', '\x1A', '\x3', '\x1A', '\x5', '\x1A', '\x210', '\n', '\x1A', '\x3', + '\x1B', '\x3', '\x1B', '\x5', '\x1B', '\x214', '\n', '\x1B', '\x3', '\x1C', + '\x5', '\x1C', '\x217', '\n', '\x1C', '\x3', '\x1C', '\x5', '\x1C', '\x21A', + '\n', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1D', + '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x5', '\x1D', + '\x224', '\n', '\x1D', '\x3', '\x1E', '\x3', '\x1E', '\x5', '\x1E', '\x228', + '\n', '\x1E', '\x3', '\x1F', '\x3', '\x1F', '\x3', ' ', '\x3', ' ', '\x3', + '!', '\x3', '!', '\x3', '!', '\x5', '!', '\x231', '\n', '!', '\x3', '!', + '\x3', '!', '\x5', '!', '\x235', '\n', '!', '\x3', '!', '\x3', '!', '\x3', + '!', '\x3', '!', '\x3', '\"', '\x3', '\"', '\x5', '\"', '\x23D', '\n', + '\"', '\x3', '#', '\x3', '#', '\x5', '#', '\x241', '\n', '#', '\x3', '$', + '\x5', '$', '\x244', '\n', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', + '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x5', '%', '\x24E', + '\n', '%', '\x3', '&', '\x3', '&', '\x5', '&', '\x252', '\n', '&', '\x3', + '\'', '\x3', '\'', '\x3', '\'', '\x3', '(', '\x3', '(', '\x3', '(', '\x5', + '(', '\x25A', '\n', '(', '\x3', ')', '\x5', ')', '\x25D', '\n', ')', '\x3', + ')', '\x5', ')', '\x260', '\n', ')', '\x3', ')', '\x3', ')', '\x3', ')', + '\x5', ')', '\x265', '\n', ')', '\x3', ')', '\x5', ')', '\x268', '\n', + ')', '\x3', ')', '\x5', ')', '\x26B', '\n', ')', '\x3', ')', '\x3', ')', + '\x3', '*', '\x3', '*', '\x3', '+', '\x3', '+', '\a', '+', '\x273', '\n', + '+', '\f', '+', '\xE', '+', '\x276', '\v', '+', '\x3', '+', '\x3', '+', + '\x3', ',', '\x3', ',', '\x3', '-', '\x5', '-', '\x27D', '\n', '-', '\x3', + '-', '\x5', '-', '\x280', '\n', '-', '\x3', '-', '\x5', '-', '\x283', + '\n', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x288', '\n', + '-', '\x3', '-', '\x5', '-', '\x28B', '\n', '-', '\x3', '-', '\x5', '-', + '\x28E', '\n', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x293', + '\n', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x297', '\n', '-', '\x3', + '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x29C', '\n', '-', '\x3', '-', + '\x5', '-', '\x29F', '\n', '-', '\x3', '-', '\x5', '-', '\x2A2', '\n', + '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x2A6', '\n', '-', '\x3', '.', + '\x3', '.', '\x3', '/', '\x3', '/', '\a', '/', '\x2AC', '\n', '/', '\f', + '/', '\xE', '/', '\x2AF', '\v', '/', '\x3', '/', '\x3', '/', '\x3', '\x30', + '\x3', '\x30', '\x3', '\x31', '\x3', '\x31', '\x3', '\x32', '\x5', '\x32', + '\x2B8', '\n', '\x32', '\x3', '\x32', '\x5', '\x32', '\x2BB', '\n', '\x32', + '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x5', '\x32', '\x2C0', '\n', + '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x33', '\x3', '\x33', '\x3', + '\x34', '\x3', '\x34', '\a', '\x34', '\x2C8', '\n', '\x34', '\f', '\x34', + '\xE', '\x34', '\x2CB', '\v', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', + '\x35', '\x3', '\x35', '\x3', '\x36', '\x3', '\x36', '\x3', '\x36', '\x3', + '\x36', '\x3', '\x36', '\x3', '\x36', '\x5', '\x36', '\x2D7', '\n', '\x36', + '\x3', '\x37', '\x3', '\x37', '\x3', '\x37', '\x5', '\x37', '\x2DC', '\n', + '\x37', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', + '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', ':', '\x3', + ':', '\x3', ':', '\x3', ':', '\x5', ':', '\x2EA', '\n', ':', '\x3', ';', + '\x3', ';', '\x3', ';', '\x3', '<', '\x3', '<', '\x3', '<', '\x3', '<', + '\a', '<', '\x2F3', '\n', '<', '\f', '<', '\xE', '<', '\x2F6', '\v', '<', + '\x3', '<', '\x3', '<', '\x3', '=', '\x3', '=', '\x3', '=', '\x5', '=', + '\x2FD', '\n', '=', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', + '>', '\x3', '>', '\x5', '>', '\x305', '\n', '>', '\x3', '?', '\x3', '?', + '\x3', '?', '\x3', '?', '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '@', + '\x3', '\x41', '\x3', '\x41', '\x3', '\x42', '\x3', '\x42', '\x3', '\x42', + '\a', '\x42', '\x314', '\n', '\x42', '\f', '\x42', '\xE', '\x42', '\x317', + '\v', '\x42', '\x3', '\x43', '\x3', '\x43', '\x3', '\x44', '\x5', '\x44', + '\x31C', '\n', '\x44', '\x3', '\x44', '\x5', '\x44', '\x31F', '\n', '\x44', + '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', '\x44', '\x324', '\n', + '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', '\x44', '\x329', + '\n', '\x44', '\x3', '\x44', '\x5', '\x44', '\x32C', '\n', '\x44', '\x3', + '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', + '\x44', '\x333', '\n', '\x44', '\x3', '\x45', '\x3', '\x45', '\a', '\x45', + '\x337', '\n', '\x45', '\f', '\x45', '\xE', '\x45', '\x33A', '\v', '\x45', + '\x3', '\x45', '\x3', '\x45', '\x3', '\x46', '\x3', '\x46', '\x3', 'G', + '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', + '\x5', 'G', '\x347', '\n', 'G', '\x3', 'H', '\x5', 'H', '\x34A', '\n', + 'H', '\x3', 'H', '\x5', 'H', '\x34D', '\n', 'H', '\x3', 'H', '\x3', 'H', + '\x3', 'H', '\x3', 'I', '\x3', 'I', '\x5', 'I', '\x354', '\n', 'I', '\x3', + 'I', '\x3', 'I', '\x3', 'J', '\x5', 'J', '\x359', '\n', 'J', '\x3', 'J', + '\x5', 'J', '\x35C', '\n', 'J', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x5', + 'J', '\x361', '\n', 'J', '\x3', 'J', '\x5', 'J', '\x364', '\n', 'J', '\x3', + 'J', '\x5', 'J', '\x367', '\n', 'J', '\x3', 'K', '\x3', 'K', '\x3', 'K', + '\x5', 'K', '\x36C', '\n', 'K', '\x3', 'K', '\x3', 'K', '\x5', 'K', '\x370', + '\n', 'K', '\x3', 'K', '\x5', 'K', '\x373', '\n', 'K', '\x3', 'L', '\x5', + 'L', '\x376', '\n', 'L', '\x3', 'L', '\x5', 'L', '\x379', '\n', 'L', '\x3', + 'L', '\x3', 'L', '\x3', 'M', '\x3', 'M', '\x5', 'M', '\x37F', '\n', 'M', + '\x3', 'N', '\x3', 'N', '\a', 'N', '\x383', '\n', 'N', '\f', 'N', '\xE', + 'N', '\x386', '\v', 'N', '\x3', 'N', '\x3', 'N', '\x3', 'O', '\x3', 'O', + '\x3', 'P', '\x3', 'P', '\x5', 'P', '\x38E', '\n', 'P', '\x3', 'P', '\x5', + 'P', '\x391', '\n', 'P', '\x3', 'P', '\x5', 'P', '\x394', '\n', 'P', '\x3', + 'P', '\x3', 'P', '\x5', 'P', '\x398', '\n', 'P', '\x3', 'P', '\x3', 'P', + '\x5', 'P', '\x39C', '\n', 'P', '\x5', 'P', '\x39E', '\n', 'P', '\x3', + 'Q', '\x3', 'Q', '\x3', 'R', '\x3', 'R', '\x3', 'S', '\x3', 'S', '\x3', + 'T', '\x3', 'T', '\x5', 'T', '\x3A8', '\n', 'T', '\x3', 'T', '\x3', 'T', + '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3AE', '\n', 'U', '\x3', 'U', '\x3', + 'U', '\x5', 'U', '\x3B2', '\n', 'U', '\x3', 'U', '\x5', 'U', '\x3B5', + '\n', 'U', '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3B9', '\n', 'U', '\x3', + 'U', '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3BE', '\n', 'U', '\x5', 'U', + '\x3C0', '\n', 'U', '\x3', 'V', '\x5', 'V', '\x3C3', '\n', 'V', '\x3', + 'V', '\x5', 'V', '\x3C6', '\n', 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', + '\x3CA', '\n', 'V', '\x3', 'V', '\x5', 'V', '\x3CD', '\n', 'V', '\x3', + 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', '\x3D2', '\n', 'V', '\x3', 'V', + '\x5', 'V', '\x3D5', '\n', 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', '\x3D9', + '\n', 'V', '\x3', 'W', '\x5', 'W', '\x3DC', '\n', 'W', '\x3', 'W', '\x5', + 'W', '\x3DF', '\n', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'X', '\x3', 'X', + '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x5', 'X', '\x3E9', '\n', + 'X', '\x3', 'Y', '\x3', 'Y', '\x3', 'Y', '\a', 'Y', '\x3EE', '\n', 'Y', + '\f', 'Y', '\xE', 'Y', '\x3F1', '\v', 'Y', '\x3', 'Z', '\x5', 'Z', '\x3F4', + '\n', 'Z', '\x3', 'Z', '\x3', 'Z', '\x3', 'Z', '\x5', 'Z', '\x3F9', '\n', + 'Z', '\x3', 'Z', '\x5', 'Z', '\x3FC', '\n', 'Z', '\x3', 'Z', '\x3', 'Z', + '\x3', 'Z', '\x3', 'Z', '\x5', 'Z', '\x402', '\n', 'Z', '\x3', '[', '\x3', + '[', '\x3', '\\', '\x3', '\\', '\x3', ']', '\x3', ']', '\x6', ']', '\x40A', + '\n', ']', '\r', ']', '\xE', ']', '\x40B', '\x3', '^', '\x3', '^', '\a', + '^', '\x410', '\n', '^', '\f', '^', '\xE', '^', '\x413', '\v', '^', '\x3', + '^', '\x3', '^', '\x3', '^', '\a', '^', '\x418', '\n', '^', '\f', '^', + '\xE', '^', '\x41B', '\v', '^', '\x3', '^', '\x3', '^', '\x3', '^', '\a', + '^', '\x420', '\n', '^', '\f', '^', '\xE', '^', '\x423', '\v', '^', '\x3', + '^', '\x3', '^', '\x3', '^', '\x3', '^', '\x3', '^', '\x5', '^', '\x42A', + '\n', '^', '\x3', '_', '\x3', '_', '\x5', '_', '\x42E', '\n', '_', '\x3', + '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', + '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', + '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x5', '`', '\x441', + '\n', '`', '\x3', '`', '\x5', '`', '\x444', '\n', '`', '\x3', '\x61', + '\x3', '\x61', '\x3', '\x61', '\x3', '\x62', '\x3', '\x62', '\x5', '\x62', + '\x44B', '\n', '\x62', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', + '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', + '\x63', '\x5', '\x63', '\x456', '\n', '\x63', '\x3', '\x64', '\x3', '\x64', + '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', '\x5', '\x64', '\x45D', '\n', + '\x64', '\x3', '\x65', '\x3', '\x65', '\x3', '\x66', '\x3', '\x66', '\x3', + '\x66', '\x5', '\x66', '\x464', '\n', '\x66', '\x3', 'g', '\x3', 'g', + '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', 'i', '\x6', 'i', + '\x46D', '\n', 'i', '\r', 'i', '\xE', 'i', '\x46E', '\x3', 'j', '\a', + 'j', '\x472', '\n', 'j', '\f', 'j', '\xE', 'j', '\x475', '\v', 'j', '\x3', + 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', + 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', + 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x5', 'k', '\x487', '\n', 'k', + '\x3', 'l', '\x3', 'l', '\x5', 'l', '\x48B', '\n', 'l', '\x3', 'm', '\x3', + 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', + 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', + 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', + 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x5', 'm', '\x4A5', + '\n', 'm', '\x3', 'n', '\x6', 'n', '\x4A8', '\n', 'n', '\r', 'n', '\xE', + 'n', '\x4A9', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', + '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', + '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', + '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', + '\x3', 'o', '\x3', 'o', '\x5', 'o', '\x4C5', '\n', 'o', '\x3', 'p', '\x3', + 'p', '\x3', 'q', '\x3', 'q', '\x3', 'q', '\x5', 'q', '\x4CC', '\n', 'q', + '\x3', 'q', '\x3', 'q', '\x5', 'q', '\x4D0', '\n', 'q', '\x3', 'q', '\x3', + 'q', '\x5', 'q', '\x4D4', '\n', 'q', '\x3', 'q', '\x3', 'q', '\x3', 'q', + '\a', 'q', '\x4D9', '\n', 'q', '\f', 'q', '\xE', 'q', '\x4DC', '\v', 'q', + '\x3', 'r', '\x3', 'r', '\x3', 's', '\x3', 's', '\x3', 't', '\x5', 't', + '\x4E3', '\n', 't', '\x3', 't', '\x3', 't', '\x5', 't', '\x4E7', '\n', + 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x5', 't', '\x4ED', + '\n', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', + '\x5', 't', '\x4F4', '\n', 't', '\x3', 'u', '\x3', 'u', '\x3', 'u', '\x3', + 'u', '\x3', 'u', '\x5', 'u', '\x4FB', '\n', 'u', '\x3', 'u', '\x3', 'u', + '\x5', 'u', '\x4FF', '\n', 'u', '\x3', 'v', '\x3', 'v', '\x3', 'v', '\x3', + 'v', '\x3', 'v', '\x5', 'v', '\x506', '\n', 'v', '\x3', 'w', '\x5', 'w', + '\x509', '\n', 'w', '\x3', 'w', '\x5', 'w', '\x50C', '\n', 'w', '\x3', + 'w', '\x3', 'w', '\x3', 'w', '\x3', 'w', '\x5', 'w', '\x512', '\n', 'w', + '\x3', 'x', '\x3', 'x', '\x3', 'x', '\x3', 'x', '\x5', 'x', '\x518', '\n', + 'x', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', + 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', + 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x5', 'y', '\x529', '\n', 'y', + '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', + '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\a', 'y', '\x535', '\n', + 'y', '\f', 'y', '\xE', 'y', '\x538', '\v', 'y', '\x3', 'z', '\x3', 'z', + '\x5', 'z', '\x53C', '\n', 'z', '\x3', 'z', '\x5', 'z', '\x53F', '\n', + 'z', '\x3', 'z', '\x3', 'z', '\x3', '{', '\x3', '{', '\x3', '|', '\x3', + '|', '\x3', '}', '\x3', '}', '\x5', '}', '\x549', '\n', '}', '\x3', '}', + '\x3', '}', '\x5', '}', '\x54D', '\n', '}', '\x3', '~', '\x3', '~', '\x3', + '\x7F', '\x3', '\x7F', '\x5', '\x7F', '\x553', '\n', '\x7F', '\x3', '\x7F', + '\x3', '\x7F', '\x3', '\x80', '\x3', '\x80', '\x3', '\x80', '\x3', '\x80', + '\x3', '\x80', '\x5', '\x80', '\x55C', '\n', '\x80', '\x3', '\x81', '\x3', + '\x81', '\x3', '\x81', '\x3', '\x81', '\x5', '\x81', '\x562', '\n', '\x81', + '\x3', '\x82', '\x3', '\x82', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', + '\x3', '\x83', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', + '\x3', '\x84', '\x3', '\x84', '\x3', '\x85', '\x3', '\x85', '\x3', '\x85', + '\x6', '\x85', '\x573', '\n', '\x85', '\r', '\x85', '\xE', '\x85', '\x574', + '\x3', '\x86', '\x3', '\x86', '\x3', '\x87', '\x3', '\x87', '\x3', '\x87', + '\x3', '\x87', '\x5', '\x87', '\x57D', '\n', '\x87', '\x3', '\x88', '\x3', + '\x88', '\x3', '\x89', '\x3', '\x89', '\x3', '\x8A', '\x5', '\x8A', '\x584', + '\n', '\x8A', '\x3', '\x8A', '\x3', '\x8A', '\x3', '\x8B', '\x3', '\x8B', + '\x3', '\x8C', '\x3', '\x8C', '\x3', '\x8D', '\x3', '\x8D', '\x5', '\x8D', + '\x58E', '\n', '\x8D', '\x3', '\x8E', '\x3', '\x8E', '\x3', '\x8E', '\x3', + '\x8E', '\x3', '\x8F', '\x3', '\x8F', '\x3', '\x8F', '\a', '\x8F', '\x597', + '\n', '\x8F', '\f', '\x8F', '\xE', '\x8F', '\x59A', '\v', '\x8F', '\x3', + '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', + '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x5', '\x90', '\x5A5', + '\n', '\x90', '\x3', '\x91', '\x3', '\x91', '\x3', '\x91', '\x3', '\x92', + '\x3', '\x92', '\x3', '\x92', '\a', '\x92', '\x5AD', '\n', '\x92', '\f', + '\x92', '\xE', '\x92', '\x5B0', '\v', '\x92', '\x3', '\x93', '\x3', '\x93', + '\x5', '\x93', '\x5B4', '\n', '\x93', '\x3', '\x94', '\x3', '\x94', '\x3', + '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', + '\x94', '\x5', '\x94', '\x5BE', '\n', '\x94', '\x3', '\x95', '\x3', '\x95', + '\x3', '\x95', '\x3', '\x95', '\x3', '\x96', '\x3', '\x96', '\x3', '\x96', + '\x3', '\x96', '\x3', '\x97', '\x3', '\x97', '\x3', '\x97', '\a', '\x97', + '\x5CB', '\n', '\x97', '\f', '\x97', '\xE', '\x97', '\x5CE', '\v', '\x97', + '\x3', '\x98', '\x3', '\x98', '\x3', '\x99', '\x3', '\x99', '\x3', '\x9A', + '\x3', '\x9A', '\x3', '\x9B', '\x3', '\x9B', '\x3', '\x9C', '\x3', '\x9C', + '\x3', '\x9D', '\x3', '\x9D', '\x3', '\x9E', '\x3', '\x9E', '\x5', '\x9E', + '\x5DE', '\n', '\x9E', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', + '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x5', '\x9F', '\x600', + '\n', '\x9F', '\x3', '\x9F', '\x2', '\x4', '\xE0', '\xF0', '\xA0', '\x2', + '\x4', '\x6', '\b', '\n', '\f', '\xE', '\x10', '\x12', '\x14', '\x16', + '\x18', '\x1A', '\x1C', '\x1E', ' ', '\"', '$', '&', '(', '*', ',', '.', + '\x30', '\x32', '\x34', '\x36', '\x38', ':', '<', '>', '@', '\x42', '\x44', + '\x46', 'H', 'J', 'L', 'N', 'P', 'R', 'T', 'V', 'X', 'Z', '\\', '^', '`', + '\x62', '\x64', '\x66', 'h', 'j', 'l', 'n', 'p', 'r', 't', 'v', 'x', 'z', + '|', '~', '\x80', '\x82', '\x84', '\x86', '\x88', '\x8A', '\x8C', '\x8E', + '\x90', '\x92', '\x94', '\x96', '\x98', '\x9A', '\x9C', '\x9E', '\xA0', + '\xA2', '\xA4', '\xA6', '\xA8', '\xAA', '\xAC', '\xAE', '\xB0', '\xB2', + '\xB4', '\xB6', '\xB8', '\xBA', '\xBC', '\xBE', '\xC0', '\xC2', '\xC4', + '\xC6', '\xC8', '\xCA', '\xCC', '\xCE', '\xD0', '\xD2', '\xD4', '\xD6', + '\xD8', '\xDA', '\xDC', '\xDE', '\xE0', '\xE2', '\xE4', '\xE6', '\xE8', + '\xEA', '\xEC', '\xEE', '\xF0', '\xF2', '\xF4', '\xF6', '\xF8', '\xFA', + '\xFC', '\xFE', '\x100', '\x102', '\x104', '\x106', '\x108', '\x10A', + '\x10C', '\x10E', '\x110', '\x112', '\x114', '\x116', '\x118', '\x11A', + '\x11C', '\x11E', '\x120', '\x122', '\x124', '\x126', '\x128', '\x12A', + '\x12C', '\x12E', '\x130', '\x132', '\x134', '\x136', '\x138', '\x13A', + '\x13C', '\x2', '\v', '\x3', '\x2', '\x4', '\n', '\x3', '\x2', '\x1A', + '\x1C', '\x6', '\x2', '~', '~', '\x80', '\x80', '\x83', '\x84', '\x86', + '\x8A', '\x3', '\x2', '\x35', '\x36', '\x3', '\x2', '@', '\x41', '\x3', + '\x2', '|', '}', '\x3', '\x2', 's', 'w', '\v', '\x2', '\f', '\xE', '\x10', + '\x11', '\x13', '\x14', '\x16', '\x1C', '%', '*', ',', '/', '\x34', '\x36', + '\x39', ':', '\x46', '^', '\b', '\x2', '\x3', '\b', '\n', '\n', '\f', + '\x1F', '!', '<', '?', '\x42', '\x46', 'r', '\x2', '\x683', '\x2', '\x141', + '\x3', '\x2', '\x2', '\x2', '\x4', '\x147', '\x3', '\x2', '\x2', '\x2', + '\x6', '\x149', '\x3', '\x2', '\x2', '\x2', '\b', '\x156', '\x3', '\x2', + '\x2', '\x2', '\n', '\x165', '\x3', '\x2', '\x2', '\x2', '\f', '\x168', + '\x3', '\x2', '\x2', '\x2', '\xE', '\x170', '\x3', '\x2', '\x2', '\x2', + '\x10', '\x172', '\x3', '\x2', '\x2', '\x2', '\x12', '\x17A', '\x3', '\x2', + '\x2', '\x2', '\x14', '\x17C', '\x3', '\x2', '\x2', '\x2', '\x16', '\x193', + '\x3', '\x2', '\x2', '\x2', '\x18', '\x19F', '\x3', '\x2', '\x2', '\x2', + '\x1A', '\x1A1', '\x3', '\x2', '\x2', '\x2', '\x1C', '\x1A3', '\x3', '\x2', + '\x2', '\x2', '\x1E', '\x1A5', '\x3', '\x2', '\x2', '\x2', ' ', '\x1B5', + '\x3', '\x2', '\x2', '\x2', '\"', '\x1B8', '\x3', '\x2', '\x2', '\x2', + '$', '\x1D3', '\x3', '\x2', '\x2', '\x2', '&', '\x1D5', '\x3', '\x2', + '\x2', '\x2', '(', '\x1D8', '\x3', '\x2', '\x2', '\x2', '*', '\x1E4', + '\x3', '\x2', '\x2', '\x2', ',', '\x1E6', '\x3', '\x2', '\x2', '\x2', + '.', '\x1F7', '\x3', '\x2', '\x2', '\x2', '\x30', '\x1FA', '\x3', '\x2', + '\x2', '\x2', '\x32', '\x20D', '\x3', '\x2', '\x2', '\x2', '\x34', '\x213', + '\x3', '\x2', '\x2', '\x2', '\x36', '\x216', '\x3', '\x2', '\x2', '\x2', + '\x38', '\x223', '\x3', '\x2', '\x2', '\x2', ':', '\x225', '\x3', '\x2', + '\x2', '\x2', '<', '\x229', '\x3', '\x2', '\x2', '\x2', '>', '\x22B', + '\x3', '\x2', '\x2', '\x2', '@', '\x22D', '\x3', '\x2', '\x2', '\x2', + '\x42', '\x23A', '\x3', '\x2', '\x2', '\x2', '\x44', '\x240', '\x3', '\x2', + '\x2', '\x2', '\x46', '\x243', '\x3', '\x2', '\x2', '\x2', 'H', '\x24D', + '\x3', '\x2', '\x2', '\x2', 'J', '\x24F', '\x3', '\x2', '\x2', '\x2', + 'L', '\x253', '\x3', '\x2', '\x2', '\x2', 'N', '\x259', '\x3', '\x2', + '\x2', '\x2', 'P', '\x25C', '\x3', '\x2', '\x2', '\x2', 'R', '\x26E', + '\x3', '\x2', '\x2', '\x2', 'T', '\x270', '\x3', '\x2', '\x2', '\x2', + 'V', '\x279', '\x3', '\x2', '\x2', '\x2', 'X', '\x2A5', '\x3', '\x2', + '\x2', '\x2', 'Z', '\x2A7', '\x3', '\x2', '\x2', '\x2', '\\', '\x2A9', + '\x3', '\x2', '\x2', '\x2', '^', '\x2B2', '\x3', '\x2', '\x2', '\x2', + '`', '\x2B4', '\x3', '\x2', '\x2', '\x2', '\x62', '\x2B7', '\x3', '\x2', + '\x2', '\x2', '\x64', '\x2C3', '\x3', '\x2', '\x2', '\x2', '\x66', '\x2C5', + '\x3', '\x2', '\x2', '\x2', 'h', '\x2CE', '\x3', '\x2', '\x2', '\x2', + 'j', '\x2D6', '\x3', '\x2', '\x2', '\x2', 'l', '\x2DB', '\x3', '\x2', + '\x2', '\x2', 'n', '\x2DD', '\x3', '\x2', '\x2', '\x2', 'p', '\x2E1', + '\x3', '\x2', '\x2', '\x2', 'r', '\x2E5', '\x3', '\x2', '\x2', '\x2', + 't', '\x2EB', '\x3', '\x2', '\x2', '\x2', 'v', '\x2EE', '\x3', '\x2', + '\x2', '\x2', 'x', '\x2FC', '\x3', '\x2', '\x2', '\x2', 'z', '\x304', + '\x3', '\x2', '\x2', '\x2', '|', '\x306', '\x3', '\x2', '\x2', '\x2', + '~', '\x30A', '\x3', '\x2', '\x2', '\x2', '\x80', '\x30E', '\x3', '\x2', + '\x2', '\x2', '\x82', '\x310', '\x3', '\x2', '\x2', '\x2', '\x84', '\x318', + '\x3', '\x2', '\x2', '\x2', '\x86', '\x332', '\x3', '\x2', '\x2', '\x2', + '\x88', '\x334', '\x3', '\x2', '\x2', '\x2', '\x8A', '\x33D', '\x3', '\x2', + '\x2', '\x2', '\x8C', '\x346', '\x3', '\x2', '\x2', '\x2', '\x8E', '\x349', + '\x3', '\x2', '\x2', '\x2', '\x90', '\x351', '\x3', '\x2', '\x2', '\x2', + '\x92', '\x358', '\x3', '\x2', '\x2', '\x2', '\x94', '\x368', '\x3', '\x2', + '\x2', '\x2', '\x96', '\x375', '\x3', '\x2', '\x2', '\x2', '\x98', '\x37E', + '\x3', '\x2', '\x2', '\x2', '\x9A', '\x380', '\x3', '\x2', '\x2', '\x2', + '\x9C', '\x389', '\x3', '\x2', '\x2', '\x2', '\x9E', '\x39D', '\x3', '\x2', + '\x2', '\x2', '\xA0', '\x39F', '\x3', '\x2', '\x2', '\x2', '\xA2', '\x3A1', + '\x3', '\x2', '\x2', '\x2', '\xA4', '\x3A3', '\x3', '\x2', '\x2', '\x2', + '\xA6', '\x3A5', '\x3', '\x2', '\x2', '\x2', '\xA8', '\x3BF', '\x3', '\x2', + '\x2', '\x2', '\xAA', '\x3D8', '\x3', '\x2', '\x2', '\x2', '\xAC', '\x3DB', + '\x3', '\x2', '\x2', '\x2', '\xAE', '\x3E8', '\x3', '\x2', '\x2', '\x2', + '\xB0', '\x3EA', '\x3', '\x2', '\x2', '\x2', '\xB2', '\x401', '\x3', '\x2', + '\x2', '\x2', '\xB4', '\x403', '\x3', '\x2', '\x2', '\x2', '\xB6', '\x405', + '\x3', '\x2', '\x2', '\x2', '\xB8', '\x407', '\x3', '\x2', '\x2', '\x2', + '\xBA', '\x429', '\x3', '\x2', '\x2', '\x2', '\xBC', '\x42D', '\x3', '\x2', + '\x2', '\x2', '\xBE', '\x443', '\x3', '\x2', '\x2', '\x2', '\xC0', '\x445', + '\x3', '\x2', '\x2', '\x2', '\xC2', '\x44A', '\x3', '\x2', '\x2', '\x2', + '\xC4', '\x455', '\x3', '\x2', '\x2', '\x2', '\xC6', '\x45C', '\x3', '\x2', + '\x2', '\x2', '\xC8', '\x45E', '\x3', '\x2', '\x2', '\x2', '\xCA', '\x460', + '\x3', '\x2', '\x2', '\x2', '\xCC', '\x465', '\x3', '\x2', '\x2', '\x2', + '\xCE', '\x467', '\x3', '\x2', '\x2', '\x2', '\xD0', '\x46C', '\x3', '\x2', + '\x2', '\x2', '\xD2', '\x473', '\x3', '\x2', '\x2', '\x2', '\xD4', '\x486', + '\x3', '\x2', '\x2', '\x2', '\xD6', '\x48A', '\x3', '\x2', '\x2', '\x2', + '\xD8', '\x4A4', '\x3', '\x2', '\x2', '\x2', '\xDA', '\x4A7', '\x3', '\x2', + '\x2', '\x2', '\xDC', '\x4C4', '\x3', '\x2', '\x2', '\x2', '\xDE', '\x4C6', + '\x3', '\x2', '\x2', '\x2', '\xE0', '\x4D3', '\x3', '\x2', '\x2', '\x2', + '\xE2', '\x4DD', '\x3', '\x2', '\x2', '\x2', '\xE4', '\x4DF', '\x3', '\x2', + '\x2', '\x2', '\xE6', '\x4F3', '\x3', '\x2', '\x2', '\x2', '\xE8', '\x4FE', + '\x3', '\x2', '\x2', '\x2', '\xEA', '\x505', '\x3', '\x2', '\x2', '\x2', + '\xEC', '\x511', '\x3', '\x2', '\x2', '\x2', '\xEE', '\x517', '\x3', '\x2', + '\x2', '\x2', '\xF0', '\x528', '\x3', '\x2', '\x2', '\x2', '\xF2', '\x539', + '\x3', '\x2', '\x2', '\x2', '\xF4', '\x542', '\x3', '\x2', '\x2', '\x2', + '\xF6', '\x544', '\x3', '\x2', '\x2', '\x2', '\xF8', '\x546', '\x3', '\x2', + '\x2', '\x2', '\xFA', '\x54E', '\x3', '\x2', '\x2', '\x2', '\xFC', '\x550', + '\x3', '\x2', '\x2', '\x2', '\xFE', '\x55B', '\x3', '\x2', '\x2', '\x2', + '\x100', '\x561', '\x3', '\x2', '\x2', '\x2', '\x102', '\x563', '\x3', + '\x2', '\x2', '\x2', '\x104', '\x565', '\x3', '\x2', '\x2', '\x2', '\x106', + '\x569', '\x3', '\x2', '\x2', '\x2', '\x108', '\x56F', '\x3', '\x2', '\x2', + '\x2', '\x10A', '\x576', '\x3', '\x2', '\x2', '\x2', '\x10C', '\x57C', + '\x3', '\x2', '\x2', '\x2', '\x10E', '\x57E', '\x3', '\x2', '\x2', '\x2', + '\x110', '\x580', '\x3', '\x2', '\x2', '\x2', '\x112', '\x583', '\x3', + '\x2', '\x2', '\x2', '\x114', '\x587', '\x3', '\x2', '\x2', '\x2', '\x116', + '\x589', '\x3', '\x2', '\x2', '\x2', '\x118', '\x58D', '\x3', '\x2', '\x2', + '\x2', '\x11A', '\x58F', '\x3', '\x2', '\x2', '\x2', '\x11C', '\x593', + '\x3', '\x2', '\x2', '\x2', '\x11E', '\x5A4', '\x3', '\x2', '\x2', '\x2', + '\x120', '\x5A6', '\x3', '\x2', '\x2', '\x2', '\x122', '\x5A9', '\x3', + '\x2', '\x2', '\x2', '\x124', '\x5B3', '\x3', '\x2', '\x2', '\x2', '\x126', + '\x5BD', '\x3', '\x2', '\x2', '\x2', '\x128', '\x5BF', '\x3', '\x2', '\x2', + '\x2', '\x12A', '\x5C3', '\x3', '\x2', '\x2', '\x2', '\x12C', '\x5C7', + '\x3', '\x2', '\x2', '\x2', '\x12E', '\x5CF', '\x3', '\x2', '\x2', '\x2', + '\x130', '\x5D1', '\x3', '\x2', '\x2', '\x2', '\x132', '\x5D3', '\x3', + '\x2', '\x2', '\x2', '\x134', '\x5D5', '\x3', '\x2', '\x2', '\x2', '\x136', + '\x5D7', '\x3', '\x2', '\x2', '\x2', '\x138', '\x5D9', '\x3', '\x2', '\x2', + '\x2', '\x13A', '\x5DD', '\x3', '\x2', '\x2', '\x2', '\x13C', '\x5FF', + '\x3', '\x2', '\x2', '\x2', '\x13E', '\x140', '\x5', '\x4', '\x3', '\x2', + '\x13F', '\x13E', '\x3', '\x2', '\x2', '\x2', '\x140', '\x143', '\x3', + '\x2', '\x2', '\x2', '\x141', '\x13F', '\x3', '\x2', '\x2', '\x2', '\x141', + '\x142', '\x3', '\x2', '\x2', '\x2', '\x142', '\x3', '\x3', '\x2', '\x2', + '\x2', '\x143', '\x141', '\x3', '\x2', '\x2', '\x2', '\x144', '\x148', + '\x5', '\f', '\a', '\x2', '\x145', '\x148', '\x5', '\b', '\x5', '\x2', + '\x146', '\x148', '\x5', '\x6', '\x4', '\x2', '\x147', '\x144', '\x3', + '\x2', '\x2', '\x2', '\x147', '\x145', '\x3', '\x2', '\x2', '\x2', '\x147', + '\x146', '\x3', '\x2', '\x2', '\x2', '\x148', '\x5', '\x3', '\x2', '\x2', + '\x2', '\x149', '\x14A', '\a', '\x97', '\x2', '\x2', '\x14A', '\a', '\x3', + '\x2', '\x2', '\x2', '\x14B', '\x157', '\x5', '\x14', '\v', '\x2', '\x14C', + '\x157', '\x5', '(', '\x15', '\x2', '\x14D', '\x157', '\x5', '\x94', 'K', + '\x2', '\x14E', '\x157', '\x5', '.', '\x18', '\x2', '\x14F', '\x157', + '\x5', 'P', ')', '\x2', '\x150', '\x157', '\x5', 'X', '-', '\x2', '\x151', + '\x157', '\x5', '\x62', '\x32', '\x2', '\x152', '\x157', '\x5', '\x86', + '\x44', '\x2', '\x153', '\x157', '\x5', '\x8C', 'G', '\x2', '\x154', '\x157', + '\x5', 'l', '\x37', '\x2', '\x155', '\x157', '\x5', 'v', '<', '\x2', '\x156', + '\x14B', '\x3', '\x2', '\x2', '\x2', '\x156', '\x14C', '\x3', '\x2', '\x2', + '\x2', '\x156', '\x14D', '\x3', '\x2', '\x2', '\x2', '\x156', '\x14E', + '\x3', '\x2', '\x2', '\x2', '\x156', '\x14F', '\x3', '\x2', '\x2', '\x2', + '\x156', '\x150', '\x3', '\x2', '\x2', '\x2', '\x156', '\x151', '\x3', + '\x2', '\x2', '\x2', '\x156', '\x152', '\x3', '\x2', '\x2', '\x2', '\x156', + '\x153', '\x3', '\x2', '\x2', '\x2', '\x156', '\x154', '\x3', '\x2', '\x2', + '\x2', '\x156', '\x155', '\x3', '\x2', '\x2', '\x2', '\x157', '\t', '\x3', + '\x2', '\x2', '\x2', '\x158', '\x166', '\x5', '\x14', '\v', '\x2', '\x159', + '\x166', '\x5', '(', '\x15', '\x2', '\x15A', '\x166', '\x5', '\x94', 'K', + '\x2', '\x15B', '\x166', '\x5', '.', '\x18', '\x2', '\x15C', '\x166', + '\x5', 'P', ')', '\x2', '\x15D', '\x166', '\x5', 'X', '-', '\x2', '\x15E', + '\x166', '\x5', '\x62', '\x32', '\x2', '\x15F', '\x166', '\x5', '\xA8', + 'U', '\x2', '\x160', '\x166', '\x5', '\xAC', 'W', '\x2', '\x161', '\x166', + '\x5', '\x86', '\x44', '\x2', '\x162', '\x166', '\x5', '\x8C', 'G', '\x2', + '\x163', '\x166', '\x5', 'l', '\x37', '\x2', '\x164', '\x166', '\x5', + 'v', '<', '\x2', '\x165', '\x158', '\x3', '\x2', '\x2', '\x2', '\x165', + '\x159', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15A', '\x3', '\x2', '\x2', + '\x2', '\x165', '\x15B', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15C', + '\x3', '\x2', '\x2', '\x2', '\x165', '\x15D', '\x3', '\x2', '\x2', '\x2', + '\x165', '\x15E', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15F', '\x3', + '\x2', '\x2', '\x2', '\x165', '\x160', '\x3', '\x2', '\x2', '\x2', '\x165', + '\x161', '\x3', '\x2', '\x2', '\x2', '\x165', '\x162', '\x3', '\x2', '\x2', + '\x2', '\x165', '\x163', '\x3', '\x2', '\x2', '\x2', '\x165', '\x164', + '\x3', '\x2', '\x2', '\x2', '\x166', '\v', '\x3', '\x2', '\x2', '\x2', + '\x167', '\x169', '\x5', '\xD0', 'i', '\x2', '\x168', '\x167', '\x3', + '\x2', '\x2', '\x2', '\x168', '\x169', '\x3', '\x2', '\x2', '\x2', '\x169', + '\x16A', '\x3', '\x2', '\x2', '\x2', '\x16A', '\x16C', '\a', '\x3', '\x2', + '\x2', '\x16B', '\x16D', '\x5', '\xE', '\b', '\x2', '\x16C', '\x16B', + '\x3', '\x2', '\x2', '\x2', '\x16C', '\x16D', '\x3', '\x2', '\x2', '\x2', + '\x16D', '\x16E', '\x3', '\x2', '\x2', '\x2', '\x16E', '\x16F', '\x5', + '\x10', '\t', '\x2', '\x16F', '\r', '\x3', '\x2', '\x2', '\x2', '\x170', + '\x171', '\t', '\x2', '\x2', '\x2', '\x171', '\xF', '\x3', '\x2', '\x2', + '\x2', '\x172', '\x177', '\x5', '\x12', '\n', '\x2', '\x173', '\x174', + '\a', '\x83', '\x2', '\x2', '\x174', '\x176', '\x5', '\x12', '\n', '\x2', + '\x175', '\x173', '\x3', '\x2', '\x2', '\x2', '\x176', '\x179', '\x3', + '\x2', '\x2', '\x2', '\x177', '\x175', '\x3', '\x2', '\x2', '\x2', '\x177', + '\x178', '\x3', '\x2', '\x2', '\x2', '\x178', '\x11', '\x3', '\x2', '\x2', + '\x2', '\x179', '\x177', '\x3', '\x2', '\x2', '\x2', '\x17A', '\x17B', + '\x5', '\xC2', '\x62', '\x2', '\x17B', '\x13', '\x3', '\x2', '\x2', '\x2', + '\x17C', '\x17D', '\x5', '\x16', '\f', '\x2', '\x17D', '\x182', '\x5', + '\x18', '\r', '\x2', '\x17E', '\x17F', '\a', '\x84', '\x2', '\x2', '\x17F', + '\x181', '\x5', '\x18', '\r', '\x2', '\x180', '\x17E', '\x3', '\x2', '\x2', + '\x2', '\x181', '\x184', '\x3', '\x2', '\x2', '\x2', '\x182', '\x180', + '\x3', '\x2', '\x2', '\x2', '\x182', '\x183', '\x3', '\x2', '\x2', '\x2', + '\x183', '\x15', '\x3', '\x2', '\x2', '\x2', '\x184', '\x182', '\x3', + '\x2', '\x2', '\x2', '\x185', '\x187', '\x5', '\xD0', 'i', '\x2', '\x186', + '\x185', '\x3', '\x2', '\x2', '\x2', '\x186', '\x187', '\x3', '\x2', '\x2', + '\x2', '\x187', '\x189', '\x3', '\x2', '\x2', '\x2', '\x188', '\x18A', + '\x5', '\xDA', 'n', '\x2', '\x189', '\x188', '\x3', '\x2', '\x2', '\x2', + '\x189', '\x18A', '\x3', '\x2', '\x2', '\x2', '\x18A', '\x18B', '\x3', + '\x2', '\x2', '\x2', '\x18B', '\x194', '\x5', '\x1C', '\xF', '\x2', '\x18C', + '\x18E', '\x5', '\xD0', 'i', '\x2', '\x18D', '\x18C', '\x3', '\x2', '\x2', + '\x2', '\x18D', '\x18E', '\x3', '\x2', '\x2', '\x2', '\x18E', '\x190', + '\x3', '\x2', '\x2', '\x2', '\x18F', '\x191', '\x5', '\xDA', 'n', '\x2', + '\x190', '\x18F', '\x3', '\x2', '\x2', '\x2', '\x190', '\x191', '\x3', + '\x2', '\x2', '\x2', '\x191', '\x192', '\x3', '\x2', '\x2', '\x2', '\x192', + '\x194', '\x5', '\x1E', '\x10', '\x2', '\x193', '\x186', '\x3', '\x2', + '\x2', '\x2', '\x193', '\x18D', '\x3', '\x2', '\x2', '\x2', '\x194', '\x17', + '\x3', '\x2', '\x2', '\x2', '\x195', '\x196', '\x5', '\x1A', '\xE', '\x2', + '\x196', '\x198', '\x5', '\xF2', 'z', '\x2', '\x197', '\x199', '\x5', + ' ', '\x11', '\x2', '\x198', '\x197', '\x3', '\x2', '\x2', '\x2', '\x198', + '\x199', '\x3', '\x2', '\x2', '\x2', '\x199', '\x1A0', '\x3', '\x2', '\x2', + '\x2', '\x19A', '\x19B', '\x5', '\x1A', '\xE', '\x2', '\x19B', '\x19D', + '\x5', '\xF2', 'z', '\x2', '\x19C', '\x19E', '\x5', '\xB8', ']', '\x2', + '\x19D', '\x19C', '\x3', '\x2', '\x2', '\x2', '\x19D', '\x19E', '\x3', + '\x2', '\x2', '\x2', '\x19E', '\x1A0', '\x3', '\x2', '\x2', '\x2', '\x19F', + '\x195', '\x3', '\x2', '\x2', '\x2', '\x19F', '\x19A', '\x3', '\x2', '\x2', + '\x2', '\x1A0', '\x19', '\x3', '\x2', '\x2', '\x2', '\x1A1', '\x1A2', + '\x5', '\xC2', '\x62', '\x2', '\x1A2', '\x1B', '\x3', '\x2', '\x2', '\x2', + '\x1A3', '\x1A4', '\a', '\t', '\x2', '\x2', '\x1A4', '\x1D', '\x3', '\x2', + '\x2', '\x2', '\x1A5', '\x1A6', '\a', '\v', '\x2', '\x2', '\x1A6', '\x1F', + '\x3', '\x2', '\x2', '\x2', '\x1A7', '\x1A8', '\a', '\x90', '\x2', '\x2', + '\x1A8', '\x1A9', '\x5', '\"', '\x12', '\x2', '\x1A9', '\x1AA', '\x5', + '$', '\x13', '\x2', '\x1AA', '\x1AB', '\a', '\x91', '\x2', '\x2', '\x1AB', + '\x1B6', '\x3', '\x2', '\x2', '\x2', '\x1AC', '\x1AD', '\a', '\x90', '\x2', + '\x2', '\x1AD', '\x1AE', '\x5', '$', '\x13', '\x2', '\x1AE', '\x1AF', + '\x5', '\"', '\x12', '\x2', '\x1AF', '\x1B0', '\a', '\x91', '\x2', '\x2', + '\x1B0', '\x1B6', '\x3', '\x2', '\x2', '\x2', '\x1B1', '\x1B2', '\a', + '\x90', '\x2', '\x2', '\x1B2', '\x1B3', '\x5', '\"', '\x12', '\x2', '\x1B3', + '\x1B4', '\a', '\x91', '\x2', '\x2', '\x1B4', '\x1B6', '\x3', '\x2', '\x2', + '\x2', '\x1B5', '\x1A7', '\x3', '\x2', '\x2', '\x2', '\x1B5', '\x1AC', + '\x3', '\x2', '\x2', '\x2', '\x1B5', '\x1B1', '\x3', '\x2', '\x2', '\x2', + '\x1B6', '!', '\x3', '\x2', '\x2', '\x2', '\x1B7', '\x1B9', '\x5', '\xD0', + 'i', '\x2', '\x1B8', '\x1B7', '\x3', '\x2', '\x2', '\x2', '\x1B8', '\x1B9', + '\x3', '\x2', '\x2', '\x2', '\x1B9', '\x1BB', '\x3', '\x2', '\x2', '\x2', + '\x1BA', '\x1BC', '\x5', '\xDE', 'p', '\x2', '\x1BB', '\x1BA', '\x3', + '\x2', '\x2', '\x2', '\x1BB', '\x1BC', '\x3', '\x2', '\x2', '\x2', '\x1BC', + '\x1BD', '\x3', '\x2', '\x2', '\x2', '\x1BD', '\x1BF', '\a', '\f', '\x2', + '\x2', '\x1BE', '\x1C0', '\x5', '\xA0', 'Q', '\x2', '\x1BF', '\x1BE', + '\x3', '\x2', '\x2', '\x2', '\x1BF', '\x1C0', '\x3', '\x2', '\x2', '\x2', + '\x1C0', '#', '\x3', '\x2', '\x2', '\x2', '\x1C1', '\x1C3', '\x5', '\xD0', + 'i', '\x2', '\x1C2', '\x1C1', '\x3', '\x2', '\x2', '\x2', '\x1C2', '\x1C3', + '\x3', '\x2', '\x2', '\x2', '\x1C3', '\x1C5', '\x3', '\x2', '\x2', '\x2', + '\x1C4', '\x1C6', '\x5', '\xDE', 'p', '\x2', '\x1C5', '\x1C4', '\x3', + '\x2', '\x2', '\x2', '\x1C5', '\x1C6', '\x3', '\x2', '\x2', '\x2', '\x1C6', + '\x1C7', '\x3', '\x2', '\x2', '\x2', '\x1C7', '\x1D4', '\a', '\r', '\x2', + '\x2', '\x1C8', '\x1CA', '\x5', '\xD0', 'i', '\x2', '\x1C9', '\x1C8', + '\x3', '\x2', '\x2', '\x2', '\x1C9', '\x1CA', '\x3', '\x2', '\x2', '\x2', + '\x1CA', '\x1CC', '\x3', '\x2', '\x2', '\x2', '\x1CB', '\x1CD', '\x5', + '\xDE', 'p', '\x2', '\x1CC', '\x1CB', '\x3', '\x2', '\x2', '\x2', '\x1CC', + '\x1CD', '\x3', '\x2', '\x2', '\x2', '\x1CD', '\x1CE', '\x3', '\x2', '\x2', + '\x2', '\x1CE', '\x1CF', '\a', '\r', '\x2', '\x2', '\x1CF', '\x1D0', '\a', + '\x8C', '\x2', '\x2', '\x1D0', '\x1D1', '\x5', '&', '\x14', '\x2', '\x1D1', + '\x1D2', '\a', '\x8D', '\x2', '\x2', '\x1D2', '\x1D4', '\x3', '\x2', '\x2', + '\x2', '\x1D3', '\x1C2', '\x3', '\x2', '\x2', '\x2', '\x1D3', '\x1C9', + '\x3', '\x2', '\x2', '\x2', '\x1D4', '%', '\x3', '\x2', '\x2', '\x2', + '\x1D5', '\x1D6', '\x5', '\xC2', '\x62', '\x2', '\x1D6', '\'', '\x3', + '\x2', '\x2', '\x2', '\x1D7', '\x1D9', '\x5', '\xD0', 'i', '\x2', '\x1D8', + '\x1D7', '\x3', '\x2', '\x2', '\x2', '\x1D8', '\x1D9', '\x3', '\x2', '\x2', + '\x2', '\x1D9', '\x1DB', '\x3', '\x2', '\x2', '\x2', '\x1DA', '\x1DC', + '\x5', '\xDC', 'o', '\x2', '\x1DB', '\x1DA', '\x3', '\x2', '\x2', '\x2', + '\x1DB', '\x1DC', '\x3', '\x2', '\x2', '\x2', '\x1DC', '\x1DD', '\x3', + '\x2', '\x2', '\x2', '\x1DD', '\x1DE', '\a', '\x4', '\x2', '\x2', '\x1DE', + '\x1E0', '\x5', '*', '\x16', '\x2', '\x1DF', '\x1E1', '\x5', '\x11A', + '\x8E', '\x2', '\x1E0', '\x1DF', '\x3', '\x2', '\x2', '\x2', '\x1E0', + '\x1E1', '\x3', '\x2', '\x2', '\x2', '\x1E1', '\x1E2', '\x3', '\x2', '\x2', + '\x2', '\x1E2', '\x1E3', '\x5', ',', '\x17', '\x2', '\x1E3', ')', '\x3', + '\x2', '\x2', '\x2', '\x1E4', '\x1E5', '\x5', '\xC2', '\x62', '\x2', '\x1E5', + '+', '\x3', '\x2', '\x2', '\x2', '\x1E6', '\x1E7', '\a', '~', '\x2', '\x2', + '\x1E7', '\x1E8', '\x5', '\xF0', 'y', '\x2', '\x1E8', '-', '\x3', '\x2', + '\x2', '\x2', '\x1E9', '\x1EB', '\x5', '\xD0', 'i', '\x2', '\x1EA', '\x1E9', + '\x3', '\x2', '\x2', '\x2', '\x1EA', '\x1EB', '\x3', '\x2', '\x2', '\x2', + '\x1EB', '\x1ED', '\x3', '\x2', '\x2', '\x2', '\x1EC', '\x1EE', '\x5', + '\xDC', 'o', '\x2', '\x1ED', '\x1EC', '\x3', '\x2', '\x2', '\x2', '\x1ED', + '\x1EE', '\x3', '\x2', '\x2', '\x2', '\x1EE', '\x1EF', '\x3', '\x2', '\x2', + '\x2', '\x1EF', '\x1F8', '\x5', '\x30', '\x19', '\x2', '\x1F0', '\x1F2', + '\x5', '\xD0', 'i', '\x2', '\x1F1', '\x1F0', '\x3', '\x2', '\x2', '\x2', + '\x1F1', '\x1F2', '\x3', '\x2', '\x2', '\x2', '\x1F2', '\x1F4', '\x3', + '\x2', '\x2', '\x2', '\x1F3', '\x1F5', '\x5', '\xDC', 'o', '\x2', '\x1F4', + '\x1F3', '\x3', '\x2', '\x2', '\x2', '\x1F4', '\x1F5', '\x3', '\x2', '\x2', + '\x2', '\x1F5', '\x1F6', '\x3', '\x2', '\x2', '\x2', '\x1F6', '\x1F8', + '\x5', '@', '!', '\x2', '\x1F7', '\x1EA', '\x3', '\x2', '\x2', '\x2', + '\x1F7', '\x1F1', '\x3', '\x2', '\x2', '\x2', '\x1F8', '/', '\x3', '\x2', + '\x2', '\x2', '\x1F9', '\x1FB', '\a', '\xE', '\x2', '\x2', '\x1FA', '\x1F9', + '\x3', '\x2', '\x2', '\x2', '\x1FA', '\x1FB', '\x3', '\x2', '\x2', '\x2', + '\x1FB', '\x1FC', '\x3', '\x2', '\x2', '\x2', '\x1FC', '\x1FD', '\a', + '\a', '\x2', '\x2', '\x1FD', '\x1FF', '\x5', '<', '\x1F', '\x2', '\x1FE', + '\x200', '\x5', '\x11A', '\x8E', '\x2', '\x1FF', '\x1FE', '\x3', '\x2', + '\x2', '\x2', '\x1FF', '\x200', '\x3', '\x2', '\x2', '\x2', '\x200', '\x202', + '\x3', '\x2', '\x2', '\x2', '\x201', '\x203', '\x5', '\xC4', '\x63', '\x2', + '\x202', '\x201', '\x3', '\x2', '\x2', '\x2', '\x202', '\x203', '\x3', + '\x2', '\x2', '\x2', '\x203', '\x205', '\x3', '\x2', '\x2', '\x2', '\x204', + '\x206', '\x5', '\x120', '\x91', '\x2', '\x205', '\x204', '\x3', '\x2', + '\x2', '\x2', '\x205', '\x206', '\x3', '\x2', '\x2', '\x2', '\x206', '\x207', + '\x3', '\x2', '\x2', '\x2', '\x207', '\x209', '\a', '\x90', '\x2', '\x2', + '\x208', '\x20A', '\x5', '\x32', '\x1A', '\x2', '\x209', '\x208', '\x3', + '\x2', '\x2', '\x2', '\x209', '\x20A', '\x3', '\x2', '\x2', '\x2', '\x20A', + '\x20B', '\x3', '\x2', '\x2', '\x2', '\x20B', '\x20C', '\a', '\x91', '\x2', + '\x2', '\x20C', '\x31', '\x3', '\x2', '\x2', '\x2', '\x20D', '\x20F', + '\x5', '\x34', '\x1B', '\x2', '\x20E', '\x210', '\x5', '\x32', '\x1A', + '\x2', '\x20F', '\x20E', '\x3', '\x2', '\x2', '\x2', '\x20F', '\x210', + '\x3', '\x2', '\x2', '\x2', '\x210', '\x33', '\x3', '\x2', '\x2', '\x2', + '\x211', '\x214', '\x5', '\n', '\x6', '\x2', '\x212', '\x214', '\x5', + '\x36', '\x1C', '\x2', '\x213', '\x211', '\x3', '\x2', '\x2', '\x2', '\x213', + '\x212', '\x3', '\x2', '\x2', '\x2', '\x214', '\x35', '\x3', '\x2', '\x2', + '\x2', '\x215', '\x217', '\x5', '\xD0', 'i', '\x2', '\x216', '\x215', + '\x3', '\x2', '\x2', '\x2', '\x216', '\x217', '\x3', '\x2', '\x2', '\x2', + '\x217', '\x219', '\x3', '\x2', '\x2', '\x2', '\x218', '\x21A', '\a', + '\xE', '\x2', '\x2', '\x219', '\x218', '\x3', '\x2', '\x2', '\x2', '\x219', + '\x21A', '\x3', '\x2', '\x2', '\x2', '\x21A', '\x21B', '\x3', '\x2', '\x2', + '\x2', '\x21B', '\x21C', '\a', '\xF', '\x2', '\x2', '\x21C', '\x21D', + '\x5', '\x38', '\x1D', '\x2', '\x21D', '\x37', '\x3', '\x2', '\x2', '\x2', + '\x21E', '\x224', '\x5', ':', '\x1E', '\x2', '\x21F', '\x220', '\x5', + ':', '\x1E', '\x2', '\x220', '\x221', '\a', '\x84', '\x2', '\x2', '\x221', + '\x222', '\x5', '\x38', '\x1D', '\x2', '\x222', '\x224', '\x3', '\x2', + '\x2', '\x2', '\x223', '\x21E', '\x3', '\x2', '\x2', '\x2', '\x223', '\x21F', + '\x3', '\x2', '\x2', '\x2', '\x224', '\x39', '\x3', '\x2', '\x2', '\x2', + '\x225', '\x227', '\x5', '>', ' ', '\x2', '\x226', '\x228', '\x5', '\xFC', + '\x7F', '\x2', '\x227', '\x226', '\x3', '\x2', '\x2', '\x2', '\x227', + '\x228', '\x3', '\x2', '\x2', '\x2', '\x228', ';', '\x3', '\x2', '\x2', + '\x2', '\x229', '\x22A', '\x5', '\xC2', '\x62', '\x2', '\x22A', '=', '\x3', + '\x2', '\x2', '\x2', '\x22B', '\x22C', '\x5', '\xC2', '\x62', '\x2', '\x22C', + '?', '\x3', '\x2', '\x2', '\x2', '\x22D', '\x22E', '\a', '\a', '\x2', + '\x2', '\x22E', '\x230', '\x5', '<', '\x1F', '\x2', '\x22F', '\x231', + '\x5', '\x11A', '\x8E', '\x2', '\x230', '\x22F', '\x3', '\x2', '\x2', + '\x2', '\x230', '\x231', '\x3', '\x2', '\x2', '\x2', '\x231', '\x232', + '\x3', '\x2', '\x2', '\x2', '\x232', '\x234', '\x5', '\xC4', '\x63', '\x2', + '\x233', '\x235', '\x5', '\x120', '\x91', '\x2', '\x234', '\x233', '\x3', + '\x2', '\x2', '\x2', '\x234', '\x235', '\x3', '\x2', '\x2', '\x2', '\x235', + '\x236', '\x3', '\x2', '\x2', '\x2', '\x236', '\x237', '\a', '\x90', '\x2', + '\x2', '\x237', '\x238', '\x5', '\x42', '\"', '\x2', '\x238', '\x239', + '\a', '\x91', '\x2', '\x2', '\x239', '\x41', '\x3', '\x2', '\x2', '\x2', + '\x23A', '\x23C', '\x5', '\x44', '#', '\x2', '\x23B', '\x23D', '\x5', + '\x42', '\"', '\x2', '\x23C', '\x23B', '\x3', '\x2', '\x2', '\x2', '\x23C', + '\x23D', '\x3', '\x2', '\x2', '\x2', '\x23D', '\x43', '\x3', '\x2', '\x2', + '\x2', '\x23E', '\x241', '\x5', '\n', '\x6', '\x2', '\x23F', '\x241', + '\x5', '\x46', '$', '\x2', '\x240', '\x23E', '\x3', '\x2', '\x2', '\x2', + '\x240', '\x23F', '\x3', '\x2', '\x2', '\x2', '\x241', '\x45', '\x3', + '\x2', '\x2', '\x2', '\x242', '\x244', '\x5', '\xD0', 'i', '\x2', '\x243', + '\x242', '\x3', '\x2', '\x2', '\x2', '\x243', '\x244', '\x3', '\x2', '\x2', + '\x2', '\x244', '\x245', '\x3', '\x2', '\x2', '\x2', '\x245', '\x246', + '\a', '\xF', '\x2', '\x2', '\x246', '\x247', '\x5', 'H', '%', '\x2', '\x247', + 'G', '\x3', '\x2', '\x2', '\x2', '\x248', '\x24E', '\x5', 'J', '&', '\x2', + '\x249', '\x24A', '\x5', 'J', '&', '\x2', '\x24A', '\x24B', '\a', '\x84', + '\x2', '\x2', '\x24B', '\x24C', '\x5', 'H', '%', '\x2', '\x24C', '\x24E', + '\x3', '\x2', '\x2', '\x2', '\x24D', '\x248', '\x3', '\x2', '\x2', '\x2', + '\x24D', '\x249', '\x3', '\x2', '\x2', '\x2', '\x24E', 'I', '\x3', '\x2', + '\x2', '\x2', '\x24F', '\x251', '\x5', '>', ' ', '\x2', '\x250', '\x252', + '\x5', 'L', '\'', '\x2', '\x251', '\x250', '\x3', '\x2', '\x2', '\x2', + '\x251', '\x252', '\x3', '\x2', '\x2', '\x2', '\x252', 'K', '\x3', '\x2', + '\x2', '\x2', '\x253', '\x254', '\a', '~', '\x2', '\x2', '\x254', '\x255', + '\x5', 'N', '(', '\x2', '\x255', 'M', '\x3', '\x2', '\x2', '\x2', '\x256', + '\x25A', '\x5', '\x112', '\x8A', '\x2', '\x257', '\x25A', '\a', 'x', '\x2', + '\x2', '\x258', '\x25A', '\x5', '\x110', '\x89', '\x2', '\x259', '\x256', + '\x3', '\x2', '\x2', '\x2', '\x259', '\x257', '\x3', '\x2', '\x2', '\x2', + '\x259', '\x258', '\x3', '\x2', '\x2', '\x2', '\x25A', 'O', '\x3', '\x2', + '\x2', '\x2', '\x25B', '\x25D', '\x5', '\xD0', 'i', '\x2', '\x25C', '\x25B', + '\x3', '\x2', '\x2', '\x2', '\x25C', '\x25D', '\x3', '\x2', '\x2', '\x2', + '\x25D', '\x25F', '\x3', '\x2', '\x2', '\x2', '\x25E', '\x260', '\x5', + '\xDC', 'o', '\x2', '\x25F', '\x25E', '\x3', '\x2', '\x2', '\x2', '\x25F', + '\x260', '\x3', '\x2', '\x2', '\x2', '\x260', '\x261', '\x3', '\x2', '\x2', + '\x2', '\x261', '\x262', '\a', '\x5', '\x2', '\x2', '\x262', '\x264', + '\x5', 'R', '*', '\x2', '\x263', '\x265', '\x5', '\x11A', '\x8E', '\x2', + '\x264', '\x263', '\x3', '\x2', '\x2', '\x2', '\x264', '\x265', '\x3', + '\x2', '\x2', '\x2', '\x265', '\x267', '\x3', '\x2', '\x2', '\x2', '\x266', + '\x268', '\x5', '\xC4', '\x63', '\x2', '\x267', '\x266', '\x3', '\x2', + '\x2', '\x2', '\x267', '\x268', '\x3', '\x2', '\x2', '\x2', '\x268', '\x26A', + '\x3', '\x2', '\x2', '\x2', '\x269', '\x26B', '\x5', '\x120', '\x91', + '\x2', '\x26A', '\x269', '\x3', '\x2', '\x2', '\x2', '\x26A', '\x26B', + '\x3', '\x2', '\x2', '\x2', '\x26B', '\x26C', '\x3', '\x2', '\x2', '\x2', + '\x26C', '\x26D', '\x5', 'T', '+', '\x2', '\x26D', 'Q', '\x3', '\x2', + '\x2', '\x2', '\x26E', '\x26F', '\x5', '\xC2', '\x62', '\x2', '\x26F', + 'S', '\x3', '\x2', '\x2', '\x2', '\x270', '\x274', '\a', '\x90', '\x2', + '\x2', '\x271', '\x273', '\x5', 'V', ',', '\x2', '\x272', '\x271', '\x3', + '\x2', '\x2', '\x2', '\x273', '\x276', '\x3', '\x2', '\x2', '\x2', '\x274', + '\x272', '\x3', '\x2', '\x2', '\x2', '\x274', '\x275', '\x3', '\x2', '\x2', + '\x2', '\x275', '\x277', '\x3', '\x2', '\x2', '\x2', '\x276', '\x274', + '\x3', '\x2', '\x2', '\x2', '\x277', '\x278', '\a', '\x91', '\x2', '\x2', + '\x278', 'U', '\x3', '\x2', '\x2', '\x2', '\x279', '\x27A', '\x5', '\n', + '\x6', '\x2', '\x27A', 'W', '\x3', '\x2', '\x2', '\x2', '\x27B', '\x27D', + '\x5', '\xD0', 'i', '\x2', '\x27C', '\x27B', '\x3', '\x2', '\x2', '\x2', + '\x27C', '\x27D', '\x3', '\x2', '\x2', '\x2', '\x27D', '\x27F', '\x3', + '\x2', '\x2', '\x2', '\x27E', '\x280', '\x5', '\xDC', 'o', '\x2', '\x27F', + '\x27E', '\x3', '\x2', '\x2', '\x2', '\x27F', '\x280', '\x3', '\x2', '\x2', + '\x2', '\x280', '\x282', '\x3', '\x2', '\x2', '\x2', '\x281', '\x283', + '\x5', '`', '\x31', '\x2', '\x282', '\x281', '\x3', '\x2', '\x2', '\x2', + '\x282', '\x283', '\x3', '\x2', '\x2', '\x2', '\x283', '\x284', '\x3', + '\x2', '\x2', '\x2', '\x284', '\x285', '\a', '\x6', '\x2', '\x2', '\x285', + '\x287', '\x5', 'Z', '.', '\x2', '\x286', '\x288', '\x5', '\x11A', '\x8E', + '\x2', '\x287', '\x286', '\x3', '\x2', '\x2', '\x2', '\x287', '\x288', + '\x3', '\x2', '\x2', '\x2', '\x288', '\x28A', '\x3', '\x2', '\x2', '\x2', + '\x289', '\x28B', '\x5', '\xC4', '\x63', '\x2', '\x28A', '\x289', '\x3', + '\x2', '\x2', '\x2', '\x28A', '\x28B', '\x3', '\x2', '\x2', '\x2', '\x28B', + '\x28D', '\x3', '\x2', '\x2', '\x2', '\x28C', '\x28E', '\x5', '\x120', + '\x91', '\x2', '\x28D', '\x28C', '\x3', '\x2', '\x2', '\x2', '\x28D', + '\x28E', '\x3', '\x2', '\x2', '\x2', '\x28E', '\x28F', '\x3', '\x2', '\x2', + '\x2', '\x28F', '\x290', '\x5', '\\', '/', '\x2', '\x290', '\x2A6', '\x3', + '\x2', '\x2', '\x2', '\x291', '\x293', '\x5', '\xD0', 'i', '\x2', '\x292', + '\x291', '\x3', '\x2', '\x2', '\x2', '\x292', '\x293', '\x3', '\x2', '\x2', + '\x2', '\x293', '\x294', '\x3', '\x2', '\x2', '\x2', '\x294', '\x296', + '\x5', '`', '\x31', '\x2', '\x295', '\x297', '\x5', '\xDC', 'o', '\x2', + '\x296', '\x295', '\x3', '\x2', '\x2', '\x2', '\x296', '\x297', '\x3', + '\x2', '\x2', '\x2', '\x297', '\x298', '\x3', '\x2', '\x2', '\x2', '\x298', + '\x299', '\a', '\x6', '\x2', '\x2', '\x299', '\x29B', '\x5', 'Z', '.', + '\x2', '\x29A', '\x29C', '\x5', '\x11A', '\x8E', '\x2', '\x29B', '\x29A', + '\x3', '\x2', '\x2', '\x2', '\x29B', '\x29C', '\x3', '\x2', '\x2', '\x2', + '\x29C', '\x29E', '\x3', '\x2', '\x2', '\x2', '\x29D', '\x29F', '\x5', + '\xC4', '\x63', '\x2', '\x29E', '\x29D', '\x3', '\x2', '\x2', '\x2', '\x29E', + '\x29F', '\x3', '\x2', '\x2', '\x2', '\x29F', '\x2A1', '\x3', '\x2', '\x2', + '\x2', '\x2A0', '\x2A2', '\x5', '\x120', '\x91', '\x2', '\x2A1', '\x2A0', + '\x3', '\x2', '\x2', '\x2', '\x2A1', '\x2A2', '\x3', '\x2', '\x2', '\x2', + '\x2A2', '\x2A3', '\x3', '\x2', '\x2', '\x2', '\x2A3', '\x2A4', '\x5', + '\\', '/', '\x2', '\x2A4', '\x2A6', '\x3', '\x2', '\x2', '\x2', '\x2A5', + '\x27C', '\x3', '\x2', '\x2', '\x2', '\x2A5', '\x292', '\x3', '\x2', '\x2', + '\x2', '\x2A6', 'Y', '\x3', '\x2', '\x2', '\x2', '\x2A7', '\x2A8', '\x5', + '\xC2', '\x62', '\x2', '\x2A8', '[', '\x3', '\x2', '\x2', '\x2', '\x2A9', + '\x2AD', '\a', '\x90', '\x2', '\x2', '\x2AA', '\x2AC', '\x5', '^', '\x30', + '\x2', '\x2AB', '\x2AA', '\x3', '\x2', '\x2', '\x2', '\x2AC', '\x2AF', + '\x3', '\x2', '\x2', '\x2', '\x2AD', '\x2AB', '\x3', '\x2', '\x2', '\x2', + '\x2AD', '\x2AE', '\x3', '\x2', '\x2', '\x2', '\x2AE', '\x2B0', '\x3', + '\x2', '\x2', '\x2', '\x2AF', '\x2AD', '\x3', '\x2', '\x2', '\x2', '\x2B0', + '\x2B1', '\a', '\x91', '\x2', '\x2', '\x2B1', ']', '\x3', '\x2', '\x2', + '\x2', '\x2B2', '\x2B3', '\x5', '\n', '\x6', '\x2', '\x2B3', '_', '\x3', + '\x2', '\x2', '\x2', '\x2B4', '\x2B5', '\a', '\x10', '\x2', '\x2', '\x2B5', + '\x61', '\x3', '\x2', '\x2', '\x2', '\x2B6', '\x2B8', '\x5', '\xD0', 'i', + '\x2', '\x2B7', '\x2B6', '\x3', '\x2', '\x2', '\x2', '\x2B7', '\x2B8', + '\x3', '\x2', '\x2', '\x2', '\x2B8', '\x2BA', '\x3', '\x2', '\x2', '\x2', + '\x2B9', '\x2BB', '\x5', '\xDC', 'o', '\x2', '\x2BA', '\x2B9', '\x3', + '\x2', '\x2', '\x2', '\x2BA', '\x2BB', '\x3', '\x2', '\x2', '\x2', '\x2BB', + '\x2BC', '\x3', '\x2', '\x2', '\x2', '\x2BC', '\x2BD', '\a', '\b', '\x2', + '\x2', '\x2BD', '\x2BF', '\x5', '\x64', '\x33', '\x2', '\x2BE', '\x2C0', + '\x5', '\xC4', '\x63', '\x2', '\x2BF', '\x2BE', '\x3', '\x2', '\x2', '\x2', + '\x2BF', '\x2C0', '\x3', '\x2', '\x2', '\x2', '\x2C0', '\x2C1', '\x3', + '\x2', '\x2', '\x2', '\x2C1', '\x2C2', '\x5', '\x66', '\x34', '\x2', '\x2C2', + '\x63', '\x3', '\x2', '\x2', '\x2', '\x2C3', '\x2C4', '\x5', '\xC2', '\x62', + '\x2', '\x2C4', '\x65', '\x3', '\x2', '\x2', '\x2', '\x2C5', '\x2C9', + '\a', '\x90', '\x2', '\x2', '\x2C6', '\x2C8', '\x5', 'h', '\x35', '\x2', + '\x2C7', '\x2C6', '\x3', '\x2', '\x2', '\x2', '\x2C8', '\x2CB', '\x3', + '\x2', '\x2', '\x2', '\x2C9', '\x2C7', '\x3', '\x2', '\x2', '\x2', '\x2C9', + '\x2CA', '\x3', '\x2', '\x2', '\x2', '\x2CA', '\x2CC', '\x3', '\x2', '\x2', + '\x2', '\x2CB', '\x2C9', '\x3', '\x2', '\x2', '\x2', '\x2CC', '\x2CD', + '\a', '\x91', '\x2', '\x2', '\x2CD', 'g', '\x3', '\x2', '\x2', '\x2', + '\x2CE', '\x2CF', '\x5', 'j', '\x36', '\x2', '\x2CF', 'i', '\x3', '\x2', + '\x2', '\x2', '\x2D0', '\x2D7', '\x5', '\x14', '\v', '\x2', '\x2D1', '\x2D7', + '\x5', '\x94', 'K', '\x2', '\x2D2', '\x2D7', '\x5', '\xA8', 'U', '\x2', + '\x2D3', '\x2D7', '\x5', '\x8C', 'G', '\x2', '\x2D4', '\x2D7', '\x5', + '\x92', 'J', '\x2', '\x2D5', '\x2D7', '\x5', '(', '\x15', '\x2', '\x2D6', + '\x2D0', '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D1', '\x3', '\x2', '\x2', + '\x2', '\x2D6', '\x2D2', '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D3', + '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D4', '\x3', '\x2', '\x2', '\x2', + '\x2D6', '\x2D5', '\x3', '\x2', '\x2', '\x2', '\x2D7', 'k', '\x3', '\x2', + '\x2', '\x2', '\x2D8', '\x2DC', '\x5', 'n', '\x38', '\x2', '\x2D9', '\x2DC', + '\x5', 'p', '\x39', '\x2', '\x2DA', '\x2DC', '\x5', 'r', ':', '\x2', '\x2DB', + '\x2D8', '\x3', '\x2', '\x2', '\x2', '\x2DB', '\x2D9', '\x3', '\x2', '\x2', + '\x2', '\x2DB', '\x2DA', '\x3', '\x2', '\x2', '\x2', '\x2DC', 'm', '\x3', + '\x2', '\x2', '\x2', '\x2DD', '\x2DE', '\a', '\x11', '\x2', '\x2', '\x2DE', + '\x2DF', '\a', '\x12', '\x2', '\x2', '\x2DF', '\x2E0', '\x5', '\x13A', + '\x9E', '\x2', '\x2E0', 'o', '\x3', '\x2', '\x2', '\x2', '\x2E1', '\x2E2', + '\a', '\x13', '\x2', '\x2', '\x2E2', '\x2E3', '\a', '\x12', '\x2', '\x2', + '\x2E3', '\x2E4', '\x5', '\x13A', '\x9E', '\x2', '\x2E4', 'q', '\x3', + '\x2', '\x2', '\x2', '\x2E5', '\x2E6', '\a', '\x14', '\x2', '\x2', '\x2E6', + '\x2E7', '\a', '\x12', '\x2', '\x2', '\x2E7', '\x2E9', '\x5', '\x13A', + '\x9E', '\x2', '\x2E8', '\x2EA', '\x5', 't', ';', '\x2', '\x2E9', '\x2E8', + '\x3', '\x2', '\x2', '\x2', '\x2E9', '\x2EA', '\x3', '\x2', '\x2', '\x2', + '\x2EA', 's', '\x3', '\x2', '\x2', '\x2', '\x2EB', '\x2EC', '\a', '\x86', + '\x2', '\x2', '\x2EC', '\x2ED', '\x5', '\x84', '\x43', '\x2', '\x2ED', + 'u', '\x3', '\x2', '\x2', '\x2', '\x2EE', '\x2EF', '\a', '\x15', '\x2', + '\x2', '\x2EF', '\x2F0', '\x5', '\x84', '\x43', '\x2', '\x2F0', '\x2F4', + '\a', '\x90', '\x2', '\x2', '\x2F1', '\x2F3', '\x5', 'x', '=', '\x2', + '\x2F2', '\x2F1', '\x3', '\x2', '\x2', '\x2', '\x2F3', '\x2F6', '\x3', + '\x2', '\x2', '\x2', '\x2F4', '\x2F2', '\x3', '\x2', '\x2', '\x2', '\x2F4', + '\x2F5', '\x3', '\x2', '\x2', '\x2', '\x2F5', '\x2F7', '\x3', '\x2', '\x2', + '\x2', '\x2F6', '\x2F4', '\x3', '\x2', '\x2', '\x2', '\x2F7', '\x2F8', + '\a', '\x91', '\x2', '\x2', '\x2F8', 'w', '\x3', '\x2', '\x2', '\x2', + '\x2F9', '\x2FD', '\x5', 'z', '>', '\x2', '\x2FA', '\x2FD', '\x5', '|', + '?', '\x2', '\x2FB', '\x2FD', '\x5', '~', '@', '\x2', '\x2FC', '\x2F9', + '\x3', '\x2', '\x2', '\x2', '\x2FC', '\x2FA', '\x3', '\x2', '\x2', '\x2', + '\x2FC', '\x2FB', '\x3', '\x2', '\x2', '\x2', '\x2FD', 'y', '\x3', '\x2', + '\x2', '\x2', '\x2FE', '\x2FF', '\a', '\x16', '\x2', '\x2', '\x2FF', '\x300', + '\a', '\x86', '\x2', '\x2', '\x300', '\x305', '\x5', '\x82', '\x42', '\x2', + '\x301', '\x302', '\a', '\x17', '\x2', '\x2', '\x302', '\x303', '\a', + '\x86', '\x2', '\x2', '\x303', '\x305', '\x5', '\x82', '\x42', '\x2', + '\x304', '\x2FE', '\x3', '\x2', '\x2', '\x2', '\x304', '\x301', '\x3', + '\x2', '\x2', '\x2', '\x305', '{', '\x3', '\x2', '\x2', '\x2', '\x306', + '\x307', '\a', '\x18', '\x2', '\x2', '\x307', '\x308', '\a', '\x86', '\x2', + '\x2', '\x308', '\x309', '\x5', '\x110', '\x89', '\x2', '\x309', '}', + '\x3', '\x2', '\x2', '\x2', '\x30A', '\x30B', '\a', '\x19', '\x2', '\x2', + '\x30B', '\x30C', '\a', '\x86', '\x2', '\x2', '\x30C', '\x30D', '\x5', + '\x80', '\x41', '\x2', '\x30D', '\x7F', '\x3', '\x2', '\x2', '\x2', '\x30E', + '\x30F', '\t', '\x3', '\x2', '\x2', '\x30F', '\x81', '\x3', '\x2', '\x2', + '\x2', '\x310', '\x315', '\x5', '\x84', '\x43', '\x2', '\x311', '\x312', + '\a', '\x84', '\x2', '\x2', '\x312', '\x314', '\x5', '\x84', '\x43', '\x2', + '\x313', '\x311', '\x3', '\x2', '\x2', '\x2', '\x314', '\x317', '\x3', + '\x2', '\x2', '\x2', '\x315', '\x313', '\x3', '\x2', '\x2', '\x2', '\x315', + '\x316', '\x3', '\x2', '\x2', '\x2', '\x316', '\x83', '\x3', '\x2', '\x2', + '\x2', '\x317', '\x315', '\x3', '\x2', '\x2', '\x2', '\x318', '\x319', + '\x5', '\xC2', '\x62', '\x2', '\x319', '\x85', '\x3', '\x2', '\x2', '\x2', + '\x31A', '\x31C', '\x5', '\xD0', 'i', '\x2', '\x31B', '\x31A', '\x3', + '\x2', '\x2', '\x2', '\x31B', '\x31C', '\x3', '\x2', '\x2', '\x2', '\x31C', + '\x31E', '\x3', '\x2', '\x2', '\x2', '\x31D', '\x31F', '\x5', '\xDC', + 'o', '\x2', '\x31E', '\x31D', '\x3', '\x2', '\x2', '\x2', '\x31E', '\x31F', + '\x3', '\x2', '\x2', '\x2', '\x31F', '\x320', '\x3', '\x2', '\x2', '\x2', + '\x320', '\x321', '\a', '\x1D', '\x2', '\x2', '\x321', '\x323', '\x5', + '\xF8', '}', '\x2', '\x322', '\x324', '\x5', '\xC4', '\x63', '\x2', '\x323', + '\x322', '\x3', '\x2', '\x2', '\x2', '\x323', '\x324', '\x3', '\x2', '\x2', + '\x2', '\x324', '\x325', '\x3', '\x2', '\x2', '\x2', '\x325', '\x326', + '\x5', '\x88', '\x45', '\x2', '\x326', '\x333', '\x3', '\x2', '\x2', '\x2', + '\x327', '\x329', '\x5', '\xD0', 'i', '\x2', '\x328', '\x327', '\x3', + '\x2', '\x2', '\x2', '\x328', '\x329', '\x3', '\x2', '\x2', '\x2', '\x329', + '\x32B', '\x3', '\x2', '\x2', '\x2', '\x32A', '\x32C', '\x5', '\xDC', + 'o', '\x2', '\x32B', '\x32A', '\x3', '\x2', '\x2', '\x2', '\x32B', '\x32C', + '\x3', '\x2', '\x2', '\x2', '\x32C', '\x32D', '\x3', '\x2', '\x2', '\x2', + '\x32D', '\x32E', '\a', '\x1D', '\x2', '\x2', '\x32E', '\x32F', '\x5', + '\xF8', '}', '\x2', '\x32F', '\x330', '\x5', '\x120', '\x91', '\x2', '\x330', + '\x331', '\x5', '\x88', '\x45', '\x2', '\x331', '\x333', '\x3', '\x2', + '\x2', '\x2', '\x332', '\x31B', '\x3', '\x2', '\x2', '\x2', '\x332', '\x328', + '\x3', '\x2', '\x2', '\x2', '\x333', '\x87', '\x3', '\x2', '\x2', '\x2', + '\x334', '\x338', '\a', '\x90', '\x2', '\x2', '\x335', '\x337', '\x5', + '\x8A', '\x46', '\x2', '\x336', '\x335', '\x3', '\x2', '\x2', '\x2', '\x337', + '\x33A', '\x3', '\x2', '\x2', '\x2', '\x338', '\x336', '\x3', '\x2', '\x2', + '\x2', '\x338', '\x339', '\x3', '\x2', '\x2', '\x2', '\x339', '\x33B', + '\x3', '\x2', '\x2', '\x2', '\x33A', '\x338', '\x3', '\x2', '\x2', '\x2', + '\x33B', '\x33C', '\a', '\x91', '\x2', '\x2', '\x33C', '\x89', '\x3', + '\x2', '\x2', '\x2', '\x33D', '\x33E', '\x5', '\b', '\x5', '\x2', '\x33E', + '\x8B', '\x3', '\x2', '\x2', '\x2', '\x33F', '\x340', '\x5', '\x8E', 'H', + '\x2', '\x340', '\x341', '\x5', '\x90', 'I', '\x2', '\x341', '\x347', + '\x3', '\x2', '\x2', '\x2', '\x342', '\x343', '\x5', '\x8E', 'H', '\x2', + '\x343', '\x344', '\x5', '\x90', 'I', '\x2', '\x344', '\x345', '\x5', + ' ', '\x11', '\x2', '\x345', '\x347', '\x3', '\x2', '\x2', '\x2', '\x346', + '\x33F', '\x3', '\x2', '\x2', '\x2', '\x346', '\x342', '\x3', '\x2', '\x2', + '\x2', '\x347', '\x8D', '\x3', '\x2', '\x2', '\x2', '\x348', '\x34A', + '\x5', '\xD0', 'i', '\x2', '\x349', '\x348', '\x3', '\x2', '\x2', '\x2', + '\x349', '\x34A', '\x3', '\x2', '\x2', '\x2', '\x34A', '\x34C', '\x3', + '\x2', '\x2', '\x2', '\x34B', '\x34D', '\x5', '\xDA', 'n', '\x2', '\x34C', + '\x34B', '\x3', '\x2', '\x2', '\x2', '\x34C', '\x34D', '\x3', '\x2', '\x2', + '\x2', '\x34D', '\x34E', '\x3', '\x2', '\x2', '\x2', '\x34E', '\x34F', + '\a', '\x1E', '\x2', '\x2', '\x34F', '\x350', '\x5', '\xAE', 'X', '\x2', + '\x350', '\x8F', '\x3', '\x2', '\x2', '\x2', '\x351', '\x353', '\x5', + '\x132', '\x9A', '\x2', '\x352', '\x354', '\x5', '\xD0', 'i', '\x2', '\x353', + '\x352', '\x3', '\x2', '\x2', '\x2', '\x353', '\x354', '\x3', '\x2', '\x2', + '\x2', '\x354', '\x355', '\x3', '\x2', '\x2', '\x2', '\x355', '\x356', + '\x5', '\xF0', 'y', '\x2', '\x356', '\x91', '\x3', '\x2', '\x2', '\x2', + '\x357', '\x359', '\x5', '\xD0', 'i', '\x2', '\x358', '\x357', '\x3', + '\x2', '\x2', '\x2', '\x358', '\x359', '\x3', '\x2', '\x2', '\x2', '\x359', + '\x35B', '\x3', '\x2', '\x2', '\x2', '\x35A', '\x35C', '\x5', '\xDC', + 'o', '\x2', '\x35B', '\x35A', '\x3', '\x2', '\x2', '\x2', '\x35B', '\x35C', + '\x3', '\x2', '\x2', '\x2', '\x35C', '\x35D', '\x3', '\x2', '\x2', '\x2', + '\x35D', '\x35E', '\a', '\x1F', '\x2', '\x2', '\x35E', '\x360', '\x5', + '*', '\x16', '\x2', '\x35F', '\x361', '\x5', '\xC4', '\x63', '\x2', '\x360', + '\x35F', '\x3', '\x2', '\x2', '\x2', '\x360', '\x361', '\x3', '\x2', '\x2', + '\x2', '\x361', '\x363', '\x3', '\x2', '\x2', '\x2', '\x362', '\x364', + '\x5', ',', '\x17', '\x2', '\x363', '\x362', '\x3', '\x2', '\x2', '\x2', + '\x363', '\x364', '\x3', '\x2', '\x2', '\x2', '\x364', '\x366', '\x3', + '\x2', '\x2', '\x2', '\x365', '\x367', '\x5', '\x120', '\x91', '\x2', + '\x366', '\x365', '\x3', '\x2', '\x2', '\x2', '\x366', '\x367', '\x3', + '\x2', '\x2', '\x2', '\x367', '\x93', '\x3', '\x2', '\x2', '\x2', '\x368', + '\x369', '\x5', '\x96', 'L', '\x2', '\x369', '\x36B', '\x5', '\x98', 'M', + '\x2', '\x36A', '\x36C', '\x5', '\x11A', '\x8E', '\x2', '\x36B', '\x36A', + '\x3', '\x2', '\x2', '\x2', '\x36B', '\x36C', '\x3', '\x2', '\x2', '\x2', + '\x36C', '\x36D', '\x3', '\x2', '\x2', '\x2', '\x36D', '\x36F', '\x5', + '\x9E', 'P', '\x2', '\x36E', '\x370', '\x5', '\x120', '\x91', '\x2', '\x36F', + '\x36E', '\x3', '\x2', '\x2', '\x2', '\x36F', '\x370', '\x3', '\x2', '\x2', + '\x2', '\x370', '\x372', '\x3', '\x2', '\x2', '\x2', '\x371', '\x373', + '\x5', '\x9A', 'N', '\x2', '\x372', '\x371', '\x3', '\x2', '\x2', '\x2', + '\x372', '\x373', '\x3', '\x2', '\x2', '\x2', '\x373', '\x95', '\x3', + '\x2', '\x2', '\x2', '\x374', '\x376', '\x5', '\xD0', 'i', '\x2', '\x375', + '\x374', '\x3', '\x2', '\x2', '\x2', '\x375', '\x376', '\x3', '\x2', '\x2', + '\x2', '\x376', '\x378', '\x3', '\x2', '\x2', '\x2', '\x377', '\x379', + '\x5', '\xDA', 'n', '\x2', '\x378', '\x377', '\x3', '\x2', '\x2', '\x2', + '\x378', '\x379', '\x3', '\x2', '\x2', '\x2', '\x379', '\x37A', '\x3', + '\x2', '\x2', '\x2', '\x37A', '\x37B', '\a', '\n', '\x2', '\x2', '\x37B', + '\x97', '\x3', '\x2', '\x2', '\x2', '\x37C', '\x37F', '\x5', '\xC2', '\x62', + '\x2', '\x37D', '\x37F', '\x5', '\x9C', 'O', '\x2', '\x37E', '\x37C', + '\x3', '\x2', '\x2', '\x2', '\x37E', '\x37D', '\x3', '\x2', '\x2', '\x2', + '\x37F', '\x99', '\x3', '\x2', '\x2', '\x2', '\x380', '\x384', '\a', '\x90', + '\x2', '\x2', '\x381', '\x383', '\x5', '\xBC', '_', '\x2', '\x382', '\x381', + '\x3', '\x2', '\x2', '\x2', '\x383', '\x386', '\x3', '\x2', '\x2', '\x2', + '\x384', '\x382', '\x3', '\x2', '\x2', '\x2', '\x384', '\x385', '\x3', + '\x2', '\x2', '\x2', '\x385', '\x387', '\x3', '\x2', '\x2', '\x2', '\x386', + '\x384', '\x3', '\x2', '\x2', '\x2', '\x387', '\x388', '\a', '\x91', '\x2', + '\x2', '\x388', '\x9B', '\x3', '\x2', '\x2', '\x2', '\x389', '\x38A', + '\x5', '\x13A', '\x9E', '\x2', '\x38A', '\x9D', '\x3', '\x2', '\x2', '\x2', + '\x38B', '\x38D', '\x5', '\xAE', 'X', '\x2', '\x38C', '\x38E', '\x5', + '\xA0', 'Q', '\x2', '\x38D', '\x38C', '\x3', '\x2', '\x2', '\x2', '\x38D', + '\x38E', '\x3', '\x2', '\x2', '\x2', '\x38E', '\x390', '\x3', '\x2', '\x2', + '\x2', '\x38F', '\x391', '\x5', '\xA2', 'R', '\x2', '\x390', '\x38F', + '\x3', '\x2', '\x2', '\x2', '\x390', '\x391', '\x3', '\x2', '\x2', '\x2', + '\x391', '\x393', '\x3', '\x2', '\x2', '\x2', '\x392', '\x394', '\x5', + '\xA6', 'T', '\x2', '\x393', '\x392', '\x3', '\x2', '\x2', '\x2', '\x393', + '\x394', '\x3', '\x2', '\x2', '\x2', '\x394', '\x39E', '\x3', '\x2', '\x2', + '\x2', '\x395', '\x397', '\x5', '\xAE', 'X', '\x2', '\x396', '\x398', + '\x5', '\xA0', 'Q', '\x2', '\x397', '\x396', '\x3', '\x2', '\x2', '\x2', + '\x397', '\x398', '\x3', '\x2', '\x2', '\x2', '\x398', '\x399', '\x3', + '\x2', '\x2', '\x2', '\x399', '\x39B', '\x5', '\xA4', 'S', '\x2', '\x39A', + '\x39C', '\x5', '\xA6', 'T', '\x2', '\x39B', '\x39A', '\x3', '\x2', '\x2', + '\x2', '\x39B', '\x39C', '\x3', '\x2', '\x2', '\x2', '\x39C', '\x39E', + '\x3', '\x2', '\x2', '\x2', '\x39D', '\x38B', '\x3', '\x2', '\x2', '\x2', + '\x39D', '\x395', '\x3', '\x2', '\x2', '\x2', '\x39E', '\x9F', '\x3', + '\x2', '\x2', '\x2', '\x39F', '\x3A0', '\a', ' ', '\x2', '\x2', '\x3A0', + '\xA1', '\x3', '\x2', '\x2', '\x2', '\x3A1', '\x3A2', '\a', '!', '\x2', + '\x2', '\x3A2', '\xA3', '\x3', '\x2', '\x2', '\x2', '\x3A3', '\x3A4', + '\a', '\"', '\x2', '\x2', '\x3A4', '\xA5', '\x3', '\x2', '\x2', '\x2', + '\x3A5', '\x3A7', '\x5', '\x132', '\x9A', '\x2', '\x3A6', '\x3A8', '\x5', + '\xD0', 'i', '\x2', '\x3A7', '\x3A6', '\x3', '\x2', '\x2', '\x2', '\x3A7', + '\x3A8', '\x3', '\x2', '\x2', '\x2', '\x3A8', '\x3A9', '\x3', '\x2', '\x2', + '\x2', '\x3A9', '\x3AA', '\x5', '\xF0', 'y', '\x2', '\x3AA', '\xA7', '\x3', + '\x2', '\x2', '\x2', '\x3AB', '\x3AD', '\x5', '\xAA', 'V', '\x2', '\x3AC', + '\x3AE', '\x5', '\x11A', '\x8E', '\x2', '\x3AD', '\x3AC', '\x3', '\x2', + '\x2', '\x2', '\x3AD', '\x3AE', '\x3', '\x2', '\x2', '\x2', '\x3AE', '\x3AF', + '\x3', '\x2', '\x2', '\x2', '\x3AF', '\x3B1', '\x5', '\xAE', 'X', '\x2', + '\x3B0', '\x3B2', '\x5', '\xA2', 'R', '\x2', '\x3B1', '\x3B0', '\x3', + '\x2', '\x2', '\x2', '\x3B1', '\x3B2', '\x3', '\x2', '\x2', '\x2', '\x3B2', + '\x3B4', '\x3', '\x2', '\x2', '\x2', '\x3B3', '\x3B5', '\x5', '\x120', + '\x91', '\x2', '\x3B4', '\x3B3', '\x3', '\x2', '\x2', '\x2', '\x3B4', + '\x3B5', '\x3', '\x2', '\x2', '\x2', '\x3B5', '\x3C0', '\x3', '\x2', '\x2', + '\x2', '\x3B6', '\x3B8', '\x5', '\xAA', 'V', '\x2', '\x3B7', '\x3B9', + '\x5', '\x11A', '\x8E', '\x2', '\x3B8', '\x3B7', '\x3', '\x2', '\x2', + '\x2', '\x3B8', '\x3B9', '\x3', '\x2', '\x2', '\x2', '\x3B9', '\x3BA', + '\x3', '\x2', '\x2', '\x2', '\x3BA', '\x3BB', '\x5', '\xAE', 'X', '\x2', + '\x3BB', '\x3BD', '\x5', '\xA4', 'S', '\x2', '\x3BC', '\x3BE', '\x5', + '\x120', '\x91', '\x2', '\x3BD', '\x3BC', '\x3', '\x2', '\x2', '\x2', + '\x3BD', '\x3BE', '\x3', '\x2', '\x2', '\x2', '\x3BE', '\x3C0', '\x3', + '\x2', '\x2', '\x2', '\x3BF', '\x3AB', '\x3', '\x2', '\x2', '\x2', '\x3BF', + '\x3B6', '\x3', '\x2', '\x2', '\x2', '\x3C0', '\xA9', '\x3', '\x2', '\x2', + '\x2', '\x3C1', '\x3C3', '\x5', '\xD0', 'i', '\x2', '\x3C2', '\x3C1', + '\x3', '\x2', '\x2', '\x2', '\x3C2', '\x3C3', '\x3', '\x2', '\x2', '\x2', + '\x3C3', '\x3C5', '\x3', '\x2', '\x2', '\x2', '\x3C4', '\x3C6', '\x5', + '\xDA', 'n', '\x2', '\x3C5', '\x3C4', '\x3', '\x2', '\x2', '\x2', '\x3C5', + '\x3C6', '\x3', '\x2', '\x2', '\x2', '\x3C6', '\x3C7', '\x3', '\x2', '\x2', + '\x2', '\x3C7', '\x3D9', '\a', '#', '\x2', '\x2', '\x3C8', '\x3CA', '\x5', + '\xD0', 'i', '\x2', '\x3C9', '\x3C8', '\x3', '\x2', '\x2', '\x2', '\x3C9', + '\x3CA', '\x3', '\x2', '\x2', '\x2', '\x3CA', '\x3CC', '\x3', '\x2', '\x2', + '\x2', '\x3CB', '\x3CD', '\x5', '\xDA', 'n', '\x2', '\x3CC', '\x3CB', + '\x3', '\x2', '\x2', '\x2', '\x3CC', '\x3CD', '\x3', '\x2', '\x2', '\x2', + '\x3CD', '\x3CE', '\x3', '\x2', '\x2', '\x2', '\x3CE', '\x3CF', '\a', + '#', '\x2', '\x2', '\x3CF', '\x3D9', '\a', '\x80', '\x2', '\x2', '\x3D0', + '\x3D2', '\x5', '\xD0', 'i', '\x2', '\x3D1', '\x3D0', '\x3', '\x2', '\x2', + '\x2', '\x3D1', '\x3D2', '\x3', '\x2', '\x2', '\x2', '\x3D2', '\x3D4', + '\x3', '\x2', '\x2', '\x2', '\x3D3', '\x3D5', '\x5', '\xDA', 'n', '\x2', + '\x3D4', '\x3D3', '\x3', '\x2', '\x2', '\x2', '\x3D4', '\x3D5', '\x3', + '\x2', '\x2', '\x2', '\x3D5', '\x3D6', '\x3', '\x2', '\x2', '\x2', '\x3D6', + '\x3D7', '\a', '#', '\x2', '\x2', '\x3D7', '\x3D9', '\a', '\x82', '\x2', + '\x2', '\x3D8', '\x3C2', '\x3', '\x2', '\x2', '\x2', '\x3D8', '\x3C9', + '\x3', '\x2', '\x2', '\x2', '\x3D8', '\x3D1', '\x3', '\x2', '\x2', '\x2', + '\x3D9', '\xAB', '\x3', '\x2', '\x2', '\x2', '\x3DA', '\x3DC', '\x5', + '\xD0', 'i', '\x2', '\x3DB', '\x3DA', '\x3', '\x2', '\x2', '\x2', '\x3DB', + '\x3DC', '\x3', '\x2', '\x2', '\x2', '\x3DC', '\x3DE', '\x3', '\x2', '\x2', + '\x2', '\x3DD', '\x3DF', '\x5', '\xDA', 'n', '\x2', '\x3DE', '\x3DD', + '\x3', '\x2', '\x2', '\x2', '\x3DE', '\x3DF', '\x3', '\x2', '\x2', '\x2', + '\x3DF', '\x3E0', '\x3', '\x2', '\x2', '\x2', '\x3E0', '\x3E1', '\a', + '$', '\x2', '\x2', '\x3E1', '\xAD', '\x3', '\x2', '\x2', '\x2', '\x3E2', + '\x3E3', '\a', '\x8C', '\x2', '\x2', '\x3E3', '\x3E9', '\a', '\x8D', '\x2', + '\x2', '\x3E4', '\x3E5', '\a', '\x8C', '\x2', '\x2', '\x3E5', '\x3E6', + '\x5', '\xB0', 'Y', '\x2', '\x3E6', '\x3E7', '\a', '\x8D', '\x2', '\x2', + '\x3E7', '\x3E9', '\x3', '\x2', '\x2', '\x2', '\x3E8', '\x3E2', '\x3', + '\x2', '\x2', '\x2', '\x3E8', '\x3E4', '\x3', '\x2', '\x2', '\x2', '\x3E9', + '\xAF', '\x3', '\x2', '\x2', '\x2', '\x3EA', '\x3EF', '\x5', '\xB2', 'Z', + '\x2', '\x3EB', '\x3EC', '\a', '\x84', '\x2', '\x2', '\x3EC', '\x3EE', + '\x5', '\xB2', 'Z', '\x2', '\x3ED', '\x3EB', '\x3', '\x2', '\x2', '\x2', + '\x3EE', '\x3F1', '\x3', '\x2', '\x2', '\x2', '\x3EF', '\x3ED', '\x3', + '\x2', '\x2', '\x2', '\x3EF', '\x3F0', '\x3', '\x2', '\x2', '\x2', '\x3F0', + '\xB1', '\x3', '\x2', '\x2', '\x2', '\x3F1', '\x3EF', '\x3', '\x2', '\x2', + '\x2', '\x3F2', '\x3F4', '\x5', '\xB4', '[', '\x2', '\x3F3', '\x3F2', + '\x3', '\x2', '\x2', '\x2', '\x3F3', '\x3F4', '\x3', '\x2', '\x2', '\x2', + '\x3F4', '\x3F5', '\x3', '\x2', '\x2', '\x2', '\x3F5', '\x3F6', '\x5', + '\xB6', '\\', '\x2', '\x3F6', '\x3F8', '\x5', '\xF2', 'z', '\x2', '\x3F7', + '\x3F9', '\x5', '\xB8', ']', '\x2', '\x3F8', '\x3F7', '\x3', '\x2', '\x2', + '\x2', '\x3F8', '\x3F9', '\x3', '\x2', '\x2', '\x2', '\x3F9', '\x402', + '\x3', '\x2', '\x2', '\x2', '\x3FA', '\x3FC', '\x5', '\xB4', '[', '\x2', + '\x3FB', '\x3FA', '\x3', '\x2', '\x2', '\x2', '\x3FB', '\x3FC', '\x3', + '\x2', '\x2', '\x2', '\x3FC', '\x3FD', '\x3', '\x2', '\x2', '\x2', '\x3FD', + '\x3FE', '\x5', '\xB6', '\\', '\x2', '\x3FE', '\x3FF', '\x5', '\xF2', + 'z', '\x2', '\x3FF', '\x400', '\x5', '\x134', '\x9B', '\x2', '\x400', + '\x402', '\x3', '\x2', '\x2', '\x2', '\x401', '\x3F3', '\x3', '\x2', '\x2', + '\x2', '\x401', '\x3FB', '\x3', '\x2', '\x2', '\x2', '\x402', '\xB3', + '\x3', '\x2', '\x2', '\x2', '\x403', '\x404', '\x5', '\x118', '\x8D', + '\x2', '\x404', '\xB5', '\x3', '\x2', '\x2', '\x2', '\x405', '\x406', + '\x5', '\x118', '\x8D', '\x2', '\x406', '\xB7', '\x3', '\x2', '\x2', '\x2', + '\x407', '\x409', '\a', '~', '\x2', '\x2', '\x408', '\x40A', '\x5', '\xBA', + '^', '\x2', '\x409', '\x408', '\x3', '\x2', '\x2', '\x2', '\x40A', '\x40B', + '\x3', '\x2', '\x2', '\x2', '\x40B', '\x409', '\x3', '\x2', '\x2', '\x2', + '\x40B', '\x40C', '\x3', '\x2', '\x2', '\x2', '\x40C', '\xB9', '\x3', + '\x2', '\x2', '\x2', '\x40D', '\x411', '\a', '\x8C', '\x2', '\x2', '\x40E', + '\x410', '\x5', '\xBC', '_', '\x2', '\x40F', '\x40E', '\x3', '\x2', '\x2', + '\x2', '\x410', '\x413', '\x3', '\x2', '\x2', '\x2', '\x411', '\x40F', + '\x3', '\x2', '\x2', '\x2', '\x411', '\x412', '\x3', '\x2', '\x2', '\x2', + '\x412', '\x414', '\x3', '\x2', '\x2', '\x2', '\x413', '\x411', '\x3', + '\x2', '\x2', '\x2', '\x414', '\x42A', '\a', '\x8D', '\x2', '\x2', '\x415', + '\x419', '\a', '\x8E', '\x2', '\x2', '\x416', '\x418', '\x5', '\xBC', + '_', '\x2', '\x417', '\x416', '\x3', '\x2', '\x2', '\x2', '\x418', '\x41B', + '\x3', '\x2', '\x2', '\x2', '\x419', '\x417', '\x3', '\x2', '\x2', '\x2', + '\x419', '\x41A', '\x3', '\x2', '\x2', '\x2', '\x41A', '\x41C', '\x3', + '\x2', '\x2', '\x2', '\x41B', '\x419', '\x3', '\x2', '\x2', '\x2', '\x41C', + '\x42A', '\a', '\x8F', '\x2', '\x2', '\x41D', '\x421', '\a', '\x90', '\x2', + '\x2', '\x41E', '\x420', '\x5', '\xBC', '_', '\x2', '\x41F', '\x41E', + '\x3', '\x2', '\x2', '\x2', '\x420', '\x423', '\x3', '\x2', '\x2', '\x2', + '\x421', '\x41F', '\x3', '\x2', '\x2', '\x2', '\x421', '\x422', '\x3', + '\x2', '\x2', '\x2', '\x422', '\x424', '\x3', '\x2', '\x2', '\x2', '\x423', + '\x421', '\x3', '\x2', '\x2', '\x2', '\x424', '\x42A', '\a', '\x91', '\x2', + '\x2', '\x425', '\x42A', '\x5', '\x118', '\x8D', '\x2', '\x426', '\x42A', + '\x5', '\x10C', '\x87', '\x2', '\x427', '\x42A', '\x5', '\x13A', '\x9E', + '\x2', '\x428', '\x42A', '\x5', '\xC0', '\x61', '\x2', '\x429', '\x40D', + '\x3', '\x2', '\x2', '\x2', '\x429', '\x415', '\x3', '\x2', '\x2', '\x2', + '\x429', '\x41D', '\x3', '\x2', '\x2', '\x2', '\x429', '\x425', '\x3', + '\x2', '\x2', '\x2', '\x429', '\x426', '\x3', '\x2', '\x2', '\x2', '\x429', + '\x427', '\x3', '\x2', '\x2', '\x2', '\x429', '\x428', '\x3', '\x2', '\x2', + '\x2', '\x42A', '\xBB', '\x3', '\x2', '\x2', '\x2', '\x42B', '\x42E', + '\x5', '\xBA', '^', '\x2', '\x42C', '\x42E', '\x5', '\xBE', '`', '\x2', + '\x42D', '\x42B', '\x3', '\x2', '\x2', '\x2', '\x42D', '\x42C', '\x3', + '\x2', '\x2', '\x2', '\x42E', '\xBD', '\x3', '\x2', '\x2', '\x2', '\x42F', + '\x441', '\a', '\x83', '\x2', '\x2', '\x430', '\x441', '\a', '\x84', '\x2', + '\x2', '\x431', '\x441', '\a', '\x86', '\x2', '\x2', '\x432', '\x441', + '\a', '\x87', '\x2', '\x2', '\x433', '\x441', '\a', '~', '\x2', '\x2', + '\x434', '\x441', '\a', '\x88', '\x2', '\x2', '\x435', '\x441', '\a', + '\x89', '\x2', '\x2', '\x436', '\x441', '\a', '\x8A', '\x2', '\x2', '\x437', + '\x441', '\a', '\x80', '\x2', '\x2', '\x438', '\x441', '\a', '\x8B', '\x2', + '\x2', '\x439', '\x441', '\a', '|', '\x2', '\x2', '\x43A', '\x441', '\a', + '}', '\x2', '\x2', '\x43B', '\x441', '\a', '\x7F', '\x2', '\x2', '\x43C', + '\x441', '\a', '\x82', '\x2', '\x2', '\x43D', '\x441', '\a', '\x85', '\x2', + '\x2', '\x43E', '\x441', '\a', '\x98', '\x2', '\x2', '\x43F', '\x441', + '\x5', '\x130', '\x99', '\x2', '\x440', '\x42F', '\x3', '\x2', '\x2', + '\x2', '\x440', '\x430', '\x3', '\x2', '\x2', '\x2', '\x440', '\x431', + '\x3', '\x2', '\x2', '\x2', '\x440', '\x432', '\x3', '\x2', '\x2', '\x2', + '\x440', '\x433', '\x3', '\x2', '\x2', '\x2', '\x440', '\x434', '\x3', + '\x2', '\x2', '\x2', '\x440', '\x435', '\x3', '\x2', '\x2', '\x2', '\x440', + '\x436', '\x3', '\x2', '\x2', '\x2', '\x440', '\x437', '\x3', '\x2', '\x2', + '\x2', '\x440', '\x438', '\x3', '\x2', '\x2', '\x2', '\x440', '\x439', + '\x3', '\x2', '\x2', '\x2', '\x440', '\x43A', '\x3', '\x2', '\x2', '\x2', + '\x440', '\x43B', '\x3', '\x2', '\x2', '\x2', '\x440', '\x43C', '\x3', + '\x2', '\x2', '\x2', '\x440', '\x43D', '\x3', '\x2', '\x2', '\x2', '\x440', + '\x43E', '\x3', '\x2', '\x2', '\x2', '\x440', '\x43F', '\x3', '\x2', '\x2', + '\x2', '\x441', '\x444', '\x3', '\x2', '\x2', '\x2', '\x442', '\x444', + '\x5', '\x132', '\x9A', '\x2', '\x443', '\x440', '\x3', '\x2', '\x2', + '\x2', '\x443', '\x442', '\x3', '\x2', '\x2', '\x2', '\x444', '\xBF', + '\x3', '\x2', '\x2', '\x2', '\x445', '\x446', '\a', '\x83', '\x2', '\x2', + '\x446', '\x447', '\x5', '\xC2', '\x62', '\x2', '\x447', '\xC1', '\x3', + '\x2', '\x2', '\x2', '\x448', '\x44B', '\a', 'y', '\x2', '\x2', '\x449', + '\x44B', '\x5', '\x136', '\x9C', '\x2', '\x44A', '\x448', '\x3', '\x2', + '\x2', '\x2', '\x44A', '\x449', '\x3', '\x2', '\x2', '\x2', '\x44B', '\xC3', + '\x3', '\x2', '\x2', '\x2', '\x44C', '\x44D', '\a', '\x86', '\x2', '\x2', + '\x44D', '\x44E', '\x5', '\xC8', '\x65', '\x2', '\x44E', '\x44F', '\a', + '\x84', '\x2', '\x2', '\x44F', '\x450', '\x5', '\xC6', '\x64', '\x2', + '\x450', '\x456', '\x3', '\x2', '\x2', '\x2', '\x451', '\x452', '\a', + '\x86', '\x2', '\x2', '\x452', '\x456', '\x5', '\xC8', '\x65', '\x2', + '\x453', '\x454', '\a', '\x86', '\x2', '\x2', '\x454', '\x456', '\x5', + '\xC6', '\x64', '\x2', '\x455', '\x44C', '\x3', '\x2', '\x2', '\x2', '\x455', + '\x451', '\x3', '\x2', '\x2', '\x2', '\x455', '\x453', '\x3', '\x2', '\x2', + '\x2', '\x456', '\xC5', '\x3', '\x2', '\x2', '\x2', '\x457', '\x45D', + '\x5', '\xF8', '}', '\x2', '\x458', '\x459', '\x5', '\xF8', '}', '\x2', + '\x459', '\x45A', '\a', '\x84', '\x2', '\x2', '\x45A', '\x45B', '\x5', + '\xC6', '\x64', '\x2', '\x45B', '\x45D', '\x3', '\x2', '\x2', '\x2', '\x45C', + '\x457', '\x3', '\x2', '\x2', '\x2', '\x45C', '\x458', '\x3', '\x2', '\x2', + '\x2', '\x45D', '\xC7', '\x3', '\x2', '\x2', '\x2', '\x45E', '\x45F', + '\a', '\x6', '\x2', '\x2', '\x45F', '\xC9', '\x3', '\x2', '\x2', '\x2', + '\x460', '\x461', '\a', '\x88', '\x2', '\x2', '\x461', '\x463', '\x5', + '\xCC', 'g', '\x2', '\x462', '\x464', '\x5', '\xCE', 'h', '\x2', '\x463', + '\x462', '\x3', '\x2', '\x2', '\x2', '\x463', '\x464', '\x3', '\x2', '\x2', + '\x2', '\x464', '\xCB', '\x3', '\x2', '\x2', '\x2', '\x465', '\x466', + '\x5', '\xF8', '}', '\x2', '\x466', '\xCD', '\x3', '\x2', '\x2', '\x2', + '\x467', '\x468', '\a', '\x8C', '\x2', '\x2', '\x468', '\x469', '\x5', + '\xD2', 'j', '\x2', '\x469', '\x46A', '\a', '\x8D', '\x2', '\x2', '\x46A', + '\xCF', '\x3', '\x2', '\x2', '\x2', '\x46B', '\x46D', '\x5', '\xCA', '\x66', + '\x2', '\x46C', '\x46B', '\x3', '\x2', '\x2', '\x2', '\x46D', '\x46E', + '\x3', '\x2', '\x2', '\x2', '\x46E', '\x46C', '\x3', '\x2', '\x2', '\x2', + '\x46E', '\x46F', '\x3', '\x2', '\x2', '\x2', '\x46F', '\xD1', '\x3', + '\x2', '\x2', '\x2', '\x470', '\x472', '\x5', '\xD4', 'k', '\x2', '\x471', + '\x470', '\x3', '\x2', '\x2', '\x2', '\x472', '\x475', '\x3', '\x2', '\x2', + '\x2', '\x473', '\x471', '\x3', '\x2', '\x2', '\x2', '\x473', '\x474', + '\x3', '\x2', '\x2', '\x2', '\x474', '\xD3', '\x3', '\x2', '\x2', '\x2', + '\x475', '\x473', '\x3', '\x2', '\x2', '\x2', '\x476', '\x477', '\a', + '\x8C', '\x2', '\x2', '\x477', '\x478', '\x5', '\xD2', 'j', '\x2', '\x478', + '\x479', '\a', '\x8D', '\x2', '\x2', '\x479', '\x487', '\x3', '\x2', '\x2', + '\x2', '\x47A', '\x47B', '\a', '\x8E', '\x2', '\x2', '\x47B', '\x47C', + '\x5', '\xD2', 'j', '\x2', '\x47C', '\x47D', '\a', '\x8F', '\x2', '\x2', + '\x47D', '\x487', '\x3', '\x2', '\x2', '\x2', '\x47E', '\x47F', '\a', + '\x90', '\x2', '\x2', '\x47F', '\x480', '\x5', '\xD2', 'j', '\x2', '\x480', + '\x481', '\a', '\x91', '\x2', '\x2', '\x481', '\x487', '\x3', '\x2', '\x2', + '\x2', '\x482', '\x487', '\x5', '\x118', '\x8D', '\x2', '\x483', '\x487', + '\x5', '\x10C', '\x87', '\x2', '\x484', '\x487', '\x5', '\x13A', '\x9E', + '\x2', '\x485', '\x487', '\x5', '\xD6', 'l', '\x2', '\x486', '\x476', + '\x3', '\x2', '\x2', '\x2', '\x486', '\x47A', '\x3', '\x2', '\x2', '\x2', + '\x486', '\x47E', '\x3', '\x2', '\x2', '\x2', '\x486', '\x482', '\x3', + '\x2', '\x2', '\x2', '\x486', '\x483', '\x3', '\x2', '\x2', '\x2', '\x486', + '\x484', '\x3', '\x2', '\x2', '\x2', '\x486', '\x485', '\x3', '\x2', '\x2', + '\x2', '\x487', '\xD5', '\x3', '\x2', '\x2', '\x2', '\x488', '\x48B', + '\t', '\x4', '\x2', '\x2', '\x489', '\x48B', '\x5', '\x132', '\x9A', '\x2', + '\x48A', '\x488', '\x3', '\x2', '\x2', '\x2', '\x48A', '\x489', '\x3', + '\x2', '\x2', '\x2', '\x48B', '\xD7', '\x3', '\x2', '\x2', '\x2', '\x48C', + '\x4A5', '\a', '\x6', '\x2', '\x2', '\x48D', '\x4A5', '\a', '%', '\x2', + '\x2', '\x48E', '\x4A5', '\a', '&', '\x2', '\x2', '\x48F', '\x4A5', '\a', + '\x10', '\x2', '\x2', '\x490', '\x4A5', '\a', '\x14', '\x2', '\x2', '\x491', + '\x4A5', '\a', '\'', '\x2', '\x2', '\x492', '\x4A5', '\a', '(', '\x2', + '\x2', '\x493', '\x4A5', '\a', ')', '\x2', '\x2', '\x494', '\x4A5', '\a', + '\x13', '\x2', '\x2', '\x495', '\x4A5', '\a', '\x11', '\x2', '\x2', '\x496', + '\x4A5', '\a', '*', '\x2', '\x2', '\x497', '\x4A5', '\a', '+', '\x2', + '\x2', '\x498', '\x4A5', '\a', ',', '\x2', '\x2', '\x499', '\x49A', '\a', + ',', '\x2', '\x2', '\x49A', '\x49B', '\a', '\x8C', '\x2', '\x2', '\x49B', + '\x49C', '\a', '-', '\x2', '\x2', '\x49C', '\x4A5', '\a', '\x8D', '\x2', + '\x2', '\x49D', '\x49E', '\a', ',', '\x2', '\x2', '\x49E', '\x49F', '\a', + '\x8C', '\x2', '\x2', '\x49F', '\x4A0', '\a', '.', '\x2', '\x2', '\x4A0', + '\x4A5', '\a', '\x8D', '\x2', '\x2', '\x4A1', '\x4A5', '\a', '/', '\x2', + '\x2', '\x4A2', '\x4A5', '\x5', '\xDC', 'o', '\x2', '\x4A3', '\x4A5', + '\x5', '\xDE', 'p', '\x2', '\x4A4', '\x48C', '\x3', '\x2', '\x2', '\x2', + '\x4A4', '\x48D', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x48E', '\x3', + '\x2', '\x2', '\x2', '\x4A4', '\x48F', '\x3', '\x2', '\x2', '\x2', '\x4A4', + '\x490', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x491', '\x3', '\x2', '\x2', + '\x2', '\x4A4', '\x492', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x493', + '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x494', '\x3', '\x2', '\x2', '\x2', + '\x4A4', '\x495', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x496', '\x3', + '\x2', '\x2', '\x2', '\x4A4', '\x497', '\x3', '\x2', '\x2', '\x2', '\x4A4', + '\x498', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x499', '\x3', '\x2', '\x2', + '\x2', '\x4A4', '\x49D', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A1', + '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A2', '\x3', '\x2', '\x2', '\x2', + '\x4A4', '\x4A3', '\x3', '\x2', '\x2', '\x2', '\x4A5', '\xD9', '\x3', + '\x2', '\x2', '\x2', '\x4A6', '\x4A8', '\x5', '\xD8', 'm', '\x2', '\x4A7', + '\x4A6', '\x3', '\x2', '\x2', '\x2', '\x4A8', '\x4A9', '\x3', '\x2', '\x2', + '\x2', '\x4A9', '\x4A7', '\x3', '\x2', '\x2', '\x2', '\x4A9', '\x4AA', + '\x3', '\x2', '\x2', '\x2', '\x4AA', '\xDB', '\x3', '\x2', '\x2', '\x2', + '\x4AB', '\x4C5', '\a', '\x30', '\x2', '\x2', '\x4AC', '\x4AD', '\a', + '\x30', '\x2', '\x2', '\x4AD', '\x4AE', '\a', '\x8C', '\x2', '\x2', '\x4AE', + '\x4AF', '\a', '\r', '\x2', '\x2', '\x4AF', '\x4C5', '\a', '\x8D', '\x2', + '\x2', '\x4B0', '\x4C5', '\a', '\x31', '\x2', '\x2', '\x4B1', '\x4B2', + '\a', '\x31', '\x2', '\x2', '\x4B2', '\x4B3', '\a', '\x8C', '\x2', '\x2', + '\x4B3', '\x4B4', '\a', '\r', '\x2', '\x2', '\x4B4', '\x4C5', '\a', '\x8D', + '\x2', '\x2', '\x4B5', '\x4C5', '\a', '\x32', '\x2', '\x2', '\x4B6', '\x4B7', + '\a', '\x32', '\x2', '\x2', '\x4B7', '\x4B8', '\a', '\x8C', '\x2', '\x2', + '\x4B8', '\x4B9', '\a', '\r', '\x2', '\x2', '\x4B9', '\x4C5', '\a', '\x8D', + '\x2', '\x2', '\x4BA', '\x4C5', '\a', '\x33', '\x2', '\x2', '\x4BB', '\x4BC', + '\a', '\x33', '\x2', '\x2', '\x4BC', '\x4BD', '\a', '\x8C', '\x2', '\x2', + '\x4BD', '\x4BE', '\a', '\r', '\x2', '\x2', '\x4BE', '\x4C5', '\a', '\x8D', + '\x2', '\x2', '\x4BF', '\x4C5', '\a', '\x34', '\x2', '\x2', '\x4C0', '\x4C1', + '\a', '\x34', '\x2', '\x2', '\x4C1', '\x4C2', '\a', '\x8C', '\x2', '\x2', + '\x4C2', '\x4C3', '\a', '\r', '\x2', '\x2', '\x4C3', '\x4C5', '\a', '\x8D', + '\x2', '\x2', '\x4C4', '\x4AB', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4AC', + '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4B0', '\x3', '\x2', '\x2', '\x2', + '\x4C4', '\x4B1', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4B5', '\x3', + '\x2', '\x2', '\x2', '\x4C4', '\x4B6', '\x3', '\x2', '\x2', '\x2', '\x4C4', + '\x4BA', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4BB', '\x3', '\x2', '\x2', + '\x2', '\x4C4', '\x4BF', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4C0', + '\x3', '\x2', '\x2', '\x2', '\x4C5', '\xDD', '\x3', '\x2', '\x2', '\x2', + '\x4C6', '\x4C7', '\t', '\x5', '\x2', '\x2', '\x4C7', '\xDF', '\x3', '\x2', + '\x2', '\x2', '\x4C8', '\x4C9', '\b', 'q', '\x1', '\x2', '\x4C9', '\x4CB', + '\x5', '\xE2', 'r', '\x2', '\x4CA', '\x4CC', '\x5', '\xF2', 'z', '\x2', + '\x4CB', '\x4CA', '\x3', '\x2', '\x2', '\x2', '\x4CB', '\x4CC', '\x3', + '\x2', '\x2', '\x2', '\x4CC', '\x4D4', '\x3', '\x2', '\x2', '\x2', '\x4CD', + '\x4CF', '\x5', '\xE4', 's', '\x2', '\x4CE', '\x4D0', '\x5', '\xF2', 'z', + '\x2', '\x4CF', '\x4CE', '\x3', '\x2', '\x2', '\x2', '\x4CF', '\x4D0', + '\x3', '\x2', '\x2', '\x2', '\x4D0', '\x4D4', '\x3', '\x2', '\x2', '\x2', + '\x4D1', '\x4D2', '\a', '\x37', '\x2', '\x2', '\x4D2', '\x4D4', '\x5', + '\xF0', 'y', '\x2', '\x4D3', '\x4C8', '\x3', '\x2', '\x2', '\x2', '\x4D3', + '\x4CD', '\x3', '\x2', '\x2', '\x2', '\x4D3', '\x4D1', '\x3', '\x2', '\x2', + '\x2', '\x4D4', '\x4DA', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4D6', + '\f', '\x3', '\x2', '\x2', '\x4D6', '\x4D7', '\a', '\x38', '\x2', '\x2', + '\x4D7', '\x4D9', '\x5', '\xF0', 'y', '\x2', '\x4D8', '\x4D5', '\x3', + '\x2', '\x2', '\x2', '\x4D9', '\x4DC', '\x3', '\x2', '\x2', '\x2', '\x4DA', + '\x4D8', '\x3', '\x2', '\x2', '\x2', '\x4DA', '\x4DB', '\x3', '\x2', '\x2', + '\x2', '\x4DB', '\xE1', '\x3', '\x2', '\x2', '\x2', '\x4DC', '\x4DA', + '\x3', '\x2', '\x2', '\x2', '\x4DD', '\x4DE', '\a', '\x8B', '\x2', '\x2', + '\x4DE', '\xE3', '\x3', '\x2', '\x2', '\x2', '\x4DF', '\x4E0', '\x5', + '\xC2', '\x62', '\x2', '\x4E0', '\xE5', '\x3', '\x2', '\x2', '\x2', '\x4E1', + '\x4E3', '\x5', '\xD0', 'i', '\x2', '\x4E2', '\x4E1', '\x3', '\x2', '\x2', + '\x2', '\x4E2', '\x4E3', '\x3', '\x2', '\x2', '\x2', '\x4E3', '\x4E4', + '\x3', '\x2', '\x2', '\x2', '\x4E4', '\x4E6', '\x5', '\xE8', 'u', '\x2', + '\x4E5', '\x4E7', '\a', '!', '\x2', '\x2', '\x4E6', '\x4E5', '\x3', '\x2', + '\x2', '\x2', '\x4E6', '\x4E7', '\x3', '\x2', '\x2', '\x2', '\x4E7', '\x4E8', + '\x3', '\x2', '\x2', '\x2', '\x4E8', '\x4E9', '\x5', '\x132', '\x9A', + '\x2', '\x4E9', '\x4EA', '\x5', '\xF0', 'y', '\x2', '\x4EA', '\x4F4', + '\x3', '\x2', '\x2', '\x2', '\x4EB', '\x4ED', '\x5', '\xD0', 'i', '\x2', + '\x4EC', '\x4EB', '\x3', '\x2', '\x2', '\x2', '\x4EC', '\x4ED', '\x3', + '\x2', '\x2', '\x2', '\x4ED', '\x4EE', '\x3', '\x2', '\x2', '\x2', '\x4EE', + '\x4EF', '\x5', '\xE8', 'u', '\x2', '\x4EF', '\x4F0', '\a', '\"', '\x2', + '\x2', '\x4F0', '\x4F1', '\x5', '\x132', '\x9A', '\x2', '\x4F1', '\x4F2', + '\x5', '\xF0', 'y', '\x2', '\x4F2', '\x4F4', '\x3', '\x2', '\x2', '\x2', + '\x4F3', '\x4E2', '\x3', '\x2', '\x2', '\x2', '\x4F3', '\x4EC', '\x3', + '\x2', '\x2', '\x2', '\x4F4', '\xE7', '\x3', '\x2', '\x2', '\x2', '\x4F5', + '\x4F6', '\a', '\x8C', '\x2', '\x2', '\x4F6', '\x4FF', '\a', '\x8D', '\x2', + '\x2', '\x4F7', '\x4F8', '\a', '\x8C', '\x2', '\x2', '\x4F8', '\x4FA', + '\x5', '\xEA', 'v', '\x2', '\x4F9', '\x4FB', '\x5', '\x134', '\x9B', '\x2', + '\x4FA', '\x4F9', '\x3', '\x2', '\x2', '\x2', '\x4FA', '\x4FB', '\x3', + '\x2', '\x2', '\x2', '\x4FB', '\x4FC', '\x3', '\x2', '\x2', '\x2', '\x4FC', + '\x4FD', '\a', '\x8D', '\x2', '\x2', '\x4FD', '\x4FF', '\x3', '\x2', '\x2', + '\x2', '\x4FE', '\x4F5', '\x3', '\x2', '\x2', '\x2', '\x4FE', '\x4F7', + '\x3', '\x2', '\x2', '\x2', '\x4FF', '\xE9', '\x3', '\x2', '\x2', '\x2', + '\x500', '\x506', '\x5', '\xEC', 'w', '\x2', '\x501', '\x502', '\x5', + '\xEC', 'w', '\x2', '\x502', '\x503', '\a', '\x84', '\x2', '\x2', '\x503', + '\x504', '\x5', '\xEA', 'v', '\x2', '\x504', '\x506', '\x3', '\x2', '\x2', + '\x2', '\x505', '\x500', '\x3', '\x2', '\x2', '\x2', '\x505', '\x501', + '\x3', '\x2', '\x2', '\x2', '\x506', '\xEB', '\x3', '\x2', '\x2', '\x2', + '\x507', '\x509', '\x5', '\xD0', 'i', '\x2', '\x508', '\x507', '\x3', + '\x2', '\x2', '\x2', '\x508', '\x509', '\x3', '\x2', '\x2', '\x2', '\x509', + '\x50B', '\x3', '\x2', '\x2', '\x2', '\x50A', '\x50C', '\x5', '\xF6', + '|', '\x2', '\x50B', '\x50A', '\x3', '\x2', '\x2', '\x2', '\x50B', '\x50C', + '\x3', '\x2', '\x2', '\x2', '\x50C', '\x50D', '\x3', '\x2', '\x2', '\x2', + '\x50D', '\x512', '\x5', '\xF0', 'y', '\x2', '\x50E', '\x50F', '\x5', + '\xEE', 'x', '\x2', '\x50F', '\x510', '\x5', '\xF2', 'z', '\x2', '\x510', + '\x512', '\x3', '\x2', '\x2', '\x2', '\x511', '\x508', '\x3', '\x2', '\x2', + '\x2', '\x511', '\x50E', '\x3', '\x2', '\x2', '\x2', '\x512', '\xED', + '\x3', '\x2', '\x2', '\x2', '\x513', '\x518', '\x5', '\x118', '\x8D', + '\x2', '\x514', '\x515', '\x5', '\x118', '\x8D', '\x2', '\x515', '\x516', + '\x5', '\x118', '\x8D', '\x2', '\x516', '\x518', '\x3', '\x2', '\x2', + '\x2', '\x517', '\x513', '\x3', '\x2', '\x2', '\x2', '\x517', '\x514', + '\x3', '\x2', '\x2', '\x2', '\x518', '\xEF', '\x3', '\x2', '\x2', '\x2', + '\x519', '\x51A', '\b', 'y', '\x1', '\x2', '\x51A', '\x529', '\x5', '\x104', + '\x83', '\x2', '\x51B', '\x529', '\x5', '\x106', '\x84', '\x2', '\x51C', + '\x529', '\x5', '\xE6', 't', '\x2', '\x51D', '\x529', '\x5', '\xF8', '}', + '\x2', '\x51E', '\x529', '\x5', '\xFC', '\x7F', '\x2', '\x51F', '\x529', + '\x5', '\x108', '\x85', '\x2', '\x520', '\x521', '\x5', '\xF4', '{', '\x2', + '\x521', '\x522', '\x5', '\xF0', 'y', '\x6', '\x522', '\x529', '\x3', + '\x2', '\x2', '\x2', '\x523', '\x529', '\a', ';', '\x2', '\x2', '\x524', + '\x529', '\a', '<', '\x2', '\x2', '\x525', '\x526', '\a', '<', '\x2', + '\x2', '\x526', '\x527', '\a', '\x83', '\x2', '\x2', '\x527', '\x529', + '\x5', '\xF8', '}', '\x2', '\x528', '\x519', '\x3', '\x2', '\x2', '\x2', + '\x528', '\x51B', '\x3', '\x2', '\x2', '\x2', '\x528', '\x51C', '\x3', + '\x2', '\x2', '\x2', '\x528', '\x51D', '\x3', '\x2', '\x2', '\x2', '\x528', + '\x51E', '\x3', '\x2', '\x2', '\x2', '\x528', '\x51F', '\x3', '\x2', '\x2', + '\x2', '\x528', '\x520', '\x3', '\x2', '\x2', '\x2', '\x528', '\x523', + '\x3', '\x2', '\x2', '\x2', '\x528', '\x524', '\x3', '\x2', '\x2', '\x2', + '\x528', '\x525', '\x3', '\x2', '\x2', '\x2', '\x529', '\x536', '\x3', + '\x2', '\x2', '\x2', '\x52A', '\x52B', '\f', '\v', '\x2', '\x2', '\x52B', + '\x535', '\a', '\x80', '\x2', '\x2', '\x52C', '\x52D', '\f', '\n', '\x2', + '\x2', '\x52D', '\x535', '\a', '\x82', '\x2', '\x2', '\x52E', '\x52F', + '\f', '\b', '\x2', '\x2', '\x52F', '\x530', '\a', '\x83', '\x2', '\x2', + '\x530', '\x535', '\a', '\x39', '\x2', '\x2', '\x531', '\x532', '\f', + '\a', '\x2', '\x2', '\x532', '\x533', '\a', '\x83', '\x2', '\x2', '\x533', + '\x535', '\a', ':', '\x2', '\x2', '\x534', '\x52A', '\x3', '\x2', '\x2', + '\x2', '\x534', '\x52C', '\x3', '\x2', '\x2', '\x2', '\x534', '\x52E', + '\x3', '\x2', '\x2', '\x2', '\x534', '\x531', '\x3', '\x2', '\x2', '\x2', + '\x535', '\x538', '\x3', '\x2', '\x2', '\x2', '\x536', '\x534', '\x3', + '\x2', '\x2', '\x2', '\x536', '\x537', '\x3', '\x2', '\x2', '\x2', '\x537', + '\xF1', '\x3', '\x2', '\x2', '\x2', '\x538', '\x536', '\x3', '\x2', '\x2', + '\x2', '\x539', '\x53B', '\a', '\x86', '\x2', '\x2', '\x53A', '\x53C', + '\x5', '\xD0', 'i', '\x2', '\x53B', '\x53A', '\x3', '\x2', '\x2', '\x2', + '\x53B', '\x53C', '\x3', '\x2', '\x2', '\x2', '\x53C', '\x53E', '\x3', + '\x2', '\x2', '\x2', '\x53D', '\x53F', '\x5', '\xF6', '|', '\x2', '\x53E', + '\x53D', '\x3', '\x2', '\x2', '\x2', '\x53E', '\x53F', '\x3', '\x2', '\x2', + '\x2', '\x53F', '\x540', '\x3', '\x2', '\x2', '\x2', '\x540', '\x541', + '\x5', '\xF0', 'y', '\x2', '\x541', '\xF3', '\x3', '\x2', '\x2', '\x2', + '\x542', '\x543', '\a', '=', '\x2', '\x2', '\x543', '\xF5', '\x3', '\x2', + '\x2', '\x2', '\x544', '\x545', '\a', '>', '\x2', '\x2', '\x545', '\xF7', + '\x3', '\x2', '\x2', '\x2', '\x546', '\x548', '\x5', '\xFA', '~', '\x2', + '\x547', '\x549', '\x5', '\x12A', '\x96', '\x2', '\x548', '\x547', '\x3', + '\x2', '\x2', '\x2', '\x548', '\x549', '\x3', '\x2', '\x2', '\x2', '\x549', + '\x54C', '\x3', '\x2', '\x2', '\x2', '\x54A', '\x54B', '\a', '\x83', '\x2', + '\x2', '\x54B', '\x54D', '\x5', '\xF8', '}', '\x2', '\x54C', '\x54A', + '\x3', '\x2', '\x2', '\x2', '\x54C', '\x54D', '\x3', '\x2', '\x2', '\x2', + '\x54D', '\xF9', '\x3', '\x2', '\x2', '\x2', '\x54E', '\x54F', '\x5', + '\xC2', '\x62', '\x2', '\x54F', '\xFB', '\x3', '\x2', '\x2', '\x2', '\x550', + '\x552', '\a', '\x8C', '\x2', '\x2', '\x551', '\x553', '\x5', '\xFE', + '\x80', '\x2', '\x552', '\x551', '\x3', '\x2', '\x2', '\x2', '\x552', + '\x553', '\x3', '\x2', '\x2', '\x2', '\x553', '\x554', '\x3', '\x2', '\x2', + '\x2', '\x554', '\x555', '\a', '\x8D', '\x2', '\x2', '\x555', '\xFD', + '\x3', '\x2', '\x2', '\x2', '\x556', '\x55C', '\x5', '\x100', '\x81', + '\x2', '\x557', '\x558', '\x5', '\x100', '\x81', '\x2', '\x558', '\x559', + '\a', '\x84', '\x2', '\x2', '\x559', '\x55A', '\x5', '\xFE', '\x80', '\x2', + '\x55A', '\x55C', '\x3', '\x2', '\x2', '\x2', '\x55B', '\x556', '\x3', + '\x2', '\x2', '\x2', '\x55B', '\x557', '\x3', '\x2', '\x2', '\x2', '\x55C', + '\xFF', '\x3', '\x2', '\x2', '\x2', '\x55D', '\x55E', '\x5', '\x102', + '\x82', '\x2', '\x55E', '\x55F', '\x5', '\xF2', 'z', '\x2', '\x55F', '\x562', + '\x3', '\x2', '\x2', '\x2', '\x560', '\x562', '\x5', '\xF0', 'y', '\x2', + '\x561', '\x55D', '\x3', '\x2', '\x2', '\x2', '\x561', '\x560', '\x3', + '\x2', '\x2', '\x2', '\x562', '\x101', '\x3', '\x2', '\x2', '\x2', '\x563', + '\x564', '\x5', '\x118', '\x8D', '\x2', '\x564', '\x103', '\x3', '\x2', + '\x2', '\x2', '\x565', '\x566', '\a', '\x8E', '\x2', '\x2', '\x566', '\x567', + '\x5', '\xF0', 'y', '\x2', '\x567', '\x568', '\a', '\x8F', '\x2', '\x2', + '\x568', '\x105', '\x3', '\x2', '\x2', '\x2', '\x569', '\x56A', '\a', + '\x8E', '\x2', '\x2', '\x56A', '\x56B', '\x5', '\xF0', 'y', '\x2', '\x56B', + '\x56C', '\a', '\x86', '\x2', '\x2', '\x56C', '\x56D', '\x5', '\xF0', + 'y', '\x2', '\x56D', '\x56E', '\a', '\x8F', '\x2', '\x2', '\x56E', '\x107', + '\x3', '\x2', '\x2', '\x2', '\x56F', '\x572', '\x5', '\x10A', '\x86', + '\x2', '\x570', '\x571', '\a', '\x7F', '\x2', '\x2', '\x571', '\x573', + '\x5', '\x10A', '\x86', '\x2', '\x572', '\x570', '\x3', '\x2', '\x2', + '\x2', '\x573', '\x574', '\x3', '\x2', '\x2', '\x2', '\x574', '\x572', + '\x3', '\x2', '\x2', '\x2', '\x574', '\x575', '\x3', '\x2', '\x2', '\x2', + '\x575', '\x109', '\x3', '\x2', '\x2', '\x2', '\x576', '\x577', '\x5', + '\xF8', '}', '\x2', '\x577', '\x10B', '\x3', '\x2', '\x2', '\x2', '\x578', + '\x57D', '\x5', '\x112', '\x8A', '\x2', '\x579', '\x57D', '\x5', '\x116', + '\x8C', '\x2', '\x57A', '\x57D', '\x5', '\x110', '\x89', '\x2', '\x57B', + '\x57D', '\x5', '\x10E', '\x88', '\x2', '\x57C', '\x578', '\x3', '\x2', + '\x2', '\x2', '\x57C', '\x579', '\x3', '\x2', '\x2', '\x2', '\x57C', '\x57A', + '\x3', '\x2', '\x2', '\x2', '\x57C', '\x57B', '\x3', '\x2', '\x2', '\x2', + '\x57D', '\x10D', '\x3', '\x2', '\x2', '\x2', '\x57E', '\x57F', '\a', + '?', '\x2', '\x2', '\x57F', '\x10F', '\x3', '\x2', '\x2', '\x2', '\x580', + '\x581', '\t', '\x6', '\x2', '\x2', '\x581', '\x111', '\x3', '\x2', '\x2', + '\x2', '\x582', '\x584', '\t', '\a', '\x2', '\x2', '\x583', '\x582', '\x3', + '\x2', '\x2', '\x2', '\x583', '\x584', '\x3', '\x2', '\x2', '\x2', '\x584', + '\x585', '\x3', '\x2', '\x2', '\x2', '\x585', '\x586', '\x5', '\x114', + '\x8B', '\x2', '\x586', '\x113', '\x3', '\x2', '\x2', '\x2', '\x587', + '\x588', '\t', '\b', '\x2', '\x2', '\x588', '\x115', '\x3', '\x2', '\x2', + '\x2', '\x589', '\x58A', '\a', 'x', '\x2', '\x2', '\x58A', '\x117', '\x3', + '\x2', '\x2', '\x2', '\x58B', '\x58E', '\a', 'y', '\x2', '\x2', '\x58C', + '\x58E', '\x5', '\x138', '\x9D', '\x2', '\x58D', '\x58B', '\x3', '\x2', + '\x2', '\x2', '\x58D', '\x58C', '\x3', '\x2', '\x2', '\x2', '\x58E', '\x119', + '\x3', '\x2', '\x2', '\x2', '\x58F', '\x590', '\a', '\x81', '\x2', '\x2', + '\x590', '\x591', '\x5', '\x11C', '\x8F', '\x2', '\x591', '\x592', '\x5', + '\x130', '\x99', '\x2', '\x592', '\x11B', '\x3', '\x2', '\x2', '\x2', + '\x593', '\x598', '\x5', '\x11E', '\x90', '\x2', '\x594', '\x595', '\a', + '\x84', '\x2', '\x2', '\x595', '\x597', '\x5', '\x11E', '\x90', '\x2', + '\x596', '\x594', '\x3', '\x2', '\x2', '\x2', '\x597', '\x59A', '\x3', + '\x2', '\x2', '\x2', '\x598', '\x596', '\x3', '\x2', '\x2', '\x2', '\x598', + '\x599', '\x3', '\x2', '\x2', '\x2', '\x599', '\x11D', '\x3', '\x2', '\x2', + '\x2', '\x59A', '\x598', '\x3', '\x2', '\x2', '\x2', '\x59B', '\x5A5', + '\x5', '\xFA', '~', '\x2', '\x59C', '\x59D', '\x5', '\xFA', '~', '\x2', + '\x59D', '\x59E', '\a', '\x86', '\x2', '\x2', '\x59E', '\x59F', '\x5', + '\xF8', '}', '\x2', '\x59F', '\x5A5', '\x3', '\x2', '\x2', '\x2', '\x5A0', + '\x5A1', '\x5', '\xFA', '~', '\x2', '\x5A1', '\x5A2', '\a', '\x86', '\x2', + '\x2', '\x5A2', '\x5A3', '\x5', '\x108', '\x85', '\x2', '\x5A3', '\x5A5', + '\x3', '\x2', '\x2', '\x2', '\x5A4', '\x59B', '\x3', '\x2', '\x2', '\x2', + '\x5A4', '\x59C', '\x3', '\x2', '\x2', '\x2', '\x5A4', '\x5A0', '\x3', + '\x2', '\x2', '\x2', '\x5A5', '\x11F', '\x3', '\x2', '\x2', '\x2', '\x5A6', + '\x5A7', '\a', '\x42', '\x2', '\x2', '\x5A7', '\x5A8', '\x5', '\x122', + '\x92', '\x2', '\x5A8', '\x121', '\x3', '\x2', '\x2', '\x2', '\x5A9', + '\x5AE', '\x5', '\x124', '\x93', '\x2', '\x5AA', '\x5AB', '\a', '\x84', + '\x2', '\x2', '\x5AB', '\x5AD', '\x5', '\x124', '\x93', '\x2', '\x5AC', + '\x5AA', '\x3', '\x2', '\x2', '\x2', '\x5AD', '\x5B0', '\x3', '\x2', '\x2', + '\x2', '\x5AE', '\x5AC', '\x3', '\x2', '\x2', '\x2', '\x5AE', '\x5AF', + '\x3', '\x2', '\x2', '\x2', '\x5AF', '\x123', '\x3', '\x2', '\x2', '\x2', + '\x5B0', '\x5AE', '\x3', '\x2', '\x2', '\x2', '\x5B1', '\x5B4', '\x5', + '\x126', '\x94', '\x2', '\x5B2', '\x5B4', '\x5', '\x128', '\x95', '\x2', + '\x5B3', '\x5B1', '\x3', '\x2', '\x2', '\x2', '\x5B3', '\x5B2', '\x3', + '\x2', '\x2', '\x2', '\x5B4', '\x125', '\x3', '\x2', '\x2', '\x2', '\x5B5', + '\x5B6', '\x5', '\xF8', '}', '\x2', '\x5B6', '\x5B7', '\a', '\x86', '\x2', + '\x2', '\x5B7', '\x5B8', '\x5', '\xF8', '}', '\x2', '\x5B8', '\x5BE', + '\x3', '\x2', '\x2', '\x2', '\x5B9', '\x5BA', '\x5', '\xF8', '}', '\x2', + '\x5BA', '\x5BB', '\a', '\x86', '\x2', '\x2', '\x5BB', '\x5BC', '\x5', + '\x108', '\x85', '\x2', '\x5BC', '\x5BE', '\x3', '\x2', '\x2', '\x2', + '\x5BD', '\x5B5', '\x3', '\x2', '\x2', '\x2', '\x5BD', '\x5B9', '\x3', + '\x2', '\x2', '\x2', '\x5BE', '\x127', '\x3', '\x2', '\x2', '\x2', '\x5BF', + '\x5C0', '\x5', '\xF8', '}', '\x2', '\x5C0', '\x5C1', '\x5', '\x13A', + '\x9E', '\x2', '\x5C1', '\x5C2', '\x5', '\xF0', 'y', '\x2', '\x5C2', '\x129', + '\x3', '\x2', '\x2', '\x2', '\x5C3', '\x5C4', '\a', '\x81', '\x2', '\x2', + '\x5C4', '\x5C5', '\x5', '\x12C', '\x97', '\x2', '\x5C5', '\x5C6', '\x5', + '\x130', '\x99', '\x2', '\x5C6', '\x12B', '\x3', '\x2', '\x2', '\x2', + '\x5C7', '\x5CC', '\x5', '\x12E', '\x98', '\x2', '\x5C8', '\x5C9', '\a', + '\x84', '\x2', '\x2', '\x5C9', '\x5CB', '\x5', '\x12E', '\x98', '\x2', + '\x5CA', '\x5C8', '\x3', '\x2', '\x2', '\x2', '\x5CB', '\x5CE', '\x3', + '\x2', '\x2', '\x2', '\x5CC', '\x5CA', '\x3', '\x2', '\x2', '\x2', '\x5CC', + '\x5CD', '\x3', '\x2', '\x2', '\x2', '\x5CD', '\x12D', '\x3', '\x2', '\x2', + '\x2', '\x5CE', '\x5CC', '\x3', '\x2', '\x2', '\x2', '\x5CF', '\x5D0', + '\x5', '\xF0', 'y', '\x2', '\x5D0', '\x12F', '\x3', '\x2', '\x2', '\x2', + '\x5D1', '\x5D2', '\a', '\x43', '\x2', '\x2', '\x5D2', '\x131', '\x3', + '\x2', '\x2', '\x2', '\x5D3', '\x5D4', '\a', '\x44', '\x2', '\x2', '\x5D4', + '\x133', '\x3', '\x2', '\x2', '\x2', '\x5D5', '\x5D6', '\a', '\x45', '\x2', + '\x2', '\x5D6', '\x135', '\x3', '\x2', '\x2', '\x2', '\x5D7', '\x5D8', + '\t', '\t', '\x2', '\x2', '\x5D8', '\x137', '\x3', '\x2', '\x2', '\x2', + '\x5D9', '\x5DA', '\t', '\n', '\x2', '\x2', '\x5DA', '\x139', '\x3', '\x2', + '\x2', '\x2', '\x5DB', '\x5DE', '\x5', '\x13C', '\x9F', '\x2', '\x5DC', + '\x5DE', '\a', '\x93', '\x2', '\x2', '\x5DD', '\x5DB', '\x3', '\x2', '\x2', + '\x2', '\x5DD', '\x5DC', '\x3', '\x2', '\x2', '\x2', '\x5DE', '\x13B', + '\x3', '\x2', '\x2', '\x2', '\x5DF', '\x600', '\a', '\x43', '\x2', '\x2', + '\x5E0', '\x5E1', '\a', '\x43', '\x2', '\x2', '\x5E1', '\x600', '\a', + '\x43', '\x2', '\x2', '\x5E2', '\x5E3', '\a', '\x43', '\x2', '\x2', '\x5E3', + '\x5E4', '\a', '\x43', '\x2', '\x2', '\x5E4', '\x600', '\a', '\x43', '\x2', + '\x2', '\x5E5', '\x5E6', '\a', '\x43', '\x2', '\x2', '\x5E6', '\x5E7', + '\a', '\x43', '\x2', '\x2', '\x5E7', '\x5E8', '\a', '\x43', '\x2', '\x2', + '\x5E8', '\x5E9', '\a', '\x43', '\x2', '\x2', '\x5E9', '\x600', '\a', + '\x43', '\x2', '\x2', '\x5EA', '\x5EB', '\a', '\x43', '\x2', '\x2', '\x5EB', + '\x5EC', '\a', '\x43', '\x2', '\x2', '\x5EC', '\x5ED', '\a', '\x43', '\x2', + '\x2', '\x5ED', '\x5EE', '\a', '\x43', '\x2', '\x2', '\x5EE', '\x5EF', + '\a', '\x43', '\x2', '\x2', '\x5EF', '\x600', '\a', '\x43', '\x2', '\x2', + '\x5F0', '\x5F1', '\a', '\x43', '\x2', '\x2', '\x5F1', '\x5F2', '\a', + '\x43', '\x2', '\x2', '\x5F2', '\x5F3', '\a', '\x43', '\x2', '\x2', '\x5F3', + '\x5F4', '\a', '\x43', '\x2', '\x2', '\x5F4', '\x5F5', '\a', '\x43', '\x2', + '\x2', '\x5F5', '\x5F6', '\a', '\x43', '\x2', '\x2', '\x5F6', '\x600', + '\a', '\x43', '\x2', '\x2', '\x5F7', '\x5F8', '\a', '\x43', '\x2', '\x2', + '\x5F8', '\x5F9', '\a', '\x43', '\x2', '\x2', '\x5F9', '\x5FA', '\a', + '\x43', '\x2', '\x2', '\x5FA', '\x5FB', '\a', '\x43', '\x2', '\x2', '\x5FB', + '\x5FC', '\a', '\x43', '\x2', '\x2', '\x5FC', '\x5FD', '\a', '\x43', '\x2', + '\x2', '\x5FD', '\x5FE', '\a', '\x43', '\x2', '\x2', '\x5FE', '\x600', + '\a', '\x43', '\x2', '\x2', '\x5FF', '\x5DF', '\x3', '\x2', '\x2', '\x2', + '\x5FF', '\x5E0', '\x3', '\x2', '\x2', '\x2', '\x5FF', '\x5E2', '\x3', + '\x2', '\x2', '\x2', '\x5FF', '\x5E5', '\x3', '\x2', '\x2', '\x2', '\x5FF', + '\x5EA', '\x3', '\x2', '\x2', '\x2', '\x5FF', '\x5F0', '\x3', '\x2', '\x2', + '\x2', '\x5FF', '\x5F7', '\x3', '\x2', '\x2', '\x2', '\x600', '\x13D', + '\x3', '\x2', '\x2', '\x2', '\xBF', '\x141', '\x147', '\x156', '\x165', + '\x168', '\x16C', '\x177', '\x182', '\x186', '\x189', '\x18D', '\x190', + '\x193', '\x198', '\x19D', '\x19F', '\x1B5', '\x1B8', '\x1BB', '\x1BF', + '\x1C2', '\x1C5', '\x1C9', '\x1CC', '\x1D3', '\x1D8', '\x1DB', '\x1E0', + '\x1EA', '\x1ED', '\x1F1', '\x1F4', '\x1F7', '\x1FA', '\x1FF', '\x202', + '\x205', '\x209', '\x20F', '\x213', '\x216', '\x219', '\x223', '\x227', + '\x230', '\x234', '\x23C', '\x240', '\x243', '\x24D', '\x251', '\x259', + '\x25C', '\x25F', '\x264', '\x267', '\x26A', '\x274', '\x27C', '\x27F', + '\x282', '\x287', '\x28A', '\x28D', '\x292', '\x296', '\x29B', '\x29E', + '\x2A1', '\x2A5', '\x2AD', '\x2B7', '\x2BA', '\x2BF', '\x2C9', '\x2D6', + '\x2DB', '\x2E9', '\x2F4', '\x2FC', '\x304', '\x315', '\x31B', '\x31E', + '\x323', '\x328', '\x32B', '\x332', '\x338', '\x346', '\x349', '\x34C', + '\x353', '\x358', '\x35B', '\x360', '\x363', '\x366', '\x36B', '\x36F', + '\x372', '\x375', '\x378', '\x37E', '\x384', '\x38D', '\x390', '\x393', + '\x397', '\x39B', '\x39D', '\x3A7', '\x3AD', '\x3B1', '\x3B4', '\x3B8', + '\x3BD', '\x3BF', '\x3C2', '\x3C5', '\x3C9', '\x3CC', '\x3D1', '\x3D4', + '\x3D8', '\x3DB', '\x3DE', '\x3E8', '\x3EF', '\x3F3', '\x3F8', '\x3FB', + '\x401', '\x40B', '\x411', '\x419', '\x421', '\x429', '\x42D', '\x440', + '\x443', '\x44A', '\x455', '\x45C', '\x463', '\x46E', '\x473', '\x486', + '\x48A', '\x4A4', '\x4A9', '\x4C4', '\x4CB', '\x4CF', '\x4D3', '\x4DA', + '\x4E2', '\x4E6', '\x4EC', '\x4F3', '\x4FA', '\x4FE', '\x505', '\x508', + '\x50B', '\x511', '\x517', '\x528', '\x534', '\x536', '\x53B', '\x53E', + '\x548', '\x54C', '\x552', '\x55B', '\x561', '\x574', '\x57C', '\x583', + '\x58D', '\x598', '\x5A4', '\x5AE', '\x5B3', '\x5BD', '\x5CC', '\x5DD', + '\x5FF', + }; + + public static readonly ATN _ATN = + new ATNDeserializer().Deserialize(_serializedATN); + + +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs b/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs new file mode 100644 index 000000000000..e0583d9d1afa --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftInterfaceReflector { + public interface IModuleLoader { + bool Load (string moduleName, TypeDatabase into); + } + + // this is only useful for tests, really. + public class NoLoadLoader : IModuleLoader { + public NoLoadLoader () + { + } + + public bool Load (string moduleName, TypeDatabase into) + { + if (moduleName == "_Concurrency") + return true; + // only returns true is the module is already loaded + return into.ModuleNames.Contains (moduleName); + } + } +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs b/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs new file mode 100644 index 000000000000..3429dafa31db --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs @@ -0,0 +1,317 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Xml.Linq; +using SyntaxDynamo; +using System.Linq; +using System.Text; + +namespace SwiftReflector.SwiftInterfaceReflector { + public class ObjCSelectorFactory { + XElement funcElement; + + static string [] prepositions = new string [] { + "above", "after", "along", "alongside", "as", "at", + "before", "below", "by", "following", "for", "from", + "given", "in", "including", "inside", "into", "matching", + "of", "on", "passing", "preceding", "since", "to", + "until", "using", "via", "when", "with", "within" + }; + + static string [] pluralSuffixes = new string [] { + "s", "es", "ies" + }; + + public ObjCSelectorFactory (XElement funcElement) + { + this.funcElement = Exceptions.ThrowOnNull (funcElement, nameof (funcElement)); + } + + public string Generate () + { + // it's in an @objc attribute + var providedSelector = ProvidedObjCSelector (); + if (!String.IsNullOrEmpty (providedSelector)) + return providedSelector; + + if (IsDeInit ()) + return "dealloc"; + + var argNames = GetArgumentNames (); + + var baseName = IsInit () ? "init" : + (IsProperty () ? PropertyName () : FunctionName ()); + + if (IsSetter ()) { + return SetterSelector (baseName); + } + + if (IsGetter ()) { + return GetterSelector (baseName); + } + + if (IsSubscriptGetter ()) { + return "objectAtIndexedSubscript:"; + } + + if (IsSubscriptSetter ()) { + return "setObject:atIndexedSubscript:"; + } + + if (IsInit () && argNames.Count == 1 && IsObjCZeroParameterWithLongSelector ()) { + var firstName = argNames [0]; + var sb = new StringBuilder (); + sb.Append ("init"); + if (!IsPreposition (FirstWord (firstName))) + sb.Append ("With"); + sb.Append (CapitalizeFirstLetter (firstName)); + return sb.ToString (); + } + + // at this point, the Apple code needs to know if there are + // foreign async or foreign error conventions. + // The definition of this is opaque enough that it's not clear + // what the conditions are for this predicate, so we're going to + // pretend it doesn't exist for now. + + var asyncConvention = false; + var errorConvention = false; + + var numSelectorPieces = argNames.Count + (asyncConvention ? 1 : 0) + + (errorConvention ? 1 : 0); + + if (numSelectorPieces == 0) + return baseName; + + if (numSelectorPieces == 1 && argNames.Count == 1 && argNames [0] == "_") + return baseName; + + var argIndex = 0; + var selector = new StringBuilder (); + for (var piece = 0; piece != numSelectorPieces; ++piece) { + if (piece > 0) { + if (asyncConvention) { + selector.Append ("completionHandler:"); + continue; + } + + // If we have an error convention that inserts an error parameter + // here, add "error". + if (errorConvention) { + selector.Append ("error:"); + continue; + } + + // Selector pieces beyond the first are simple. + selector.Append (argNames [argIndex++]).Append ('.'); + continue; + } + var firstPiece = baseName; + var scratch = new StringBuilder (); + scratch.Append (firstPiece); + if (asyncConvention) { + // The completion handler is first; append "WithCompletionHandler". + scratch.Append ("WithCompletionHandler"); + firstPiece = scratch.ToString (); + } else if (errorConvention) { + scratch.Append ("AndReturnError"); + firstPiece = scratch.ToString (); + } else if (argNames [argIndex] != "_" && argNames [argIndex] != "") { + // If the first argument name doesn't start with a preposition, and the + // method name doesn't end with a preposition, add "with". + var firstName = argNames [argIndex++]; + if (!IsPreposition (FirstWord (firstName)) && + !IsPreposition (LastWord (firstPiece))) { + scratch.Append ("With"); + } + scratch.Append (CapitalizeFirstLetter (firstName)); + firstPiece = scratch.ToString (); + } else { + ++argIndex; + } + + selector.Append (firstPiece); + if (argNames.Count > 0) + selector.Append (':'); + } + return selector.ToString (); + } + + List GetArgumentNames () + { + var parameterList = funcElement.Descendants (SwiftInterfaceReflector.kParameterList).Last (); + var parameters = parameterList.Descendants (SwiftInterfaceReflector.kParameter).Select ( + p => { + var publicName = p.Attribute (SwiftInterfaceReflector.kPublicName)?.Value; + var privateName = p.Attribute (SwiftInterfaceReflector.kPrivateName).Value; + return String.IsNullOrEmpty (publicName) ? privateName : publicName; + }); + return parameters.ToList (); + } + + string ProvidedObjCSelector () + { + //< attributes > + // < attribute name = "objc" /> + + // + // find the first objc attribute + + var elem = funcElement.Descendants (SwiftInterfaceReflector.kAttribute) + .FirstOrDefault (el => el.Attribute (SwiftInterfaceReflector.kName)?.Value == SwiftInterfaceReflector.kObjC); + if (elem == null) + return null; + var parameters = elem.Descendants (SwiftInterfaceReflector.kAttributeParameter); + if (parameters == null) + return null; + var sb = new StringBuilder (); + foreach (var piece in parameters) { + sb.Append (piece.Attribute (SwiftInterfaceReflector.kValue)?.Value ?? ""); + } + return sb.ToString (); + } + + string GetterSelector (string baseName) + { + return baseName; + } + + string SetterSelector (string baseName) + { + return $"set{CapitalizeFirstLetter (baseName)}:"; + } + + string CapitalizeFirstLetter (string baseName) + { + if (Char.IsLower (baseName [0])) { + return Char.ToUpper (baseName [0]) + baseName.Substring (1); + } + return baseName; + } + + bool IsObjCZeroParameterWithLongSelector () + { + var parameterList = funcElement.Descendants (SwiftInterfaceReflector.kParameterList).Last (); + var onlyParameter = parameterList.Descendants (SwiftInterfaceReflector.kParameter).FirstOrDefault (); + if (onlyParameter == null) + return false; + return onlyParameter.Attribute (SwiftInterfaceReflector.kType)?.Value == "()"; + } + + bool IsDeInit () + { + return FunctionName () == SwiftInterfaceReflector.kDotDtor; + } + + bool IsInit () + { + return FunctionName () == SwiftInterfaceReflector.kDotCtor; + } + + bool IsProperty () + { + return funcElement.Attribute (SwiftInterfaceReflector.kIsProperty)?.Value == "true"; + } + + string PropertyName () + { + return FunctionName ().Substring ("get_".Length); + } + + bool IsGetter () + { + var funcName = FunctionName (); + return IsProperty () && funcName.StartsWith ("get_", StringComparison.Ordinal) && + funcName != SwiftInterfaceReflector.kGetSubscript; + } + + bool IsSetter () + { + var funcName = FunctionName (); + return IsProperty () && funcName.StartsWith ("set_", StringComparison.Ordinal) && + funcName != SwiftInterfaceReflector.kSetSubscript; + } + + bool IsSubscriptGetter () + { + return FunctionName () == SwiftInterfaceReflector.kGetSubscript; + } + + bool IsSubscriptSetter () + { + return FunctionName () == SwiftInterfaceReflector.kSetSubscript; + } + + static bool IsPreposition (string s) + { + return prepositions.Contains (s); + } + + static bool IsPluralSuffix (string s) + { + return pluralSuffixes.Contains (s); + } + + string FunctionName () + { + return funcElement.Attribute (SwiftInterfaceReflector.kName)?.Value; + } + + IEnumerable Words (string src) + { + if (String.IsNullOrEmpty (src)) + yield break; + var length = src.Length; + var start = 0; + + while (start < length) { + if (src [start] == '_') { + start++; + yield return "_"; + continue; + } + var i = start; + while (i < length && Char.IsUpper (src [i])) + i++; + if (i - start > 1) { + var endOfNext = i; + while (endOfNext < length && Char.IsLower (src [endOfNext])) + endOfNext++; + if (i == length || IsPluralSuffix (src.Substring (i, endOfNext - i)) + && src.Substring (i, endOfNext - i).EndsWith ("Is", StringComparison.Ordinal)) { + var word = src.Substring (start, endOfNext - start); + start = endOfNext; + yield return word; + continue; + } else { + if (Char.IsLower (src [i])) + i--; + var word = src.Substring (start, i - start); + start = i; + yield return word; + continue; + } + } + + while (i < length && !Char.IsUpper (src [i]) && src [i] != '_') + i++; + var thisword = src.Substring (start, i - start); + start = i; + yield return thisword; + } + yield break; + } + + string FirstWord (string src) + { + return Words (src).FirstOrDefault () ?? ""; + } + + string LastWord (string src) + { + return Words (src).LastOrDefault () ?? ""; + } + } +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs b/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs new file mode 100644 index 000000000000..c7aee16d2e35 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs @@ -0,0 +1,18 @@ +using System; +namespace SwiftReflector.SwiftInterfaceReflector { + public class ParseException : Exception { + public ParseException () + { + } + + public ParseException (string message) + : base (message) + { + } + + public ParseException (string message, Exception inner) + : base (message, inner) + { + } + } +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs b/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs new file mode 100644 index 000000000000..876efcb8ea38 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs @@ -0,0 +1,2330 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using Antlr4.Runtime; +using Antlr4.Runtime.Misc; +using Antlr4.Runtime.Tree; +using static SwiftInterfaceParser; +using System.Text; +using SyntaxDynamo; +using SwiftReflector.TypeMapping; +using SwiftReflector.SwiftXmlReflection; +using System.Threading.Tasks; +using System.Threading; + +namespace SwiftReflector.SwiftInterfaceReflector { + public class SwiftInterfaceReflector : SwiftInterfaceBaseListener { + // swift-interface-format-version: 1.0 + const string kSwiftInterfaceFormatVersion = "// swift-interface-format-version:"; + // swift-compiler-version: Apple Swift version 5.3 (swiftlang-1200.0.29.2 clang-1200.0.30.1) + const string kSwiftCompilerVersion = "// swift-compiler-version: "; + // swift-module-flags: -target x86_64-apple-macosx10.9 -enable-objc-interop -ena + const string kSwiftModuleFlags = "// swift-module-flags:"; + + internal const string kModuleName = "module-name"; + internal const string kTarget = "target"; + internal const string kIgnore = "IGNORE"; + internal const string kInheritanceKind = "inheritanceKind"; + internal const string kModule = "module"; + internal const string kFunc = "func"; + internal const string kType = "type"; + internal const string kName = "name"; + internal const string kFinal = "final"; + internal const string kPublic = "public"; + internal const string kPrivate = "private"; + internal const string kInternal = "internal"; + internal const string kOpen = "open"; + internal const string kPublicCap = "Public"; + internal const string kPrivateCap = "Private"; + internal const string kInternalCap = "Internal"; + internal const string kOpenCap = "Open"; + internal const string kFilePrivate = "fileprivate"; + internal const string kStatic = "static"; + internal const string kIsStatic = "isStatic"; + internal const string kOptional = "optional"; + internal const string kObjC = "objc"; + internal const string kExtension = "extension"; + internal const string kProtocol = "protocol"; + internal const string kClass = "class"; + internal const string kInnerClasses = "innerclasses"; + internal const string kStruct = "struct"; + internal const string kInnerStructs = "innerstructs"; + internal const string kEnum = "enum"; + internal const string kInnerEnums = "innerenums"; + internal const string kMutating = "mutating"; + internal const string kRequired = "required"; + internal const string kAssociatedTypes = "associatedtypes"; + internal const string kAssociatedType = "associatedtype"; + internal const string kDefaultType = "defaulttype"; + internal const string kConformingProtocols = "conformingprotocols"; + internal const string kConformingProtocol = "conformingprotocol"; + internal const string kMembers = "members"; + internal const string kConvenience = "convenience"; + internal const string kParameterLists = "parameterlists"; + internal const string kParameterList = "parameterlist"; + internal const string kParameter = "parameter"; + internal const string kParam = "param"; + internal const string kGenericParameters = "genericparameters"; + internal const string kWhere = "where"; + internal const string kRelationship = "relationship"; + internal const string kEquals = "equals"; + internal const string kInherits = "inherits"; + internal const string kInherit = "inherit"; + internal const string kIndex = "index"; + internal const string kGetSubscript = "get_subscript"; + internal const string kSetSubscript = "set_subscript"; + internal const string kOperator = "operator"; + internal const string kLittlePrefix = "prefix"; + internal const string kLittlePostfix = "postfix"; + internal const string kPrefix = "Prefix"; + internal const string kPostfix = "Postfix"; + internal const string kInfix = "Infix"; + internal const string kDotCtor = ".ctor"; + internal const string kDotDtor = ".dtor"; + internal const string kNewValue = "newValue"; + internal const string kOperatorKind = "operatorKind"; + internal const string kPublicName = "publicName"; + internal const string kPrivateName = "privateName"; + internal const string kKind = "kind"; + internal const string kNone = "None"; + internal const string kLittleUnknown = "unknown"; + internal const string kUnknown = "Unknown"; + internal const string kOnType = "onType"; + internal const string kAccessibility = "accessibility"; + internal const string kIsVariadic = "isVariadic"; + internal const string kTypeDeclaration = "typedeclaration"; + internal const string kIsAsync = "isAsync"; + internal const string kProperty = "property"; + internal const string kIsProperty = "isProperty"; + internal const string kStorage = "storage"; + internal const string kComputed = "Computed"; + internal const string kEscaping = "escaping"; + internal const string kAutoClosure = "autoclosure"; + internal const string kAttributes = "attributes"; + internal const string kAttribute = "attribute"; + internal const string kAttributeParameterList = "attributeparameterlist"; + internal const string kAttributeParameter = "attributeparameter"; + internal const string kLabel = "Label"; + internal const string kLiteral = "Literal"; + internal const string kSeparator = "Separator"; + internal const string kSublist = "Sublist"; + internal const string kValue = "Value"; + internal const string kObjCSelector = "objcSelector"; + internal const string kDeprecated = "deprecated"; + internal const string kUnavailable = "unavailable"; + internal const string kAvailable = "available"; + internal const string kIntroduced = "introduced"; + internal const string kObsoleted = "obsoleted"; + internal const string kElements = "elements"; + internal const string kElement = "element"; + internal const string kIntValue = "intValue"; + internal const string kRawType = "rawType"; + internal const string kRawValue = "RawValue"; + internal const string kTypeAliases = "typealiases"; + internal const string kTypeAlias = "typealias"; + internal const string kSuperclass = "superclass"; + + Stack currentElement = new Stack (); + Version interfaceVersion; + Version compilerVersion; + + List importModules = new List (); + List operators = new List (); + List> functions = new List> (); + List extensions = new List (); + Dictionary moduleFlags = new Dictionary (); + List nominalTypes = new List (); + List classes = new List (); + List associatedTypesWithConformance = new List (); + List unknownInheritance = new List (); + List typeAliasMap = new List (); + string moduleName; + TypeDatabase typeDatabase; + IModuleLoader moduleLoader; + ICharStream inputStream; + + public SwiftInterfaceReflector (TypeDatabase typeDatabase, IModuleLoader moduleLoader) + { + this.typeDatabase = typeDatabase; + this.moduleLoader = moduleLoader; + } + + public async Task ReflectAsync (string inFile, Stream outStm) + { + Exceptions.ThrowOnNull (inFile, nameof (inFile)); + Exceptions.ThrowOnNull (outStm, nameof (outStm)); + + + await Task.Run (() => { + var xDocument = Reflect (inFile); + xDocument.Save (outStm); + currentElement.Clear (); + }); + } + + public void Reflect (string inFile, Stream outStm) + { + Exceptions.ThrowOnNull (inFile, nameof (inFile)); + Exceptions.ThrowOnNull (outStm, nameof (outStm)); + + var xDocument = Reflect (inFile); + + xDocument.Save (outStm); + currentElement.Clear (); + } + + public async Task ReflectAsync (string inFile) + { + return await Task.Run (() => { + return Reflect (inFile); + }); + } + + public XDocument Reflect (string inFile) + { + // try { + Exceptions.ThrowOnNull (inFile, nameof (inFile)); + + if (!File.Exists (inFile)) + throw new ParseException ($"Input file {inFile} not found"); + + + var fileName = Path.GetFileName (inFile); + moduleName = fileName.Split ('.') [0]; + + var module = new XElement (kModule); + currentElement.Push (module); + + var desugarer = new SyntaxDesugaringParser (inFile); + var desugaredResult = desugarer.Desugar (); + inputStream = CharStreams.fromString (desugaredResult); + + var lexer = new SwiftInterfaceLexer (inputStream); + var tokenStream = new CommonTokenStream (lexer); + var parser = new SwiftInterfaceParser (tokenStream); + var walker = new ParseTreeWalker (); + walker.Walk (this, parser.swiftinterface ()); + + if (currentElement.Count != 1) + throw new ParseException ("At end of parse, stack should contain precisely one element"); + + if (module != currentElement.Peek ()) + throw new ParseException ("Expected the final element to be the initial module"); + + // LoadReferencedModules (); + + // PatchPossibleOperators (); + // PatchExtensionShortNames (); + // PatchExtensionSelfArgs (); + // PatchPossibleBadInheritance (); + // PatchAssociatedTypeConformance (); + + if (typeAliasMap.Count > 0) { + module.Add (new XElement (kTypeAliases, typeAliasMap.ToArray ())); + } + + module.Add (new XAttribute (kName, moduleName)); + SetLanguageVersion (module); + + var tlElement = new XElement ("xamreflect", new XAttribute ("version", "1.0"), + new XElement ("modulelist", module)); + var xDocument = new XDocument (new XDeclaration ("1.0", "utf-8", "yes"), tlElement); + return xDocument; + // } catch (ParseException parseException) { + // throw; + // } catch (Exception e) { + // throw new ParseException ($"Unknown error parsing {inFile}: {e.Message}", e.InnerException); + // } + } + + public override void EnterComment ([NotNull] CommentContext context) + { + var commentText = context.GetText (); + InterpretCommentText (commentText); + } + + public override void EnterClass_declaration ([NotNull] Class_declarationContext context) + { + var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: false); + var attributes = GatherAttributes (context.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isObjC = AttributesContains (context.attributes (), kObjC); + var accessibility = ToAccess (context.access_level_modifier ()); + var isFinal = context.final_clause () != null || accessibility != kOpenCap; + var typeDecl = ToTypeDeclaration (kClass, UnTick (context.class_name ().GetText ()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false); + if (generics != null) + typeDecl.Add (generics); + currentElement.Push (typeDecl); + } + + public override void ExitClass_declaration ([NotNull] Class_declarationContext context) + { + var classElem = currentElement.Pop (); + var givenClassName = classElem.Attribute (kName).Value; + var actualClassName = UnTick (context.class_name ().GetText ()); + if (givenClassName != actualClassName) + throw new ParseException ($"class name mismatch on exit declaration: expected {actualClassName} but got {givenClassName}"); + AddClassToCurrentElement (classElem); + } + + public override void EnterStruct_declaration ([NotNull] Struct_declarationContext context) + { + var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); + var attributes = GatherAttributes (context.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isFinal = true; // structs are always final + var isObjC = AttributesContains (context.attributes (), kObjC); + var accessibility = ToAccess (context.access_level_modifier ()); + var typeDecl = ToTypeDeclaration (kStruct, UnTick (context.struct_name ().GetText ()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false); + if (generics != null) + typeDecl.Add (generics); + currentElement.Push (typeDecl); + } + + public override void ExitStruct_declaration ([NotNull] Struct_declarationContext context) + { + var structElem = currentElement.Pop (); + var givenStructName = structElem.Attribute (kName).Value; + var actualStructName = UnTick (context.struct_name ().GetText ()); + if (givenStructName != actualStructName) + throw new ParseException ($"struct name mismatch on exit declaration: expected {actualStructName} but got {givenStructName}"); + AddStructToCurrentElement (structElem); + } + + public override void EnterEnum_declaration ([NotNull] Enum_declarationContext context) + { + var inheritanceClause = context.union_style_enum ()?.type_inheritance_clause () ?? + context.raw_value_style_enum ()?.type_inheritance_clause (); + var inheritance = GatherInheritance (inheritanceClause, forceProtocolInheritance: true, removeNonProtocols: true); + var attributes = GatherAttributes (context.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isFinal = true; // enums are always final + var isObjC = AttributesContains (context.attributes (), kObjC); + var accessibility = ToAccess (context.access_level_modifier ()); + var typeDecl = ToTypeDeclaration (kEnum, EnumName (context), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics (EnumGenericParameters (context), EnumGenericWhere (context), false); + if (generics != null) + typeDecl.Add (generics); + currentElement.Push (typeDecl); + } + + public override void ExitEnum_declaration ([NotNull] Enum_declarationContext context) + { + var enumElem = currentElement.Pop (); + var givenEnumName = enumElem.Attribute (kName).Value; + var actualEnumName = EnumName (context); + if (givenEnumName != actualEnumName) + throw new ParseException ($"enum name mismatch on exit declaration: expected {actualEnumName} but got {givenEnumName}"); + + var rawType = GetEnumRawType (context); + if (rawType != null) + enumElem.Add (rawType); + + AddEnumToCurrentElement (enumElem); + } + + static string EnumName (Enum_declarationContext context) + { + return UnTick (context.union_style_enum () != null ? + context.union_style_enum ().enum_name ().GetText () : + context.raw_value_style_enum ().enum_name ().GetText ()); + } + + XAttribute GetEnumRawType (Enum_declarationContext context) + { + var alias = EnumTypeAliases (context).FirstOrDefault (ta => ta.typealias_name ().GetText () == kRawValue); + if (alias == null) + return null; + var rawType = TypeText (alias.typealias_assignment ().type ()); + return new XAttribute (kRawType, rawType); + } + + IEnumerable EnumTypeAliases (Enum_declarationContext context) + { + if (context.union_style_enum () != null) + return UnionTypeAliases (context.union_style_enum ()); + else + return RawTypeAliases (context.raw_value_style_enum ()); + } + + IEnumerable UnionTypeAliases (Union_style_enumContext context) + { + var members = context.union_style_enum_members (); + while (members != null) { + if (members.union_style_enum_member () != null) { + var member = members.union_style_enum_member (); + if (member.nominal_declaration ()?.typealias_declaration () != null) + yield return member.nominal_declaration ().typealias_declaration (); + } + members = members.union_style_enum_members (); + } + yield break; + } + + IEnumerable RawTypeAliases (Raw_value_style_enumContext context) + { + var members = context.raw_value_style_enum_members (); + while (members != null) { + if (members.raw_value_style_enum_member () != null) { + var member = members.raw_value_style_enum_member (); + if (member.nominal_declaration ()?.typealias_declaration () != null) + yield return member.nominal_declaration ().typealias_declaration (); + } + members = members.raw_value_style_enum_members (); + } + yield break; + } + + public override void EnterRaw_value_style_enum_case_clause ([NotNull] Raw_value_style_enum_case_clauseContext context) + { + var enumElements = new XElement (kElements); + foreach (var enumCase in RawCases (context.raw_value_style_enum_case_list ())) { + var enumElement = ToRawEnumElement (enumCase); + enumElements.Add (enumElement); + } + AddEnumNonEmptyElements (enumElements); + } + + public override void EnterUnion_style_enum_case_clause ([NotNull] Union_style_enum_case_clauseContext context) + { + var enumElements = new XElement (kElements); + foreach (var enumCase in UnionCases (context.union_style_enum_case_list ())) { + var enumElement = ToUnionEnumElement (enumCase); + enumElements.Add (enumElement); + } + AddEnumNonEmptyElements (enumElements); + } + + void AddEnumNonEmptyElements (XElement enumElements) + { + if (enumElements.HasElements) { + var currentEnum = currentElement.Peek (); + if (currentEnum.Attribute (kKind)?.Value != kEnum) + throw new ParseException ("Current element needs to be an enum"); + + var existingElements = currentEnum.Element (kElements); + if (existingElements != null) { + foreach (var elem in enumElements.Elements ()) { + existingElements.Add (elem); + } + } else { + currentEnum.Add (enumElements); + } + } + } + + IEnumerable RawCases (Raw_value_style_enum_case_listContext context) + { + while (context != null) { + if (context.raw_value_style_enum_case () != null) { + yield return context.raw_value_style_enum_case (); + } + context = context.raw_value_style_enum_case_list (); + } + yield break; + } + + XElement ToRawEnumElement (Raw_value_style_enum_caseContext context) + { + var enumElem = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ()))); + var value = context.raw_value_assignment (); + if (value != null) + enumElem.Add (new XAttribute (kIntValue, value.raw_value_literal ().GetText ())); + return enumElem; + } + + IEnumerable UnionCases (Union_style_enum_case_listContext context) + { + while (context != null) { + if (context.union_style_enum_case () != null) { + yield return context.union_style_enum_case (); + } + context = context.union_style_enum_case_list (); + } + yield break; + } + + XElement ToUnionEnumElement (Union_style_enum_caseContext context) + { + var enumElement = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ()))); + if (context.tuple_type () != null) { + var tupString = TypeText (context.tuple_type ()); + // special casing: + // the type of a union case is a tuple, but we special case + // unit tuples to be just the type of the unit + // which may be something like ((((((())))))) + // in which case we want to let it come through as is. + // a unit tuple may also have a type label which we don't care + // about so make that go away too. + + if (tupString.IndexOf (',') < 0 && tupString.IndexOf (':') < 0) { + var pastLastOpen = tupString.LastIndexOf ('(') + 1; + var firstClosed = tupString.IndexOf (')'); + if (pastLastOpen != firstClosed) { + tupString = tupString.Substring (pastLastOpen, firstClosed - pastLastOpen); + var colonIndex = tupString.IndexOf (':'); + if (colonIndex >= 0) { + tupString = tupString.Substring (colonIndex + 1); + } + } + } + enumElement.Add (new XAttribute (kType, tupString)); + } + return enumElement; + } + + public override void EnterProtocol_declaration ([NotNull] Protocol_declarationContext context) + { + var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); + var attributes = GatherAttributes (context.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isFinal = true; // protocols don't have final + var isObjC = AttributesContains (context.attributes (), kObjC); + var accessibility = ToAccess (context.access_level_modifier ()); + var typeDecl = ToTypeDeclaration (kProtocol, UnTick (context.protocol_name ().GetText ()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + currentElement.Push (typeDecl); + } + + public override void ExitProtocol_declaration ([NotNull] Protocol_declarationContext context) + { + var protocolElem = currentElement.Pop (); + var givenProtocolName = protocolElem.Attribute (kName).Value; + var actualProtocolName = UnTick (context.protocol_name ().GetText ()); + if (givenProtocolName != actualProtocolName) + throw new ParseException ($"protocol name mismatch on exit declaration: expected {actualProtocolName} but got {givenProtocolName}"); + if (currentElement.Peek ().Name != kModule) + throw new ParseException ($"Expected a module on the element stack but found {currentElement.Peek ()}"); + currentElement.Peek ().Add (protocolElem); + } + + public override void EnterProtocol_associated_type_declaration ([NotNull] Protocol_associated_type_declarationContext context) + { + var conformingProtocols = GatherConformingProtocols (context.type_inheritance_clause ()); + var defaultDefn = TypeText (context.typealias_assignment ()?.type ()); + var assocType = new XElement (kAssociatedType, + new XAttribute (kName, UnTick (context.typealias_name ().GetText ()))); + if (defaultDefn != null) + assocType.Add (new XAttribute (kDefaultType, UnTick (defaultDefn))); + if (conformingProtocols != null && conformingProtocols.Count > 0) { + var confomingElem = new XElement (kConformingProtocols, conformingProtocols.ToArray ()); + assocType.Add (confomingElem); + associatedTypesWithConformance.Add (assocType); + } + AddAssociatedTypeToCurrentElement (assocType); + } + + List GatherConformingProtocols (Type_inheritance_clauseContext context) + { + if (context == null) + return null; + var elems = new List (); + if (context.class_requirement () != null) { + // not sure what to do here + // this is just the keyword 'class' + } + var inheritance = context.type_inheritance_list (); + while (inheritance != null) { + var elem = inheritance.GetText (); + var name = TypeText (inheritance.type_identifier ()); + if (name != null) + elems.Add (new XElement (kConformingProtocol, new XAttribute (kName, UnTick (name)))); + inheritance = inheritance.type_inheritance_list (); + } + return elems; + } + + static Generic_parameter_clauseContext EnumGenericParameters (Enum_declarationContext context) + { + return context.union_style_enum ()?.generic_parameter_clause () ?? + context.raw_value_style_enum ()?.generic_parameter_clause (); + } + + static Generic_where_clauseContext EnumGenericWhere (Enum_declarationContext context) + { + return context.union_style_enum ()?.generic_where_clause () ?? + context.raw_value_style_enum ()?.generic_where_clause (); + } + + public override void EnterFunction_declaration ([NotNull] Function_declarationContext context) + { + var head = context.function_head (); + var signature = context.function_signature (); + + var name = UnTick (context.function_name ().GetText ()); + var returnType = signature.function_result () != null ? TypeText (signature.function_result ().type ()) : "()"; + var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); + var isStatic = IsStaticOrClass (head.declaration_modifiers ()); + var hasThrows = signature.throws_clause () != null || signature.rethrows_clause () != null; + var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); + var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); + var isConvenienceInit = false; + var operatorKind = kNone; + var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); + var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); + var isProperty = false; + var attributes = GatherAttributes (head.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isAsync = signature.async_clause () != null; + var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync, attributes); + var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), true); + if (generics != null) + functionDecl.Add (generics); + + + functions.Add (new Tuple (context, functionDecl)); + currentElement.Push (functionDecl); + } + + public override void ExitFunction_declaration ([NotNull] Function_declarationContext context) + { + ExitFunctionWithName (UnTick (context.function_name ().GetText ())); + } + + void ExitFunctionWithName (string expectedName) + { + var functionDecl = currentElement.Pop (); + if (functionDecl.Name != kFunc) + throw new ParseException ($"Expected a func node but got a {functionDecl.Name}"); + var givenName = functionDecl.Attribute (kName); + if (givenName == null) + throw new ParseException ("func node doesn't have a name element"); + if (givenName.Value != expectedName) + throw new ParseException ($"Expected a func node with name {expectedName} but got {givenName.Value}"); + + AddObjCSelector (functionDecl); + + AddElementToParentMembers (functionDecl); + } + + void AddObjCSelector (XElement functionDecl) + { + var selectorFactory = new ObjCSelectorFactory (functionDecl); + var selector = selectorFactory.Generate (); + if (!String.IsNullOrEmpty (selector)) { + functionDecl.Add (new XAttribute (kObjCSelector, selector)); + } + } + + XElement PeekAsFunction () + { + var functionDecl = currentElement.Peek (); + if (functionDecl.Name != kFunc) + throw new ParseException ($"Expected a func node but got a {functionDecl.Name}"); + return functionDecl; + } + + void AddElementToParentMembers (XElement elem) + { + var parent = currentElement.Peek (); + if (parent.Name == kModule) { + parent.Add (elem); + return; + } + var memberElem = GetOrCreate (parent, kMembers); + memberElem.Add (elem); + } + + bool IsInInstance () + { + var parent = currentElement.Peek (); + return parent.Name != kModule; + } + + bool HasObjCElement (XElement elem) + { + var objcAttr = elem.Descendants () + .FirstOrDefault (el => el.Name == kAttribute && el.Attribute ("name")?.Value == kObjC); + return objcAttr != null; + } + + public override void EnterInitializer_declaration ([NotNull] Initializer_declarationContext context) + { + var head = context.initializer_head (); + + var name = kDotCtor; + + // may be optional, otherwise return type is the instance type + var returnType = GetInstanceName () + (head.OpQuestion () != null ? "?" : ""); + var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); + var isStatic = true; + var hasThrows = context.throws_clause () != null || context.rethrows_clause () != null; + var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); + var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); + var isConvenienceInit = ModifiersContains (head.declaration_modifiers (), kConvenience); + var operatorKind = kNone; + var attributes = GatherAttributes (head.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); + var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); + var isProperty = false; + var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, + isAsync: false, attributes); + currentElement.Push (functionDecl); + } + + public override void ExitInitializer_declaration ([NotNull] Initializer_declarationContext context) + { + ExitFunctionWithName (kDotCtor); + } + + public override void EnterDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context) + { + var name = kDotDtor; + var returnType = "()"; + // this might have to be forced to public, otherwise deinit is always internal, which it + // decidedly is NOT. + var accessibility = kPublic; + var isStatic = false; + var hasThrows = false; + var isFinal = ModifiersContains (context.declaration_modifiers (), kFinal); + var isOptional = ModifiersContains (context.declaration_modifiers (), kOptional); + var isConvenienceInit = false; + var operatorKind = kNone; + var attributes = GatherAttributes (context.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isMutating = ModifiersContains (context.declaration_modifiers (), kMutating); + var isRequired = ModifiersContains (context.declaration_modifiers (), kRequired); + var isProperty = false; + var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + // always has two parameter lists: (instance)() + currentElement.Push (functionDecl); + var parameterLists = new XElement (kParameterLists, MakeInstanceParameterList ()); + currentElement.Pop (); + + parameterLists.Add (new XElement (kParameterList, new XAttribute (kIndex, "1"))); + functionDecl.Add (parameterLists); + + currentElement.Push (functionDecl); + } + + public override void ExitDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context) + { + ExitFunctionWithName (kDotDtor); + } + + public override void EnterSubscript_declaration ([NotNull] Subscript_declarationContext context) + { + // subscripts are...funny. + // They have one parameter list but expand out to two function declarations + // To handle this, we process the parameter list here for the getter + // If there's a setter, we make one of those too. + // Then since we're effectively done, we push a special XElement on the stack + // named IGNORE which will make the parameter list event handler exit. + // On ExitSubscript_declaration, we remove the IGNORE tag + + var head = context.subscript_head (); + var resultType = TypeText (context.subscript_result ().type ()); + var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); + var attributes = GatherAttributes (head.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isStatic = false; + var hasThrows = false; + var isAsync = HasAsync (context.getter_setter_keyword_block ()?.getter_keyword_clause ()); + var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); + var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); + var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); + var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); + var isProperty = true; + + var getParamList = MakeParameterList (head.parameter_clause ().parameter_list (), 1, true); + var getFunc = ToFunctionDeclaration (kGetSubscript, resultType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); + + currentElement.Push (getFunc); + var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList); + currentElement.Pop (); + + getFunc.Add (getParamLists); + AddObjCSelector (getFunc); + + AddElementToParentMembers (getFunc); + + var setParamList = context.getter_setter_keyword_block ()?.setter_keyword_clause () != null + ? MakeParameterList (head.parameter_clause ().parameter_list (), 1, true, startIndex: 1) : null; + + + if (setParamList != null) { + var index = 0; + var parmName = context.getter_setter_keyword_block ().setter_keyword_clause ().new_value_name ()?.GetText () + ?? kNewValue; + var newValueParam = new XElement (kParameter, new XAttribute (nameof (index), index.ToString ()), + new XAttribute (kType, resultType), new XAttribute (kPublicName, ""), + new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false)); + setParamList.AddFirst (newValueParam); + + var setFunc = ToFunctionDeclaration (kSetSubscript, "()", accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + currentElement.Push (setFunc); + var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList); + currentElement.Pop (); + + setFunc.Add (setParamLists); + AddObjCSelector (setFunc); + AddElementToParentMembers (setFunc); + } + + // this makes the subscript parameter list get ignored because we already handled it. + PushIgnore (); + } + + public override void ExitSubscript_declaration ([NotNull] Subscript_declarationContext context) + { + PopIgnore (); + } + + string TypeText (ParserRuleContext ty) + { + return SyntaxDesugaringParser.TypeText (inputStream, ty); + } + + public override void EnterVariable_declaration ([NotNull] Variable_declarationContext context) + { + var head = context.variable_declaration_head (); + var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); + var attributes = GatherAttributes (head.attributes ()); + var isDeprecated = CheckForDeprecated (attributes); + var isUnavailable = CheckForUnavailable (attributes); + var isStatic = ModifiersContains (head.declaration_modifiers (), kStatic); + var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); + var isLet = head.let_clause () != null; + var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); + var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); + var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); + var isProperty = true; + + foreach (var tail in context.variable_declaration_tail ()) { + var name = UnTick (tail.variable_name ().GetText ()); + var resultType = TypeText (tail.type_annotation ().type ()); + var hasThrows = false; + var isAsync = HasAsync (tail.getter_setter_keyword_block ()?.getter_keyword_clause ()); + + var getParamList = new XElement (kParameterList, new XAttribute (kIndex, "1")); + var getFunc = ToFunctionDeclaration ("get_" + name, + resultType, accessibility, isStatic, hasThrows, isFinal, isOptional, + isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, + isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); + + currentElement.Push (getFunc); + var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList); + currentElement.Pop (); + getFunc.Add (getParamLists); + AddElementToParentMembers (getFunc); + AddObjCSelector (getFunc); + + var setParamList = HasSetter (tail, isLet) ? + new XElement (kParameterList, new XAttribute (kIndex, "1")) : null; + + if (setParamList != null) { + var parmName = tail.getter_setter_keyword_block ()?.setter_keyword_clause ().new_value_name ()?.GetText () + ?? kNewValue; + var setterType = EscapePossibleClosureType (resultType); + var newValueParam = new XElement (kParameter, new XAttribute (kIndex, "0"), + new XAttribute (kType, setterType), new XAttribute (kPublicName, parmName), + new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false)); + setParamList.Add (newValueParam); + var setFunc = ToFunctionDeclaration ("set_" + name, + "()", accessibility, isStatic, hasThrows, isFinal, isOptional, + isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, + isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + currentElement.Push (setFunc); + var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList); + currentElement.Pop (); + + setFunc.Add (setParamLists); + AddElementToParentMembers (setFunc); + AddObjCSelector (setFunc); + } + + var prop = new XElement (kProperty, new XAttribute (kName, name), + new XAttribute (nameof (accessibility), accessibility), + new XAttribute (kType, resultType), + new XAttribute (kStorage, kComputed), + new XAttribute (nameof (isStatic), XmlBool (isStatic)), + new XAttribute (nameof (isLet), XmlBool (isLet)), + new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated)), + new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable)), + new XAttribute (nameof (isOptional), XmlBool (isOptional))); + AddElementToParentMembers (prop); + } + + PushIgnore (); + } + + bool HasSetter (Variable_declaration_tailContext context, bool isLet) + { + // conditions for having a setter: + // defaultInitializer and getter_setter_keyword are both null (public var foo: Type) + // defaultInitializer is not null (public var foo: Type = initialValue) + // getter_setter_keyword_block is non-null and the getter_setter_keyword_block + // has a non-null setter_keyword_clause (public var foo:Type { get; set; }, public foo: Type { set } + + var defaultInitializer = context.defaultInitializer (); + var gettersetter = context.getter_setter_keyword_block (); + + return !isLet && ((defaultInitializer == null && gettersetter == null) || + defaultInitializer != null || + gettersetter?.setter_keyword_clause () != null); + } + + public override void EnterExtension_declaration ([NotNull] Extension_declarationContext context) + { + var onType = UnTick (TypeText (context.type_identifier ())); + var inherits = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); + // why, you say, why put a kKind tag into an extension? + // The reason is simple: this is a hack. Most of the contents + // of an extension are the same as a class and as a result we can + // pretend that it's a class and everything will work to fill it out + // using the class/struct/enum code for members. + var extensionElem = new XElement (kExtension, + new XAttribute (nameof (onType), onType), + new XAttribute (kKind, kClass)); + if (inherits?.Count > 0) + extensionElem.Add (new XElement (nameof (inherits), inherits.ToArray ())); + currentElement.Push (extensionElem); + extensions.Add (extensionElem); + } + + public override void ExitExtension_declaration ([NotNull] Extension_declarationContext context) + { + var extensionElem = currentElement.Pop (); + var onType = extensionElem.Attribute (kOnType); + var givenOnType = onType.Value; + var actualOnType = UnTick (TypeText (context.type_identifier ())); + if (givenOnType != actualOnType) + throw new Exception ($"extension type mismatch on exit declaration: expected {actualOnType} but got {givenOnType}"); + // remove the kKind attribute - you've done your job. + extensionElem.Attribute (kKind)?.Remove (); + + currentElement.Peek ().Add (extensionElem); + } + + public override void ExitImport_statement ([NotNull] Import_statementContext context) + { + // this is something like: import class Foo.Bar + // and we're not handling that yet + if (context.import_kind () != null) + return; + importModules.Add (context.import_path ().GetText ()); + } + + public override void EnterOperator_declaration ([NotNull] Operator_declarationContext context) + { + var operatorElement = InfixOperator (context.infix_operator_declaration ()) + ?? PostfixOperator (context.postfix_operator_declaration ()) + ?? PrefixOperator (context.prefix_operator_declaration ()); + operators.Add (operatorElement); + + currentElement.Peek ().Add (operatorElement); + } + + public override void EnterOptional_type ([NotNull] Optional_typeContext context) + { + } + + XElement InfixOperator (Infix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator (kInfix, context.@operator (), + context.infix_operator_group ()?.precedence_group_name ()?.GetText () ?? ""); + } + + XElement PostfixOperator (Postfix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator (kPostfix, context.@operator (), ""); + } + + XElement PrefixOperator (Prefix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator (kPrefix, context.@operator (), ""); + } + + XElement GeneralOperator (string operatorKind, OperatorContext context, string precedenceGroup) + { + return new XElement (kOperator, + new XAttribute (kName, context.Operator ().GetText ()), + new XAttribute (nameof (operatorKind), operatorKind), + new XAttribute (nameof (precedenceGroup), precedenceGroup)); + } + + XElement HandleGenerics (Generic_parameter_clauseContext genericContext, Generic_where_clauseContext whereContext, bool addParentGenerics) + { + if (genericContext == null) + return null; + var genericElem = new XElement (kGenericParameters); + if (addParentGenerics) + AddParentGenerics (genericElem); + foreach (var generic in genericContext.generic_parameter_list ().generic_parameter ()) { + var name = UnTick (TypeText (generic.type_name ())); + var genParam = new XElement (kParam, new XAttribute (kName, name)); + genericElem.Add (genParam); + var whereType = TypeText (generic.type_identifier ()) ?? + TypeText (generic.protocol_composition_type ()); + if (whereType != null) { + genericElem.Add (MakeConformanceWhere (name, whereType)); + } + } + + if (whereContext == null) + return genericElem; + + foreach (var requirement in whereContext.requirement_list ().requirement ()) { + if (requirement.conformance_requirement () != null) { + var name = UnTick (TypeText (requirement.conformance_requirement ().type_identifier () [0])); + + // if there is no protocol composition type, then it's the second type identifier + var from = TypeText (requirement.conformance_requirement ().protocol_composition_type ()) + ?? TypeText (requirement.conformance_requirement ().type_identifier () [1]); + genericElem.Add (MakeConformanceWhere (name, from)); + } else { + var name = UnTick (TypeText (requirement.same_type_requirement ().type_identifier ())); + var type = TypeText (requirement.same_type_requirement ().type ()); + genericElem.Add (MakeEqualityWhere (name, type)); + } + } + + return genericElem; + } + + public override void ExitTypealias_declaration ([NotNull] Typealias_declarationContext context) + { + var name = UnTick (context.typealias_name ().GetText ()); + var generics = TypeText (context.generic_parameter_clause ()) ?? ""; + var targetType = TypeText (context.typealias_assignment ().type ()); + var access = ToAccess (context.access_level_modifier ()); + var map = new XElement (kTypeAlias, new XAttribute (kName, name + generics), + new XAttribute (kAccessibility, access), + new XAttribute (kType, targetType)); + if (access != null) { + if (currentElement.Peek ().Name == kModule) { + typeAliasMap.Add (map); + } else { + var curr = currentElement.Peek (); + var aliaslist = curr.Element (kTypeAliases); + if (aliaslist == null) { + aliaslist = new XElement (kTypeAliases); + curr.Add (aliaslist); + } + aliaslist.Add (map); + } + } + } + + XElement MakeConformanceWhere (string name, string from) + { + return new XElement (kWhere, new XAttribute (nameof (name), name), + new XAttribute (kRelationship, kInherits), + new XAttribute (nameof (from), from)); + } + + XElement MakeEqualityWhere (string firsttype, string secondtype) + { + return new XElement (kWhere, new XAttribute (nameof (firsttype), firsttype), + new XAttribute (kRelationship, kEquals), + new XAttribute (nameof (secondtype), secondtype)); + } + + public override void ExitVariable_declaration ([NotNull] Variable_declarationContext context) + { + PopIgnore (); + } + + void PushIgnore () + { + currentElement.Push (new XElement (kIgnore)); + } + + void PopIgnore () + { + var elem = currentElement.Pop (); + if (elem.Name != kIgnore) + throw new ParseException ($"Expected an {kIgnore} element, but got {elem}"); + } + + bool ShouldIgnore () + { + return currentElement.Peek ().Name == kIgnore; + } + + public override void EnterParameter_clause ([NotNull] Parameter_clauseContext context) + { + if (ShouldIgnore ()) + return; + + var parameterLists = new XElement (kParameterLists); + XElement instanceList = MakeInstanceParameterList (); + var formalIndex = 0; + if (instanceList != null) { + parameterLists.Add (instanceList); + formalIndex = 1; + } + + var formalArguments = MakeParameterList (context.parameter_list (), formalIndex, false); + + parameterLists.Add (formalArguments); + currentElement.Peek ().Add (parameterLists); + } + + XElement MakeParameterList (Parameter_listContext parmList, int index, bool isSubscript, int startIndex = 0) + { + var formalArguments = new XElement (kParameterList, new XAttribute (kIndex, index.ToString ())); + + if (parmList != null) { + var i = startIndex; + foreach (var parameter in parmList.parameter ()) { + var parameterElement = ToParameterElement (parameter, i, isSubscript); + formalArguments.Add (parameterElement); + i++; + } + } + return formalArguments; + } + + XElement MakeInstanceParameterList () + { + var topElem = currentElement.Peek (); + if (topElem.Name == kModule) + return null; + if (topElem.Name != kFunc) + throw new ParseException ($"Expecting a func node but got {topElem.Name}"); + if (NominalParentAfter (0) == null) + return null; + var funcName = topElem.Attribute (kName).Value; + var isStatic = topElem.Attribute (kIsStatic).Value == "true"; + var isCtorDtor = IsCtorDtor (funcName); + var isClass = NominalParentAfter (0).Attribute (kKind).Value == kClass; + var instanceName = GetInstanceName (); + var type = $"{(isClass ? "" : "inout ")}{instanceName}{(isCtorDtor ? ".Type" : "")}"; + var parameter = new XElement (kParameter, new XAttribute (kType, type), + new XAttribute (kIndex, "0"), new XAttribute (kPublicName, "self"), + new XAttribute (kPrivateName, "self"), new XAttribute (kIsVariadic, "false")); + return new XElement (kParameterList, new XAttribute (kIndex, "0"), parameter); + } + + void AddParentGenerics (XElement genericResult) + { + var parentGenerics = new List (); + for (int i =0; i < currentElement.Count; i++) { + var elem = currentElement.ElementAt (i); + if (!IsNominal (elem)) + continue; + var elemGenerics = elem.Element (kGenericParameters); + if (elemGenerics == null) + continue; + foreach (var param in elemGenerics.Descendants (kParam)) { + parentGenerics.Add (new XElement (param)); + } + } + genericResult.Add (parentGenerics.ToArray ()); + } + + XElement NominalParentAfter (int start) + { + for (var i = start + 1; i < currentElement.Count; i++) { + var elem = currentElement.ElementAt (i); + if (IsNominal (elem)) + return elem; + } + return null; + } + + bool IsNominal (XElement elem) + { + var kind = elem.Attribute (kKind)?.Value; + return kind != null && (kind == kClass || kind == kStruct || kind == kEnum || kind == kProtocol); + } + + string GetInstanceName () + { + var nameBuffer = new StringBuilder (); + for (int i = 0; i < currentElement.Count; i++) { + var elem = currentElement.ElementAt (i); + if (IsNominal (elem)) { + if (elem.Name == kExtension) + return elem.Attribute (kOnType).Value; + if (nameBuffer.Length > 0) + nameBuffer.Insert (0, '.'); + nameBuffer.Insert (0, elem.Attribute (kName).Value); + var generics = elem.Element (kGenericParameters); + if (generics != null) { + AddGenericsToName (nameBuffer, generics); + } + } + } + nameBuffer.Insert (0, '.'); + var module = currentElement.Last (); + nameBuffer.Insert (0, moduleName); + return nameBuffer.ToString (); + } + + void AddGenericsToName (StringBuilder nameBuffer, XElement generics) + { + var isFirst = true; + foreach (var name in GenericNames (generics)) { + if (isFirst) { + nameBuffer.Append ("<"); + isFirst = false; + } else { + nameBuffer.Append (", "); + } + nameBuffer.Append (name); + } + if (!isFirst) + nameBuffer.Append (">"); + } + + IEnumerable GenericNames (XElement generics) + { + return generics.Elements ().Where (elem => elem.Name == kParam).Select (elem => elem.Attribute (kName).Value); + } + + XElement ToParameterElement (ParameterContext context, int index, bool isSubscript) + { + var typeAnnotation = context.type_annotation (); + var isInOut = typeAnnotation.inout_clause () != null; + var type = TypeText (typeAnnotation.type ()); + var privateName = NoUnderscore (UnTick (context.local_parameter_name ()?.GetText ()) ?? ""); + var replacementPublicName = isSubscript ? "" : privateName; + var publicName = NoUnderscore (UnTick (context.external_parameter_name ()?.GetText ()) ?? replacementPublicName); + var isVariadic = context.range_operator () != null; + if (isVariadic) + type = $"Swift.Array<{type}>"; + var isEscaping = AttributesContains (typeAnnotation.attributes (), kEscaping); + var isAutoClosure = AttributesContains (typeAnnotation.attributes (), kAutoClosure); + var typeBuilder = new StringBuilder (); + if (isEscaping) + typeBuilder.Append ("@escaping[] "); + if (isAutoClosure) + typeBuilder.Append ("@autoclosure[] "); + if (isInOut) + typeBuilder.Append ("inout "); + typeBuilder.Append (type); + type = typeBuilder.ToString (); + + var paramElement = new XElement (kParameter, new XAttribute (nameof (index), index.ToString ()), + new XAttribute (nameof (type), type), new XAttribute (nameof (publicName), publicName), + new XAttribute (nameof (privateName), privateName), new XAttribute (nameof (isVariadic), XmlBool (isVariadic))); + return paramElement; + } + + static string NoUnderscore (string s) + { + return s == "_" ? "" : s; + } + + XElement GatherAttributes (AttributesContext context) + { + if (context == null) + return null; + var attributes = new XElement (kAttributes); + foreach (var attr in context.attribute ()) { + var attrElement = GatherAttribute (attr); + if (attrElement != null) + attributes.Add (attrElement); + } + return attributes.HasElements ? attributes : null; + } + + XElement GatherAttribute (AttributeContext context) + { + var attribute = new XElement (kAttribute, new XAttribute (kName, context.attribute_name ().GetText ())); + if (context.attribute_argument_clause () != null) { + var parameters = GatherParameters (context.attribute_argument_clause ()?.balanced_tokens ()); + if (parameters != null) + attribute.Add (parameters); + } + return attribute; + } + + XElement GatherParameters (Balanced_tokensContext context) + { + if (context == null) + return null; + var parameterlist = new XElement (kAttributeParameterList); + + foreach (var balancedToken in context.balanced_token ()) { + var parameter = ToAttributeParameter (balancedToken); + if (parameter != null) + parameterlist.Add (parameter); + } + return parameterlist.HasElements ? parameterlist : null; + } + + XElement ToAttributeParameter (Balanced_tokenContext context) + { + if (context.balanced_tokens () != null) { + var sublist = new XElement (kAttributeParameter, new XAttribute (kKind, kSublist)); + var subparams = GatherParameters (context.balanced_tokens ()); + if (subparams != null) + sublist.Add (subparams); + return sublist; + } + + if (context.label_identifier () != null) { + var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), + new XAttribute (kValue, context.label_identifier ().GetText ())); + return label; + } + + if (context.literal () != null) { + var literal = new XElement (kAttributeParameter, new XAttribute (kKind, kLiteral), + new XAttribute (kValue, context.literal ().GetText ())); + return literal; + } + + // make the operator look like a label + if (context.@operator () != null) { + var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), + new XAttribute (kValue, context.@operator ().GetText ())); + return label; + } + + if (context.any_punctuation_for_balanced_token () != null) { + var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), + new XAttribute (kValue, context.any_punctuation_for_balanced_token ().GetText ())); + return label; + } + + return null; + } + + List GatherInheritance (Type_inheritance_clauseContext context, bool forceProtocolInheritance, + bool removeNonProtocols = false) + { + var inheritance = new List (); + if (context == null) + return inheritance; + var list = context.type_inheritance_list (); + bool first = true; + while (list != null) { + var inheritanceKind = forceProtocolInheritance ? kProtocol : + (inheritance.Count > 0 ? kProtocol : kLittleUnknown); + var type = TypeText (list.type_identifier ()); + if (!(first && removeNonProtocols && TypeIsNotProtocol (type))) { + var elem = new XElement (kInherit, new XAttribute (kType, type), + new XAttribute (nameof (inheritanceKind), inheritanceKind)); + inheritance.Add (elem); + if (inheritanceKind == kLittleUnknown) + unknownInheritance.Add (elem); + } + first = false; + list = list.type_inheritance_list (); + } + + return inheritance; + } + + bool TypeIsNotProtocol (string type) + { + // special case this - the type database as this as "other" + // which is technically not a protocol, but it is a protocol. + if (type == "Swift.Error") + return false; + var parts = type.Split ('.'); + if (parts.Length == 1) + return true; // generic + var module = parts [0]; + if (!typeDatabase.ModuleNames.Contains (module)) { + moduleLoader.Load (module, typeDatabase); + } + var entity = typeDatabase.TryGetEntityForSwiftName (type); + if (entity != null && entity.EntityType != EntityType.Protocol) + return true; + return false; + } + + XElement ToTypeDeclaration (string kind, string name, string accessibility, bool isObjC, + bool isFinal, bool isDeprecated, bool isUnavailable, List inherits, XElement generics, + XElement attributes) + { + var xobjects = new List (); + if (generics != null) + xobjects.Add (generics); + xobjects.Add (new XAttribute (nameof (kind), kind)); + xobjects.Add (new XAttribute (nameof (name), name)); + xobjects.Add (new XAttribute (nameof (accessibility), accessibility)); + xobjects.Add (new XAttribute (nameof (isObjC), XmlBool (isObjC))); + xobjects.Add (new XAttribute (nameof (isFinal), XmlBool (isFinal))); + xobjects.Add (new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated))); + xobjects.Add (new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable))); + + xobjects.Add (new XElement (kMembers)); + if (inherits != null && inherits.Count > 0) + xobjects.Add (new XElement (nameof (inherits), inherits.ToArray ())); + if (attributes != null) + xobjects.Add (attributes); + return new XElement (kTypeDeclaration, xobjects.ToArray ()); + } + + + XElement ToFunctionDeclaration (string name, string returnType, string accessibility, + bool isStatic, bool hasThrows, bool isFinal, bool isOptional, bool isConvenienceInit, + string objCSelector, string operatorKind, bool isDeprecated, bool isUnavailable, + bool isMutating, bool isRequired, bool isProperty, bool isAsync, XElement attributes) + { + var decl = new XElement (kFunc, new XAttribute (nameof (name), name), new XAttribute (nameof (returnType), returnType), + new XAttribute (nameof (accessibility), accessibility), new XAttribute (nameof (isStatic), XmlBool (isStatic)), + new XAttribute (nameof (hasThrows), XmlBool (hasThrows)), new XAttribute (nameof (isFinal), XmlBool (isFinal)), + new XAttribute (nameof (isOptional), XmlBool (isOptional)), + new XAttribute (nameof (isConvenienceInit), XmlBool (isConvenienceInit)), + new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated)), + new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable)), + new XAttribute (nameof (isRequired), XmlBool (isRequired)), + new XAttribute (kIsAsync, XmlBool (isAsync)), + new XAttribute (kIsProperty, XmlBool (isProperty)), + new XAttribute (nameof (isMutating), XmlBool (isMutating))); + + if (operatorKind != null) { + decl.Add (new XAttribute (nameof (operatorKind), operatorKind)); + } + if (objCSelector != null) { + decl.Add (new XAttribute (nameof (objCSelector), objCSelector)); + } + if (attributes != null) { + decl.Add (attributes); + } + return decl; + } + + bool CheckForDeprecated (XElement attributes) + { + var availableTags = AvailableAttributes (attributes); + foreach (var attribute in availableTags) { + var args = AttrbuteParameters (attribute); + var platform = args [0]; + if (!PlatformMatches (platform)) + continue; + + var deprecatedIndex = args.IndexOf (kDeprecated); + if (deprecatedIndex < 0) + continue; + var deprecatedVersion = GetVersionAfter (args, deprecatedIndex); + if (TargetVersionIsLessOrEqual (deprecatedVersion)) + return true; + } + return false; + } + + bool CheckForUnavailable (XElement attributes) + { + var availableTags = AvailableAttributes (attributes); + foreach (var attribute in availableTags) { + var args = AttrbuteParameters (attribute); + // if unavailable exists, need to match platform + if (args.IndexOf (kUnavailable) >= 0 && PlatformMatches (args [0])) + return true; + + } + return !CheckForAvailable (attributes); + } + + bool CheckForAvailable (XElement attributes) + { + var availableTags = AvailableAttributes (attributes); + foreach (var attribute in availableTags) { + var args = AttrbuteParameters (attribute); + if (IsShortHand (args)) { + return AvailableShorthand (args); + } else { + return AvailableLonghand (args); + } + } + return true; + } + + bool AvailableLonghand (List args) + { + // args will be plat , specifiers + // specificers will be: + // introduced: version + // deprecated: version + // obsoleted: version + // unavailable + var platform = args [0]; + if (!PlatformMatches (platform)) + return true; + + // if unavailable is present, it's not there. + if (args.IndexOf (kUnavailable) >= 0) + return false; + + var introIndex = args.IndexOf (kIntroduced); + if (introIndex >= 0) { + var introVersion = GetVersionAfter (args, introIndex); + if (TargetVersionIsGreaterOrEqual (introVersion)) + return false; + } + + var obsoletedIndex = args.IndexOf (kObsoleted); + if (obsoletedIndex >= 0) { + var obsoletedVersion = GetVersionAfter (args, obsoletedIndex); + if (TargetVersionIsLessOrEqual (obsoletedVersion)) + return false; + } + return true; + } + + bool AvailableShorthand (List args) + { + // args will be: plat ver . x . y , plat ver , ... * + + var startIndex = 0; + while (startIndex < args.Count) { + if (args [startIndex] == "*") + return false; + var platform = args [startIndex]; + if (PlatformMatches (platform)) { + var endIndex = args.IndexOf (",", startIndex + 1); + var versionNumber = args.GetRange (startIndex + 1, endIndex - startIndex); + if (TargetVersionIsGreaterOrEqual (versionNumber)) + return true; + } else { + startIndex = args.IndexOf (",", startIndex + 1); + } + } + return false; + } + + bool IsShortHand (List args) + { + if (args [1] == ",") + return false; + return args.Last () == "*"; + } + + Version GetVersionAfter (List pieces, int indexAfter) + { + var colonIndex = ColonAfter (pieces, indexAfter); + if (colonIndex < 0) + return new Version (0, 0); + var start = colonIndex + 1; + var end = start + 1; + while (end < pieces.Count && pieces [end] != ",") + end++; + var versionPieces = pieces.GetRange (start, end - start); + return VersionPiecesToVersion (versionPieces); + } + + int ColonAfter (List pieces, int start) + { + for (int i = start + 1; i < pieces.Count; i++) { + if (pieces [i] == ":") + return i; + if (pieces [i] == ",") + return -1; + } + return -1; + } + + bool TargetVersionIsGreaterOrEqual (List versionPieces) + { + var expectedVersion = VersionPiecesToVersion (versionPieces); + return TargetVersionIsGreaterOrEqual (expectedVersion); + } + + bool TargetVersionIsGreaterOrEqual (Version expectedVersion) + { + var compiledVersionStr = PlatformVersionFromModuleFlags (); + if (String.IsNullOrEmpty (compiledVersionStr)) + return true; // no version, I guess it's good? + var compiledVersion = new Version (compiledVersionStr); + return expectedVersion >= compiledVersion; + } + + bool TargetVersionIsLessOrEqual (List versionPieces) + { + var expectedVersion = VersionPiecesToVersion (versionPieces); + return TargetVersionIsLessOrEqual (expectedVersion); + } + + bool TargetVersionIsLessOrEqual (Version expectedVersion) + { + var compiledVersionStr = PlatformVersionFromModuleFlags (); + if (String.IsNullOrEmpty (compiledVersionStr)) + return true; // no version, I guess it's good? + var compiledVersion = new Version (compiledVersionStr); + return expectedVersion <= compiledVersion; + } + + Version VersionPiecesToVersion (List pieces) + { + var sb = new StringBuilder (); + for (int i = 0; i < pieces.Count; i++) { + if (pieces [i] == "." && i + 1 < pieces.Count && pieces [i + 1] == "*") + break; + sb.Append (pieces [i]); + } + return new Version (sb.ToString ()); + } + + IEnumerable AvailableAttributes (XElement attributes) + { + if (attributes == null) + return Enumerable.Empty (); + return attributes.Descendants (kAttribute).Where (el => el.Attribute (kName).Value == kAvailable); + + } + + List AttrbuteParameters (XElement attribute) + { + return attribute.Descendants (kAttributeParameter).Select (at => + at.Attribute (kValue)?.Value ?? "").ToList (); + } + + bool PlatformMatches (string platform) + { + var currentPlatform = PlatformFromModuleFlags (); + switch (platform) { + case "*": + case "swift": + return true; + case "iOS": + case "iOSApplicationExtension": + return currentPlatform.StartsWith ("ios", StringComparison.Ordinal) && + !currentPlatform.StartsWith ("ios-macabi", StringComparison.Ordinal); + case "macOS": + case "macOSApplicationExtension": + return currentPlatform.StartsWith ("macos", StringComparison.Ordinal); + case "macCatalyst": + case "macCatalystExtension": + return currentPlatform.StartsWith ("ios-macabi", StringComparison.Ordinal); + case "watchOS": + case "watchOSApplicationExtension": + return currentPlatform.StartsWith ("watch", StringComparison.Ordinal); + case "tvOS": + case "tvOSApplicationExtension": + return currentPlatform.StartsWith ("tv", StringComparison.Ordinal); + default: + return false; + } + } + + string PlatformFromModuleFlags () + { + var flagsValue = TargetFromModuleFlags (); + var os = flagsValue.ClangTargetOS (); + var digitIndex = FirstDigitIndex (os); + if (digitIndex < 0) + return os; + return os.Substring (0, digitIndex); + } + + static int FirstDigitIndex (string s) + { + var index = 0; + foreach (char c in s) { + if (Char.IsDigit (c)) + return index; + index++; + } + return -1; + } + + string PlatformVersionFromModuleFlags () + { + var flagsValue = TargetFromModuleFlags (); + var os = flagsValue.ClangTargetOS (); + var digitIndex = FirstDigitIndex (os); + if (digitIndex < 0) + return ""; + return os.Substring (digitIndex); + } + + string TargetFromModuleFlags () + { + string flagsValue = null; + if (!moduleFlags.TryGetValue ("target", out flagsValue)) { + return ""; + } + return flagsValue; + } + + static HashSet ModulesThatWeCanSkip = new HashSet () { + "XamGlue", + "RegisterAccess", + "_StringProcessing", + "_Concurrency", + }; + + void LoadReferencedModules () + { + var failures = new StringBuilder (); + foreach (var module in importModules) { + // XamGlue and RegisterAccess may very well get + // used, but the functions/types exported from these + // should never need to be loaded. + if (ModulesThatWeCanSkip.Contains (module)) + continue; + // if (!moduleLoader.Load (module, typeDatabase)) { + // if (failures.Length > 0) + // failures.Append (", "); + // failures.Append (module); + // } + } + if (failures.Length > 0) + throw new ParseException ($"Unable to load the following module(s): {failures.ToString ()}"); + } + + void PatchPossibleOperators () + { + foreach (var func in functions) { + var operatorKind = GetOperatorType (func.Item1); + if (operatorKind != OperatorType.None) { + func.Item2.Attribute (nameof (operatorKind))?.Remove (); + func.Item2.SetAttributeValue (nameof (operatorKind), operatorKind.ToString ()); + } + } + } + + void PatchPossibleBadInheritance () + { + foreach (var inh in unknownInheritance) { + var type = inh.Attribute (kType).Value; + if (IsLocalClass (type) || IsGlobalClass (type) || IsNSObject (type)) + inh.Attribute (kInheritanceKind).Value = kClass; + else + inh.Attribute (kInheritanceKind).Value = kProtocol; + } + } + + void PatchAssociatedTypeConformance () + { + foreach (var assoc in associatedTypesWithConformance) { + var conformances = assoc.Element (kConformingProtocols); + var first = conformances.Element (kConformingProtocol); + var className = (string)first.Attribute (kName); + if (IsLocalClass (className) || IsGlobalClass (className)) { + first.Remove (); + if (conformances.Nodes ().Count () == 0) + conformances.Remove (); + assoc.Add (new XElement (kSuperclass, new XAttribute (kName, className))); + } + } + } + + bool IsNSObject (string typeName) + { + return typeName == "ObjectiveC.NSObject"; + } + + bool IsLocalClass (string typeName) + { + return classes.Contains (typeName); + } + + bool IsGlobalClass (string typeName) + { + return typeDatabase.EntityForSwiftName (typeName)?.EntityType == EntityType.Class; + } + + void PatchExtensionSelfArgs () + { + foreach (var ext in extensions) { + var onType = (string)ext.Attribute (kOnType).Value; + var parts = onType.Split ('.'); + if (parts [0] == "XamGlue") + continue; + if (parts.Length > 1 && !typeDatabase.ModuleNames.Contains (parts [0])) { + moduleLoader.Load (parts [0], typeDatabase); + } + var entity = typeDatabase.EntityForSwiftName (onType); + if (entity != null) { + PatchExtensionSelfArgs (ext, entity); + } + } + } + + void PatchExtensionSelfArgs (XElement ext, Entity entity) + { + var isStructOrScalar = entity.IsStructOrEnum || entity.EntityType == EntityType.Scalar; + foreach (var func in ext.Descendants (kFunc)) { + var selfArg = SelfParameter (func); + if (selfArg == null) + continue; + var attr = selfArg.Attribute (kType); + var type = (string)attr.Value; + if (entity.Type.ContainsGenericParameters) { + type = entity.Type.ToFullyQualifiedNameWithGenerics (); + attr.Value = type; + var generics = entity.Type.Generics.ToXElement (); + if (func.Element (kGenericParameters) != null) { + var funcGenerics = func.Element (kGenericParameters); + funcGenerics.Remove (); + foreach (var generic in funcGenerics.Elements ()) + generics.Add (generic); + } + func.Add (generics); + } + if (isStructOrScalar && !type.StartsWith ("inout", StringComparison.Ordinal)) { + attr.Value = "inout " + type; + } + } + } + + XElement SelfParameter (XElement func) + { + var selfList = WhereIndexZero (func.Descendants (kParameterList)); + if (selfList == null) + return null; + var selfArg = WhereIndexZero (selfList.Descendants (kParameter)); + return selfArg; + } + + static XElement WhereIndexZero (IEnumerable elems) + { + return elems.FirstOrDefault (el => (string)el.Attribute (kIndex).Value == "0"); + } + + void PatchExtensionShortNames () + { + foreach (var ext in extensions) { + var onType = TypeSpecParser.Parse (ext.Attribute (kOnType).Value); + var replacementType = FullyQualify (onType); + ext.Attribute (kOnType).Value = replacementType.ToString (); + foreach (var func in ext.Descendants (kFunc)) { + var selfArg = SelfParameter (func); + if (selfArg == null) + continue; + onType = TypeSpecParser.Parse (selfArg.Attribute (kType).Value); + replacementType = FullyQualify (onType); + selfArg.Attribute (kType).Value = replacementType.ToString (); + } + } + } + + TypeSpec FullyQualify (TypeSpec spec) + { + switch (spec.Kind) { + case TypeSpecKind.Named: + return FullyQualify (spec as NamedTypeSpec); + case TypeSpecKind.Closure: + return FullyQualify (spec as ClosureTypeSpec); + case TypeSpecKind.ProtocolList: + return FullyQualify (spec as ProtocolListTypeSpec); + case TypeSpecKind.Tuple: + return FullyQualify (spec as TupleTypeSpec); + default: + throw new NotImplementedException ($"unknown TypeSpec kind {spec.Kind}"); + } + } + + TypeSpec FullyQualify (NamedTypeSpec named) + { + var dirty = false; + var newName = named.Name; + + if (!named.Name.Contains (".")) { + newName = ReplaceName (named.Name); + dirty = true; + } + + var genParts = new TypeSpec [named.GenericParameters.Count]; + var index = 0; + foreach (var gen in named.GenericParameters) { + var newGen = FullyQualify (gen); + genParts[index++] = newGen; + if (newGen != gen) + dirty = true; + } + + if (dirty) { + var newNamed = new NamedTypeSpec (newName, genParts); + newNamed.Attributes.AddRange (named.Attributes); + return newNamed; + } + + return named; + } + + TypeSpec FullyQualify (TupleTypeSpec tuple) + { + var dirty = false; + var parts = new TypeSpec [tuple.Elements.Count]; + var index = 0; + foreach (var spec in tuple.Elements) { + var newSpec = FullyQualify (spec); + if (newSpec != spec) + dirty = true; + parts [index++] = newSpec; + } + + if (dirty) { + var newTup = new TupleTypeSpec (parts); + newTup.Attributes.AddRange (tuple.Attributes); + return newTup; + } + + return tuple; + } + + TypeSpec FullyQualify (ProtocolListTypeSpec protolist) + { + var dirty = false; + var parts = new List (); + foreach (var named in protolist.Protocols.Keys) { + var newNamed = FullyQualify (named); + parts.Add (newNamed as NamedTypeSpec); + if (newNamed != named) + dirty = true; + } + + if (dirty) { + var newProto = new ProtocolListTypeSpec (parts); + newProto.Attributes.AddRange (protolist.Attributes); + return newProto; + } + + return protolist; + } + + TypeSpec FullyQualify (ClosureTypeSpec clos) + { + var dirty = false; + var args = FullyQualify (clos.Arguments); + if (args != clos.Arguments) + dirty = true; + var returnType = FullyQualify (clos.ReturnType); + if (returnType != clos.ReturnType) + dirty = true; + + if (dirty) { + var newClosure = new ClosureTypeSpec (args, returnType); + newClosure.Attributes.AddRange (clos.Attributes); + return newClosure; + } + + return clos; + } + + string ReplaceName (string nonQualified) + { + Exceptions.ThrowOnNull (nonQualified, nameof (nonQualified)); + + var localName = ReplaceLocalName (nonQualified); + if (localName != null) + return localName; + var globalName = ReplaceGlobalName (nonQualified); + if (globalName == null) + throw new ParseException ($"Unable to find fully qualified name for non qualified type {nonQualified}"); + return globalName; + } + + string ReplaceLocalName (string nonQualified) + { + foreach (var candidate in nominalTypes) { + var candidateWithoutModule = StripModule (candidate); + if (nonQualified == candidateWithoutModule) + return candidate; + } + return null; + } + + string ReplaceGlobalName (string nonQualified) + { + foreach (var module in importModules) { + var candidateName = $"{module}.{nonQualified}"; + var entity = typeDatabase.TryGetEntityForSwiftName (candidateName); + if (entity != null) + return candidateName; + } + if (nonQualified == "EveryProtocol") + return "XamGlue.EveryProtocol"; + return null; + } + + string StripModule (string fullyQualifiedName) + { + if (fullyQualifiedName.StartsWith (moduleName, StringComparison.Ordinal)) + // don't forget the '.' + return fullyQualifiedName.Substring (moduleName.Length + 1); + return fullyQualifiedName; + } + + static bool AttributesContains (AttributesContext context, string key) + { + if (context == null) + return false; + foreach (var attr in context.attribute ()) { + if (attr.attribute_name ().GetText () == key) + return true; + } + return false; + } + + static bool AttributesContainsAny (AttributesContext context, string [] keys) + { + foreach (var attr in context.attribute ()) { + var attrName = attr.attribute_name ().GetText (); + foreach (var key in keys) { + if (key == attrName) + return true; + } + } + return false; + } + + string EscapePossibleClosureType (string type) + { + var typeSpec = TypeSpecParser.Parse (type); + return typeSpec is ClosureTypeSpec ? "@escaping[] " + type : type; + } + + static Dictionary accessMap = new Dictionary () { + { kPublic, kPublicCap }, + { kPrivate, kPrivateCap }, + { kOpen, kOpenCap }, + { kInternal, kInternalCap }, + }; + + string AccessibilityFromModifiers (Declaration_modifiersContext context) + { + // If there is no context, we need to search for the appropriate context + // Swift has a number of "interesting" rules for implicitly defined accessibility + // If the parent element is a protocol, it's public + // If the parent is public, internal, or open then it's open + // If the parent is private or fileprivate, then it's private + + // Note that I don't make any distinction between private and fileprivate + // From our point of view, they're the same: they're things that we don't + // have access to and don't care about in writing a reflector of the public + // API. + if (context == null) { + var parentElem = NominalParentAfter (-1); + if (parentElem == null) + return kInternalCap; + if (parentElem.Attribute (kKind).Value == kProtocol) + return kPublicCap; + switch (parentElem.Attribute (kAccessibility).Value) { + case kPublic: + case kInternal: + case kOpen: + return kInternalCap; + case kPrivate: + case kFilePrivate: + return kPrivateCap; + } + } + foreach (var modifer in context.declaration_modifier ()) { + string result; + if (accessMap.TryGetValue (modifer.GetText (), out result)) + return result; + } + return kInternalCap; + } + + static bool HasAsync (Getter_keyword_clauseContext context) + { + return context == null ? false : context.async_clause () != null; + } + + static bool ModifiersContains (Declaration_modifiersContext context, string match) + { + if (context == null) + return false; + foreach (var modifier in context.declaration_modifier ()) { + var text = modifier.GetText (); + if (text == match) + return true; + } + return false; + } + + public override void EnterDeclaration_modifier ([NotNull] Declaration_modifierContext context) + { + var modifier = context.GetText (); + + } + + static bool ModifiersContainsAny (Declaration_modifiersContext context, string [] matches) + { + if (context == null) + return false; + foreach (var modifier in context.declaration_modifier ()) { + var text = modifier.GetText (); + foreach (var match in matches) + if (text == match) + return true; + } + return false; + } + + static bool IsStaticOrClass (Declaration_modifiersContext context) + { + return ModifiersContainsAny (context, new string [] { kStatic, kClass }); + } + + static bool IsFinal (Declaration_modifiersContext context) + { + return ModifiersContains (context, kFinal); + } + + void AddStructToCurrentElement (XElement elem) + { + var parentElement = GetOrCreateParentElement (kInnerStructs); + parentElement.Add (elem); + RegisterNominal (elem); + } + + void AddEnumToCurrentElement (XElement elem) + { + var parentElement = GetOrCreateParentElement (kInnerEnums); + parentElement.Add (elem); + RegisterNominal (elem); + } + + void AddClassToCurrentElement (XElement elem) + { + var parentElement = GetOrCreateParentElement (kInnerClasses); + parentElement.Add (elem); + RegisterNominal (elem); + } + + void RegisterNominal (XElement elem) + { + var isClass = elem.Attribute (kKind).Value == kClass; + var builder = new StringBuilder (); + while (elem != null) { + if (builder.Length > 0) + builder.Insert (0, '.'); + var namePart = elem.Attribute (kName)?.Value ?? moduleName; + builder.Insert (0, namePart); + elem = elem.Parent; + } + var typeName = builder.ToString (); + nominalTypes.Add (typeName); + if (isClass) + classes.Add (typeName); + } + + void AddAssociatedTypeToCurrentElement (XElement elem) + { + var parentElement = GetOrCreateParentElement (kAssociatedTypes); + parentElement.Add (elem); + } + + XElement GetOrCreateParentElement (string parentContainerName) + { + var current = currentElement.Peek (); + if (current.Name == kModule) { + return current; + } + var container = GetOrCreate (current, parentContainerName); + return container; + } + + OperatorType GetOperatorType (Function_declarationContext context) + { + var localOp = LocalOperatorType (context); + return localOp == OperatorType.None ? GlobalOperatorType (context.function_name ().GetText ()) + : localOp; + } + + OperatorType LocalOperatorType (Function_declarationContext context) + { + var head = context.function_head (); + + + // if the function declaration contains prefix + if (ModifiersContains (head.declaration_modifiers (), kLittlePrefix)) { + return OperatorType.Prefix; + } else if (ModifiersContains (head.declaration_modifiers (), kLittlePostfix)) { + return OperatorType.Postfix; + } + + var opName = context.function_name ().GetText (); + + foreach (var op in operators) { + var targetName = op.Attribute (kName).Value; + var targetKind = op.Attribute (kOperatorKind).Value; + if (opName == targetName && targetKind == kInfix) + return OperatorType.Infix; + } + return OperatorType.None; + } + + OperatorType GlobalOperatorType (string name) + { + foreach (var op in typeDatabase.FindOperators (importModules)) { + if (op.Name == name) + return op.OperatorType; + } + return OperatorType.None; + } + + void InterpretCommentText (string commentText) + { + if (commentText.StartsWith (kSwiftInterfaceFormatVersion)) { + AssignSwiftInterfaceFormat (commentText.Substring (kSwiftInterfaceFormatVersion.Length)); + } else if (commentText.StartsWith (kSwiftCompilerVersion)) { + AssignSwiftCompilerVersion (commentText.Substring (kSwiftCompilerVersion.Length)); + } else if (commentText.StartsWith (kSwiftModuleFlags)) { + ExtractModuleFlags (commentText.Substring (kSwiftModuleFlags.Length)); + moduleFlags.TryGetValue (kModuleName, out moduleName); + } + } + + void AssignSwiftInterfaceFormat (string formatVersion) + { + // when we get here, we should see something like + // [white-space]*VERSION[white-space] + formatVersion = formatVersion.Trim (); + if (!Version.TryParse (formatVersion, out interfaceVersion)) + throw new ArgumentOutOfRangeException (nameof (formatVersion), $"Expected a version string in the interface format but got {formatVersion}"); + } + + void AssignSwiftCompilerVersion (string compilerVersion) + { + // when we get here, we should see something like: + // [white-space]*Apple? Swift version VERSION (swiftlang-VERSION clang-VERSION) + var parts = compilerVersion.Trim ().Split (' ', '\t'); // don't know if tab is a thing + // expect in the array: + // 0: Apple + // 1: Swift + // 2: verion + // 3: VERSION + + var swiftIndex = Array.IndexOf (parts, "Swift"); + if (swiftIndex < 0) + throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected 'Swift' in the version string, but got {compilerVersion}"); + if (parts [swiftIndex + 1] != "version") + throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected a compiler version string but got {compilerVersion}"); + var version = parts [swiftIndex + 2]; + if (version.EndsWith ("-dev", StringComparison.Ordinal)) + version = version.Substring (0, version.Length - "-dev".Length); + if (!Version.TryParse (version, out this.compilerVersion)) + throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected a compiler version number but got {compilerVersion}"); + } + + void ExtractModuleFlags (string commentText) + { + var args = commentText.Trim ().Split (' ', '\t'); + int index = 0; + while (index < args.Length) { + var arg = args [index++]; + if (arg [0] != '-') + throw new ArgumentOutOfRangeException (nameof (CommentContext), + $"Expected argument {index - 1} to start with a '-' but got {arg} (args: {commentText}"); + var key = arg.Substring (1); + var val = ""; + if (index < args.Length && args [index] [0] != '-') { + val = args [index++]; + } + moduleFlags [key] = val; + } + } + + void SetLanguageVersion (XElement module) + { + if (compilerVersion != null) { + module.Add (new XAttribute ("swiftVersion", compilerVersion.ToString ())); + } + } + + static string XmlBool (bool b) + { + return b ? "true" : "false"; + } + + static string ToAccess (Access_level_modifierContext access) + { + var accessstr = access != null ? access.GetText () : kInternalCap; + switch (accessstr) { + case kPublic: + return kPublicCap; + case kPrivate: + return kPrivateCap; + case kOpen: + return kOpenCap; + case kInternal: + case kInternalCap: + return kInternalCap; + default: + return kUnknown; + } + } + + + static XElement GetOrCreate (XElement elem, string key) + { + var members = elem.Element (key); + if (members == null) { + members = new XElement (key); + elem.Add (members); + } + return members; + } + + static string [] ctorDtorNames = new string [] { + kDotCtor, kDotDtor + }; + + static bool IsCtorDtor (string name) + { + return ctorDtorNames.Contains (name); + } + + public static string UnTick (string str) + { + // a back-ticked string will start and end with ` + // the swift grammar guarantees this. + // Identifier : + // Identifier_head Identifier_characters? + // | OpBackTick Identifier_head Identifier_characters? OpBackTick + // | ImplicitParameterName + // There will be no starting and ending whitespace. + // + // There are some edge cases that we can take advantage of: + // 1. If it starts with `, it *has* to end with back tick, so we don't need to check + // 2. `` will never exist, so the minimum length *has* to be 3 + // In generalized string manipulation, we couldn't make these assumptions, + // but in this case the grammar works for us. + // first weed out the easy cases: + // null, too short, does start and end with back tick + // then just substring it + if (str is null || str.Length < 3 || str [0] != '`') + return str; + return str.Substring (1, str.Length - 2); + } + + + public List ImportModules { get { return importModules; } } + } +} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs b/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs new file mode 100644 index 000000000000..79701c751a34 --- /dev/null +++ b/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using Antlr4.Runtime; +using Antlr4.Runtime.Misc; +using Antlr4.Runtime.Tree; +using static SwiftInterfaceParser; +using System.Collections.Generic; + +namespace SwiftReflector.SwiftInterfaceReflector { + public class SyntaxDesugaringParser : SwiftInterfaceBaseListener { + TokenStreamRewriter rewriter; + SwiftInterfaceParser parser; + ICharStream charStream; + SwiftInterfaceLexer lexer; + + public SyntaxDesugaringParser (string inFile) + { + charStream = CharStreams.fromPath (inFile); + lexer = new SwiftInterfaceLexer (charStream); + var tokenStream = new CommonTokenStream (lexer); + + rewriter = new TokenStreamRewriter (tokenStream); + this.parser = new SwiftInterfaceParser (tokenStream); + } + + public string Desugar () + { + var walker = new ParseTreeWalker (); + walker.Walk (this, parser.swiftinterface ()); + return rewriter.GetText (); + } + + internal static string TypeText (ICharStream input, ParserRuleContext ty) + { + if (ty is null) + return null; + var start = ty.Start.StartIndex; + var end = ty.Stop.StopIndex; + var interval = new Interval (start, end); + return input.GetText (interval); + } + + string TypeText (ParserRuleContext ty) + { + return TypeText (charStream, ty); + } + + public override void ExitOptional_type ([NotNull] Optional_typeContext context) + { + var innerType = TypeText (context.type ()); + var replacementType = $"Swift.Optional<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace (startToken, endToken, replacementType); + } + + public override void ExitUnwrapped_optional_type ([NotNull] Unwrapped_optional_typeContext context) + { + var innerType = TypeText (context.type ()); + var replacementType = $"Swift.Optional<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace (startToken, endToken, replacementType); + } + + public override void ExitArray_type ([NotNull] Array_typeContext context) + { + var innerType = TypeText (context.type ()); + var replacementType = $"Swift.Array<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace (startToken, endToken, replacementType); + } + + public override void ExitDictionary_type ([NotNull] Dictionary_typeContext context) + { + var keyType = TypeText (context.children [1] as ParserRuleContext); + var valueType = TypeText (context.children [3] as ParserRuleContext); + var replacementType = $"Swift.Dictionary<{keyType},{valueType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace (startToken, endToken, replacementType); + } + + static Dictionary typeChanges = new Dictionary () { + { "Swift.Void", "()" }, + { "CoreFoundation.CGAffineTransform", "CoreGraphics.CGAffineTransform" }, + { "CoreFoundation.CGColorSapceModel", "CoreGraphics.CGColorSapceModel" }, + { "CoreFoundation.CGPoint", "CoreGraphics.CGPoint" }, + { "CoreFoundation.CGRect", "CoreGraphics.CGRect" }, + { "CoreFoundation.CGSize", "CoreGraphics.CGSize" }, + { "CoreFoundation.CGVector", "CoreGraphics.CGVector" }, + { "CoreFoundation.CGFloat", "CoreGraphics.CGFloat" }, + }; + + public override void ExitIdentifier_type ([NotNull] Identifier_typeContext context) + { + if (typeChanges.TryGetValue (context.GetText (), out var substitution)) { + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace (startToken, endToken, substitution); + } + } + + public override void ExitFunction_type_argument([NotNull] Function_type_argumentContext context) + { + if (context.argument_label () is Argument_labelContext argContext && argContext.ChildCount == 2) { + // function type argument of the form public_label private_label + // change to public_label + // in a .swiftinterface context, the private label means nothing to us + var startToken = argContext.Start; + var endToken = argContext.Stop; + rewriter.Replace (startToken, endToken, argContext.children [0].GetText ()); + } + } + } +} + diff --git a/src/SwiftReflector/SwiftName.cs b/src/SwiftReflector/SwiftName.cs new file mode 100644 index 000000000000..6ab63e6fc0fb --- /dev/null +++ b/src/SwiftReflector/SwiftName.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace SwiftReflector { + public class SwiftName { + public SwiftName (string name, bool isPunyCode) + { + if (name == null) + throw new ArgumentNullException ("name"); + PunyName = name; + Name = isPunyCode ? name.DePunyCode () : name; + } + + public string Name { get; private set; } + public string PunyName { get; private set; } + public bool HasPunyCode { get { return Name != PunyName; } } + + public override string ToString () + { + return HasPunyCode ? String.Format ("{0} ({1})", Name, PunyName) : Name; + } + + static SwiftName emptyName = new SwiftName ("", false); + public static SwiftName Empty { get { return emptyName; } } + + public override bool Equals (object obj) + { + var other = obj as SwiftName; + if (other == null) + return false; + return (PunyName == other.PunyName) && + (HasPunyCode ? Name == other.Name : true); + } + + public override int GetHashCode () + { + return PunyName.GetHashCode () + + (HasPunyCode ? Name.GetHashCode () : 0); + } + } +} + diff --git a/src/SwiftReflector/SwiftReflector.csproj b/src/SwiftReflector/SwiftReflector.csproj new file mode 100644 index 000000000000..282daa66ff9a --- /dev/null +++ b/src/SwiftReflector/SwiftReflector.csproj @@ -0,0 +1,15 @@ + + + Library + net7.0 + enable + disable + true + + + + + + + + diff --git a/src/SwiftReflector/SwiftType.cs b/src/SwiftReflector/SwiftType.cs new file mode 100644 index 000000000000..b10eb59d9787 --- /dev/null +++ b/src/SwiftReflector/SwiftType.cs @@ -0,0 +1,1118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftReflector.Demangling; +using SwiftRuntimeLibrary; + +namespace SwiftReflector { + public class SwiftType { + protected SwiftType (CoreCompoundType type, bool isReference, SwiftName name = null) + { + Type = type; + IsReference = isReference; + Name = name; + Attributes = new List (); + IsVariadic = false; + } + + public CoreCompoundType Type { get; private set; } + public SwiftName Name { get; private set; } + public bool IsReference { get; private set; } + public List Attributes { get; private set; } + public bool IsVariadic { get; set; } + + + public SwiftType ReferenceCloneOf () + { + if (IsReference) + return this; + var ty = MemberwiseClone () as SwiftType; + ty.IsReference = true; + return ty; + } + + public SwiftType NonReferenceCloneOf () + { + if (!IsReference) + return this; + var ty = MemberwiseClone () as SwiftType; + ty.IsReference = false; + return ty; + } + + public SwiftType RenamedCloneOf (SwiftName newName) + { + var ty = MemberwiseClone () as SwiftType; + ty.Name = newName; + return ty; + } + + + public bool IsConstructor { get { return this is SwiftConstructorType; } } + + public bool IsOptionalConstructor { + get { + // a SwiftType is an optional ctor if: + // 1 it's a SwiftConstructorType + // 2 its return type is SwiftBoundGenericType + // 3 its return type has a base of Swift.Optional + // 4 its return type has exactly one bound type to the type of + // the metatype of this class + var ctor = this as SwiftConstructorType; + if (ctor == null) + return false; + var returnType = ctor.ReturnType as SwiftBoundGenericType; + if (returnType == null) + return false; + if (returnType.BoundTypes.Count != 1) + return false; + var baseType = returnType.BaseType as SwiftClassType; + if (baseType == null) + return false; + var boundType = returnType.BoundTypes [0] as SwiftClassType; + if (boundType == null) + return false; + var uncurriedParameter = ctor.UncurriedParameter as SwiftMetaClassType; + if (uncurriedParameter == null) + return false; + return baseType.ClassName.ToFullyQualifiedName () == "Swift.Optional" && + boundType.ClassName.ToFullyQualifiedName (true) == uncurriedParameter.Class.ClassName.ToFullyQualifiedName (true); + } + } + + public bool IsEmptyTuple { + get { + var tuple = this as SwiftTupleType; + return tuple == null ? false : tuple.IsEmpty; + } + } + public virtual bool IsClass { get { return false; } } + public virtual bool IsStruct { get { return false; } } + public virtual bool IsEnum { get { return false; } } + public virtual bool IsProtocol { get { return false; } } + + public bool HasAttribute (SwiftTypeAttribute attribute) + { + return Attributes.Any (attr => attr == attribute); + } + + [Obsolete ("this is not supported in Swift 5")] + public bool HasObjCAttribute => HasAttribute (SwiftTypeAttribute.ObjC); + + public override int GetHashCode () + { + return Type.GetHashCode () + + (Name != null ? Name.GetHashCode () : 0); + } + + public override bool Equals (object obj) + { + var type = obj as SwiftType; + if (type == null) + return false; + if (type.Type != Type) + return false; + if (type.IsReference != IsReference) + return false; + if (type.IsVariadic != IsVariadic) + return false; + if (type.GetType () != this.GetType ()) + return false; + // shouldn't do Name equality except in functions + return LLEquals (type); + } + + public virtual bool EqualsReferenceInvaraint (SwiftType type) + { + var a = ProjectAsNonReference (this); + var b = ProjectAsNonReference (type); + + if (b.Type != a.Type) + return false; + if (b.GetType () != a.GetType ()) + return false; + // shouldn't do Name equality except in functions + return a.LLEquals (b); + } + + static SwiftType ProjectAsNonReference (SwiftType a) + { + if (a.IsReference) { + return a.NonReferenceCloneOf (); + } + var bgt = a as SwiftBoundGenericType; + if (bgt != null && bgt.BoundTypes.Count == 1) { + var baseType = bgt.BaseType as SwiftClassType; + if (baseType != null) { + string name = baseType.ClassName.ToFullyQualifiedName (true); + if (name == "Swift.UnsafePointer" || name == "Swift.UnsafeMutablePointer") + return bgt.BoundTypes [0]; + } + } + return a; + } + + protected virtual bool LLEquals (SwiftType other) + { + return true; + } + + + public static bool IsStructScalar (SwiftType st) + { + if (st == null) + return false; + if (st is SwiftBuiltInType) + return true; + var ct = st as SwiftClassType; + if (ct == null) + return false; + return IsStructScalar (ct.ClassName.ToFullyQualifiedName ()); + } + + public static bool IsStructScalar (string fullyQualifiedName) + { + switch (fullyQualifiedName) { + case "Swift.Int64": + case "Swift.UInt64": + case "Swift.Int32": + case "Swift.UInt32": + case "Swift.Int16": + case "Swift.UInt16": + case "Swift.Int8": + case "Swift.UInt8": + case "Swift.Char": + case "CoreGraphics.CGFloat": + case "Swift.UnsafeRawPointer": + case "Swift.UnsafeMutableRawPointer": + case "Swift.OpaquePointer": + return true; + default: + return false; + } + } + } + + public class SwiftModuleNameType : SwiftType { + public SwiftModuleNameType (SwiftName name, bool isReference) + : base (CoreCompoundType.ModuleName, isReference, name) + { + } + public override string ToString() + { + return Name != null ? Name.Name : "(unknown module)"; + } + } + + public abstract class SwiftBaseFunctionType : SwiftType { + public SwiftBaseFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base (CoreCompoundType.Function, isReference, name) + { + Parameters = Exceptions.ThrowOnNull (parms, nameof(parms)); + ReturnType = Exceptions.ThrowOnNull (ret, nameof(ret)); + GenericArguments = new List (); + CanThrow = canThrow; + ExtensionOn = extensionOn; + } + + public bool ContainsGenericParameters { + get { + return GenericArguments.Count () > 0; + } + } + public SwiftType ExtensionOn { get; set; } + public abstract MemberType MemberType { get; } + public SwiftType Parameters { get; private set; } + public SwiftType ReturnType { get; private set; } + public List GenericArguments { get; private set; } + public bool CanThrow { get; private set; } + public bool IsExtension { get { return ExtensionOn != null; } } + public virtual bool IsThunk => false; + public SwiftBaseFunctionType Thunk { get; set; } + + public abstract SwiftBaseFunctionType AsThunk (); + + // for short-lived discretionary storage of information + public string DiscretionaryString { get; set; } + + public IEnumerable EachParameter { + get { + for (int i = 0; i < ParameterCount; i++) { + yield return GetParameter (i); + } + } + } + + public int GenericParameterCount { + get { return EachParameter.Sum (st => st is SwiftGenericArgReferenceType ? 1 : 0); } + } + + + public bool IsVoid { get { return ReturnType.Type == CoreCompoundType.Tuple && ((SwiftTupleType)ReturnType).IsEmpty; } } + + protected override bool LLEquals (SwiftType other) + { + var fn = other as SwiftBaseFunctionType; + if (fn == null) + return false; + if (Name != null) + Name.Equals (fn.Name); + return MemberType == fn.MemberType && Parameters.Equals (fn.Parameters) + && ReturnType.Equals (fn.ReturnType); + } + + public int ParameterCount { + get { + var tt = Parameters as SwiftTupleType; + if (tt == null) { + return 1; + } else { + return tt.Contents.Count; + } + } + } + + public SwiftType GetParameter (int index) + { + var tt = Parameters as SwiftTupleType; + if (tt == null) { + if (index == 0) + return Parameters; + else + throw new ArgumentOutOfRangeException (nameof(index)); + } else { + if (index < 0 || index >= tt.Contents.Count) + throw new ArgumentOutOfRangeException (nameof (index)); + return tt.Contents [index]; + } + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return $"{name}{Parameters.ToString ()}->{ReturnType.ToString ()}"; + } + } + + public class SwiftCFunctionType : SwiftBaseFunctionType { + public SwiftCFunctionType (SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) + : base (parms, ret, isReference, false, name, null) + { + } + + public override MemberType MemberType { + get { + return MemberType.CFunction; + } + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftCFunctionTypeThunk (Parameters, ReturnType, IsReference, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftCFunctionTypeThunk : SwiftCFunctionType { + public SwiftCFunctionTypeThunk (SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) + : base (parms, ret, isReference, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftAddressorType : SwiftBaseFunctionType { + public SwiftAddressorType (AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) + : base (SwiftTupleType.Empty, ret, isReference, false, name, null) + { + AddressorType = addressor; + } + public AddressorType AddressorType { get; private set; } + public override MemberType MemberType { + get { + return MemberType.Addressor; + } + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftAddressorThunkType (AddressorType, ReturnType, IsReference, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftAddressorThunkType : SwiftAddressorType { + public SwiftAddressorThunkType (AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) + : base (addressor, ret, isReference, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftInitializerType : SwiftBaseFunctionType { + public SwiftInitializerType (InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) + : base (SwiftTupleType.Empty, ret, false, false, name, null) + { + Owner = Exceptions.ThrowOnNull (owner, nameof (owner)); + InitializerType = initType; + } + + public InitializerType InitializerType { get; private set; } + public SwiftClassType Owner { get; private set; } + public override MemberType MemberType { + get { + return MemberType.Initializer; + } + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftInitializerThunkType (InitializerType, ReturnType, Owner, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftInitializerThunkType : SwiftInitializerType { + public SwiftInitializerThunkType (InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) + : base (initType, ret, owner, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftFunctionType : SwiftBaseFunctionType { + public SwiftFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) + : base (parms, ret, isReference, canThrow, name, extensionOn) + { + IsEscaping = isEscaping; + } + + public override MemberType MemberType { get { return MemberType.Function; } } + public bool IsEscaping { get; private set; } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftFunctionThunkType (Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn, IsEscaping); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftFunctionThunkType : SwiftFunctionType { + public SwiftFunctionThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) + : base (parms, ret, isReference, canThrow, name, extensionOn, isEscaping) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftCFunctionPointerType : SwiftFunctionType { + public SwiftCFunctionPointerType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) + : base (parms, ret, isReference, canThrow, name, null) + { + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftCFunctionPointerThunkType (Parameters, ReturnType, IsReference, CanThrow, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftCFunctionPointerThunkType : SwiftCFunctionPointerType { + public SwiftCFunctionPointerThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) + : base (parms, ret, isReference, canThrow, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftStaticFunctionType : SwiftFunctionType { + public SwiftStaticFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) + : base (parms, ret, isReference, canThrow, name, extensionOn) + { + OfClass = ofClass; + } + + public SwiftClassType OfClass { get; private set; } + + public override SwiftBaseFunctionType AsThunk () + { + var func = new SwiftStaticFunctionThunkType (Parameters, ReturnType, IsReference, CanThrow, OfClass, Name, ExtensionOn); + func.DiscretionaryString = DiscretionaryString; + return func; + } + } + + public class SwiftStaticFunctionThunkType : SwiftStaticFunctionType { + public SwiftStaticFunctionThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) + : base (parms, ret, isReference, canThrow, ofClass, name, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + + public class SwiftClassConstructorType : SwiftFunctionType { + public SwiftClassConstructorType (SwiftMetaClassType meta, bool isReference) + : base (SwiftTupleType.Empty, Exceptions.ThrowOnNull (meta, "meta"), isReference, false, Decomposer.kSwiftClassConstructorName) + { + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftClassConstructorThunkType (ReturnType as SwiftMetaClassType, IsReference); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftClassConstructorThunkType : SwiftClassConstructorType { + public SwiftClassConstructorThunkType (SwiftMetaClassType meta, bool isReference) + : base (meta, isReference) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftUncurriedFunctionType : SwiftBaseFunctionType { + public SwiftUncurriedFunctionType (SwiftType unCurriedParameter, + SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : this (MemberType.UncurriedFunction, unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) + { + } + + protected SwiftUncurriedFunctionType (MemberType memberType, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base (parms, ret, isReference, canThrow, name, extensionOn) + { + // oddly enough, this is allowed to be null + UncurriedParameter = unCurriedParameter; + this.memberType = memberType; + } + MemberType memberType; + public override MemberType MemberType { get { return memberType; } } + public SwiftType UncurriedParameter { get; private set; } + + protected override bool LLEquals (SwiftType other) + { + var ucf = other as SwiftUncurriedFunctionType; + return ucf != null && ucf.UncurriedParameter.Equals (UncurriedParameter) && base.LLEquals(other); + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftUncurriedFunctionThunkType (UncurriedParameter, Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftUncurriedFunctionThunkType : SwiftUncurriedFunctionType + { + public SwiftUncurriedFunctionThunkType (SwiftType unCurriedParameter, + SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base (unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + + public class SwiftConstructorType : SwiftUncurriedFunctionType { + public SwiftConstructorType (bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) + : base (isAllocating ? MemberType.Allocator : MemberType.Constructor, + unCurriedParameter, parms, ret, isReference, canThrow, isAllocating ? Decomposer.kSwiftAllocatingConstructorName : + Decomposer.kSwiftNonAllocatingConstructorName, extensionOn) + { + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftConstructorThunkType (MemberType == MemberType.Allocator, UncurriedParameter, + Parameters, ReturnType, IsReference, CanThrow, ExtensionOn); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftConstructorThunkType : SwiftConstructorType { + public SwiftConstructorThunkType (bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) + : base (isAllocating, unCurriedParameter, parms, ret, isReference, canThrow, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftDestructorType : SwiftBaseFunctionType { + public SwiftDestructorType (bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) + : base (classType, classType, isReference, canThrow, + isDeallocating ? Decomposer.kSwiftDeallocatingDestructorName : Decomposer.kSwiftNonDeallocatingDestructorName, null) + { + memberType = isDeallocating ? MemberType.Deallocator : MemberType.Destructor; + } + MemberType memberType; + public override MemberType MemberType { get { return memberType; } } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftDestructorThunkType (Name == Decomposer.kSwiftDeallocatingDestructorName, ReturnType as SwiftClassType, IsReference, CanThrow); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftDestructorThunkType : SwiftDestructorType { + public SwiftDestructorThunkType (bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) + : base (isDeallocating, classType, isReference, canThrow) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftPropertyType : SwiftUncurriedFunctionType { + public SwiftPropertyType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base (unCurriedParameter, + (propType == PropertyType.Setter || propType == PropertyType.Materializer) ? ofType : SwiftTupleType.Empty, + (propType == PropertyType.Getter) ? ofType : SwiftTupleType.Empty, + isReference, false, propName, extensionOn) + { + PropertyType = propType; + PrivateName = privateName; + OfType = Exceptions.ThrowOnNull (ofType, "ofType"); + IsSubscript = false; + IsStatic = isStatic; + } + public SwiftPropertyType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base (unCurriedParameter, accessor.Parameters, accessor.ReturnType, isReference, false, propName, extensionOn) + { + PropertyType = propType; + PrivateName = privateName; + OfType = accessor; + IsSubscript = true; + IsStatic = isStatic; + } + + public PropertyType PropertyType { get; private set; } + public SwiftName PrivateName { get; private set; } + public SwiftType OfType { get; private set; } + public bool IsStatic { get; private set; } + + public bool IsSubscript { get; private set; } + public bool IsPublic { get { return PrivateName == null; } } + public bool IsPrivate { get { return PrivateName != null; } } + public bool IsGlobal { get { return UncurriedParameter == null; }} + + public SwiftPropertyType RecastAsStatic() + { + if (IsStatic) + return this; + SwiftPropertyType newProp = null; + if (OfType is SwiftFunctionType) { + if (this is SwiftPropertyThunkType) { + newProp = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, + true, IsReference); + + } else { + newProp = new SwiftPropertyType (UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, + true, IsReference); + } + } else { + if (this is SwiftPropertyThunkType) { + newProp = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); + + } else { + newProp = new SwiftPropertyType (UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); + } + } + newProp.DiscretionaryString = DiscretionaryString; + newProp.ExtensionOn = this.ExtensionOn; + return newProp; + } + + public override SwiftBaseFunctionType AsThunk () + { + if (IsSubscript) { + var pt = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, + PrivateName, OfType as SwiftFunctionType, IsStatic, IsReference, ExtensionOn); + pt.DiscretionaryString = DiscretionaryString; + return pt; + } else { + var pt = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, + PrivateName, OfType, IsStatic, IsReference, ExtensionOn); + pt.DiscretionaryString = DiscretionaryString; + return pt; + } + } + } + + public class SwiftPropertyThunkType : SwiftPropertyType { + public SwiftPropertyThunkType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base (unCurriedParameter, propType, propName, privateName, ofType, isStatic, isReference, extensionOn) + { + } + + public SwiftPropertyThunkType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base (unCurriedParameter, propType, propName, privateName, accessor, isStatic, isReference, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftExplicitClosureType : SwiftBaseFunctionType { + public SwiftExplicitClosureType (bool isReference) + : base (SwiftTupleType.Empty, SwiftTupleType.Empty, isReference, false, null) + { + } + + public override MemberType MemberType { + get { + return MemberType.ExplicitClosure; + } + } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftExplicitClosureThunkType (IsReference); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftExplicitClosureThunkType : SwiftExplicitClosureType { + public SwiftExplicitClosureThunkType (bool isReference) + : base (isReference) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftWitnessTableType : SwiftUncurriedFunctionType { + public SwiftWitnessTableType (WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) + : base ((SwiftType)owningType ?? SwiftTupleType.Empty, SwiftTupleType.Empty, SwiftTupleType.Empty, false, false, null) + { + WitnessType = witnessType; + if (WitnessType == WitnessType.Protocol && protocolType == null) + throw new ArgumentNullException (nameof (protocolType)); + ProtocolType = protocolType; + } + public WitnessType WitnessType { get; private set; } + public SwiftClassType ProtocolType { get; private set; } + + public override SwiftBaseFunctionType AsThunk () + { + var thunk = new SwiftWitnessTableThunkType (WitnessType, ProtocolType, UncurriedParameter as SwiftClassType); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftWitnessTableThunkType : SwiftWitnessTableType { + public SwiftWitnessTableThunkType (WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) + : base (witnessType, protocolType, owningType) + { + } + + public override bool IsThunk => true; + public override SwiftBaseFunctionType AsThunk () => this; + } + + public class SwiftTupleType : SwiftType { + public SwiftTupleType (bool isReference) + : this (null, isReference, null) + { + } + + public SwiftTupleType (IEnumerable contents, bool isReference, SwiftName name = null) + : base (CoreCompoundType.Tuple, isReference, name) + { + Contents = new List (); + if (contents != null) + Contents.AddRange (contents); + } + + public SwiftTupleType (bool isReference, SwiftName name, params SwiftType [] contents) + : this (contents, isReference, name) + { + } + + public List Contents { get; private set; } + public bool IsEmpty { get { return Contents.Count == 0; } } + static SwiftTupleType empty = new SwiftTupleType (null, false, null); + public static SwiftTupleType Empty { get { return empty; } } + + public bool HasNames () + { + return Contents.FirstOrDefault (st => st.Name != null) != null; + } + + protected override bool LLEquals (SwiftType other) + { + SwiftTupleType st = other as SwiftTupleType; + if (st == null) + return false; + return Contents.SequenceEqual (st.Contents); + } + + public SwiftType AllButFirst () + { + if (IsEmpty) + throw new ArgumentOutOfRangeException ("tuple is empty"); + // seriously, this is what we want to do. + // If a function has one argument, it will be a the simple type. + // If a function has more than one argument, it will be a tuple. + if (Contents.Count == 2) + return Contents [1]; + return new SwiftTupleType (Contents.TakeWhile ((st, i) => i > 0), IsReference, Name); + } + + public SwiftType AllButFirstN (int n) + { + if (IsEmpty) + throw new ArgumentOutOfRangeException ("tuple is empty"); + // seriously, this is what we want to do. + // If a function has one argument, it will be a the simple type. + // If a function has more than one argument, it will be a tuple. + // So if we are returning the last element, we're returning an single not a tuple. + if (Contents.Count == n + 1) + return Contents [n]; + return new SwiftTupleType (Contents.Skip (n), IsReference, Name); + } + + public override string ToString() + { + var contents = Contents.Select (el => { + var elname = el.Name != null ? el.Name.Name + ": " : ""; + return elname + el.ToString (); + }).InterleaveCommas (); + return $"({contents})"; + } + } + + public class SwiftBuiltInType : SwiftType { + public SwiftBuiltInType (CoreBuiltInType scalarType, bool isReference, SwiftName name = null) + : base (CoreCompoundType.Scalar, isReference, name) + { + BuiltInType = scalarType; + } + + public CoreBuiltInType BuiltInType { get; private set; } + + protected override bool LLEquals (SwiftType other) + { + SwiftBuiltInType sb = other as SwiftBuiltInType; + return sb != null && BuiltInType == sb.BuiltInType; + } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + BuiltInType.ToString (); + } + + } + + public class SwiftArrayType : SwiftType { + public SwiftArrayType (bool isReference, SwiftName name = null) + : base (CoreCompoundType.Array, isReference, name) + { + } + public override string ToString () + { + var name = Name != null ? Name.Name + ": " : ""; + return $"{name}[]"; + } + } + + public class SwiftClassType : SwiftType { + public SwiftClassType (SwiftClassName className, bool isReference, SwiftName name = null) + : base (CoreCompoundType.Class, isReference, name) + { + ClassName = className; + } + public SwiftClassName ClassName { get; private set; } + public override bool IsClass { get { return EntityKind == MemberNesting.Class; } } + public override bool IsStruct { get { return EntityKind == MemberNesting.Struct; } } + public override bool IsEnum { get { return EntityKind == MemberNesting.Enum; } } + public override bool IsProtocol { get { return EntityKind == MemberNesting.Protocol; } } + + public MemberNesting EntityKind { get { return ClassName.Nesting.Last (); } } + + protected override bool LLEquals (SwiftType other) + { + var sct = other as SwiftClassType; + return sct != null && ClassName.Equals (sct.ClassName); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + ClassName.ToFullyQualifiedName (); + } + } + + public class SwiftProtocolListType : SwiftType { + public SwiftProtocolListType (IEnumerable protocols, bool isReference, SwiftName name = null) + : base (CoreCompoundType.ProtocolList, isReference, name) + { + Protocols = new List (); + Protocols.AddRange (protocols.Where (p => { + if (p.IsProtocol) { + return true; + } else { + throw new ArgumentOutOfRangeException ("protocols", "protocols must contain only SwiftClassType with EntityKind protocol."); + } + })); + } + + public SwiftProtocolListType (SwiftClassType protocol, bool isReference, SwiftName name = null) + : base (CoreCompoundType.ProtocolList, isReference, name) + { + Protocols = new List (); + if (!protocol.IsProtocol) + throw new ArgumentOutOfRangeException ($"Type {protocol.ClassName.ToFullyQualifiedName ()} is not a protocol"); + Protocols.Add (protocol); + } + + public List Protocols { get; private set; } + + protected override bool LLEquals (SwiftType other) + { + var prot = other as SwiftProtocolListType; + if (other == null) + return false; + if (Protocols.Count != prot.Protocols.Count) + return false; + return Protocols.SequenceEqual (prot.Protocols); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + Protocols.Select (p => p.ToString ()).InterleaveStrings (" & "); + } + } + + public class SwiftMetaClassType : SwiftType { + public SwiftMetaClassType (SwiftClassType classType, bool isReference, SwiftName name = null) + : base (CoreCompoundType.MetaClass, isReference, name) + { + Class = Exceptions.ThrowOnNull (classType, nameof (classType)); + } + public SwiftMetaClassType (SwiftGenericArgReferenceType classGenericReference, bool isReference, SwiftName name = null) + : base (CoreCompoundType.MetaClass, isReference, name) + { + ClassGenericReference = Exceptions.ThrowOnNull (classGenericReference, nameof (classGenericReference)); + } + public SwiftClassType Class { get; private set; } + public SwiftGenericArgReferenceType ClassGenericReference { get; private set; } + protected override bool LLEquals (SwiftType other) + { + var meta = other as SwiftMetaClassType; + if (meta == null) + return false; + if (Class != null) + return Class.Equals (meta.Class); + else + return ClassGenericReference.Equals (meta.ClassGenericReference); + } + public override string ToString () + { + var name = Name != null ? Name.Name + ": " : ""; + return name + "Meta " + Class; + } + } + + public class SwiftExistentialMetaType : SwiftType { + public SwiftExistentialMetaType (SwiftProtocolListType protocolList, bool isReference, SwiftName name = null) + : base (CoreCompoundType.MetaClass, isReference, name) + { + Protocol = Exceptions.ThrowOnNull (protocolList, nameof (protocolList)); + } + public SwiftProtocolListType Protocol { get; private set; } + protected override bool LLEquals (SwiftType other) + { + var meta = other as SwiftExistentialMetaType; + return meta != null && Protocol.Equals (meta.Protocol); + } + public bool IsAny { get { return Protocol.Protocols.Count == 0; } } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + "Existential Metatype " + Protocol; + } + } + + public class GenericArgument { + public GenericArgument (int depth, int index) + { + Constraints = new List (); + Depth = depth; + Index = index; + } + public int Depth { get; set; } + public int Index { get; set; } + public List Constraints { get; private set; } + public bool IsProtocolConstrained () + { + if (Constraints.Count == 0) + return false; + foreach (SwiftType ty in Constraints) { + var ct = ty as SwiftClassType; + if (ct == null) + throw new NotSupportedException ("Expected a class type, but got " + ty.GetType ().Name); + if (ct.EntityKind != MemberNesting.Protocol) + return false; + } + return true; + } + public bool IsClassConstrained () + { + if (Constraints.Count == 0) + return false; + foreach (SwiftType ty in Constraints) { + var ct = ty as SwiftClassType; + if (ct == null) + throw new NotSupportedException ("Expected a class type, but got " + ty.GetType ().Name); + if (ct.EntityKind != MemberNesting.Protocol) + return true; + } + return false; + } + } + + + public class SwiftUnboundGenericType : SwiftType { + public SwiftUnboundGenericType (SwiftType dependentType, List parms, bool isReference, SwiftName name = null) + : base (CoreCompoundType.UnboundGeneric, isReference, name) + { + DependentType = Exceptions.ThrowOnNull (dependentType, nameof (dependentType)); + Arguments = Exceptions.ThrowOnNull (parms, nameof (parms)); + } + + public SwiftType DependentType { get; private set; } + public List Arguments { get; private set; } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + var genArgs = Arguments.Select ((arg) => $"({arg.Depth},{arg.Index})").InterleaveCommas (); + return $"{name}{DependentType.ToString ()}<{genArgs}>"; + } + } + + public class SwiftGenericArgReferenceType : SwiftType { + public SwiftGenericArgReferenceType (int depth, int index, bool isReference, SwiftName name = null, List associatedTypePath = null) + : base (CoreCompoundType.GenericReference, isReference, name) + { + Depth = depth; + Index = index; + AssociatedTypePath = new List (); + if (associatedTypePath != null) + AssociatedTypePath.AddRange (associatedTypePath); + } + + public int Depth { get; private set; } + public int Index { get; private set; } + public List AssociatedTypePath { get; private set; } + public bool HasAssociatedTypePath => AssociatedTypePath.Count > 0; + + protected override bool LLEquals (SwiftType other) + { + var art = other as SwiftGenericArgReferenceType; + if (art == null) + return false; + if (Depth != art.Depth || Index != art.Index) + return false; + if (AssociatedTypePath.Count != art.AssociatedTypePath.Count) + return false; + return AssociatedTypePath.SequenceEqual (art.AssociatedTypePath); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + if (HasAssociatedTypePath) { + var path = AssociatedTypePath.InterleaveStrings ("."); + return name + $"({Depth},{Index}){(char)('A' + Depth)}{Index}.{path}"; + } else { + return name + $"({Depth},{Index})"; + } + } + } + + public class SwiftBoundGenericType : SwiftType { + public SwiftBoundGenericType (SwiftType baseType, List boundTypes, bool isReference, SwiftName name = null) + : base (CoreCompoundType.BoundGeneric, isReference, name) + { + BaseType = Exceptions.ThrowOnNull (baseType, "baseType"); + BoundTypes = new List (); + if (boundTypes != null) + BoundTypes.AddRange (boundTypes); + } + public SwiftType BaseType { get; private set; } + public List BoundTypes { get; private set; } + protected override bool LLEquals (SwiftType other) + { + var bgt = other as SwiftBoundGenericType; + return bgt != null && BaseType.Equals (bgt.BaseType) + && BoundTypes.SequenceEqual (bgt.BoundTypes); + } + + public override bool IsClass { get { return BaseType.IsClass; } } + public override bool IsEnum { get { return BaseType.IsEnum; } } + public override bool IsStruct { get { return BaseType.IsStruct; } } + public override string ToString () + { + var name = Name != null ? Name.Name + ": " : ""; + var genArgs = BoundTypes.Select (arg => arg.ToString ()).InterleaveCommas (); + return $"{name}{BaseType.ToString()}<{genArgs}>"; + } + } + +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs new file mode 100644 index 000000000000..fe187288b436 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Xml.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + public class AssociatedTypeDeclaration { + public AssociatedTypeDeclaration () + { + ConformingProtocols = new List (); + } + + public string Name { get; set; } + + public TypeSpec SuperClass { get; set; } + public TypeSpec DefaultType { get; set; } + public List ConformingProtocols { get; private set; } + + + public static AssociatedTypeDeclaration FromXElement (TypeAliasFolder folder, XElement elem) + { + var assocType = new AssociatedTypeDeclaration (); + assocType.Name = NameAttribute (elem); + + var superClassElem = elem.Element ("superclass"); + if (superClassElem != null) { + var superClassName = NameAttribute (superClassElem); + if (superClassName != null) { + assocType.SuperClass = folder.FoldAlias (null, TypeSpecParser.Parse (superClassName)); + } + } + var defaultDefn = elem.Attribute ("defaulttype"); + if (defaultDefn != null) { + assocType.DefaultType = folder.FoldAlias (null, TypeSpecParser.Parse ((string)defaultDefn)); + } + + if (elem.Element ("conformingprotocols") != null) { + var conforming = from conform in elem.Element ("conformingprotocols").Elements () + select folder.FoldAlias (null, TypeSpecParser.Parse (NameAttribute (conform))) as NamedTypeSpec; + assocType.ConformingProtocols.AddRange (conforming); + } + + return assocType; + } + + public void GatherXObjects (List xobjects) + { + xobjects.Add (new XAttribute ("name", Name)); + if (SuperClass != null) + xobjects.Add (new XElement ("superclass", new XElement ("superclass", new XAttribute ("name", SuperClass.ToString ())))); + if (DefaultType != null) + xobjects.Add (new XAttribute ("defaulttype", DefaultType.ToString ())); + var conforming = new List (); + foreach (var spec in ConformingProtocols) { + conforming.Add (new XElement ("conformingprotocol", new XAttribute ("name", spec.ToString ()))); + } + xobjects.Add (new XElement ("conformingprotocols", conforming.ToArray ())); + } + + static string NameAttribute(XElement elem) + { + return (string)elem.Attribute ("name"); + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs new file mode 100644 index 000000000000..dafbf9871f79 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Xml.Linq; +using SyntaxDynamo; +using System.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + public class AttributeDeclaration { + public AttributeDeclaration (string typeName) + { + Name = Exceptions.ThrowOnNull (typeName, nameof (typeName)); + Parameters = new List (); + } + + public AttributeDeclaration (AttributeDeclaration other) + : this (other.Name) + { + foreach (var parameter in other.Parameters) + Parameters.Add (DuplicateOf (parameter)); + } + + public static AttributeDeclaration FromXElement (XElement elem) + { + var decl = new AttributeDeclaration (elem.Attribute ("name").Value); + var parameters = elem.Element ("attributeparameterlist"); + if (parameters == null) + return decl; + FromAttributeParameterList (parameters, decl.Parameters); + return decl; + } + + internal static void FromAttributeParameterList (XElement parameters, List outlist) + { + foreach (var parameterElem in parameters.Elements ("attributeparameter")) { + var parameter = AttributeParameter.FromXElement (parameterElem); + outlist.Add (parameter); + } + } + + public static AttributeParameter DuplicateOf(AttributeParameter other) + { + switch (other.Kind) { + case AttributeParameterKind.Label: + return new AttributeParameterLabel ((AttributeParameterLabel)other); + case AttributeParameterKind.Literal: + return new AttributeParameterLiteral ((AttributeParameterLiteral)other); + case AttributeParameterKind.Sublist: + return new AttributeParameterSublist ((AttributeParameterSublist)other); + case AttributeParameterKind.Unknown: + return new AttributeParameter (); + default: + throw new ArgumentOutOfRangeException (nameof (other), other.Kind.ToString ()); + } + } + + public NamedTypeSpec AttributeType { get; private set; } + public string Name { + get { + return AttributeType.ToString (true); + } + private set { + Exceptions.ThrowOnNull (value, nameof (value)); + var ts = TypeSpecParser.Parse (value); + if (ts is NamedTypeSpec named) + AttributeType = named; + else + throw new ArgumentOutOfRangeException ($"TypeSpec for {value} is a {ts.Kind} and not a named type spec"); + } + } + public List Parameters { get; private set; } + } + + public class AttributeParameter { + public static AttributeParameter FromXElement (XElement elem) + { + switch (elem.Attribute ("kind").Value) { + case "Label": + return new AttributeParameterLabel (elem.Attribute ("Value").Value); + case "Literal": + return new AttributeParameterLiteral (elem.Attribute ("Value").Value); + case "Sublist": + return AttributeParameterSublist.SublistFromXElement (elem); + default: + return new AttributeParameter (); + } + } + + public virtual AttributeParameterKind Kind => AttributeParameterKind.Unknown; + } + + public class AttributeParameterLabel : AttributeParameter { + public AttributeParameterLabel (string label) + { + Label = Exceptions.ThrowOnNull (label, nameof (label)); + } + + public AttributeParameterLabel (AttributeParameterLabel other) + : this (other.Label) + { + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Label; + public string Label { get; private set; } + } + + public class AttributeParameterLiteral : AttributeParameter { + public AttributeParameterLiteral (string literal) + { + Literal = Exceptions.ThrowOnNull (literal, nameof (literal)); + } + + public AttributeParameterLiteral (AttributeParameterLiteral other) + : this (other.Literal) + { + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Literal; + public string Literal { get; private set; } + } + + public class AttributeParameterSublist : AttributeParameter { + public AttributeParameterSublist () + { + Parameters = new List (); + } + + public AttributeParameterSublist (AttributeParameterSublist other) + : this () + { + Parameters.AddRange (other.Parameters.Select (prm => AttributeDeclaration.DuplicateOf (prm))); + } + + public static AttributeParameterSublist SublistFromXElement (XElement elem) + { + var sublist = new AttributeParameterSublist (); + var parameters = elem.Element ("attributeparameterlist"); + if (parameters == null) + return sublist; + AttributeDeclaration.FromAttributeParameterList (parameters, sublist.Parameters); + return sublist; + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Sublist; + public List Parameters { get; private set; } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs new file mode 100644 index 000000000000..c81105ef9b69 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Xml.Linq; +using SwiftReflector.IOUtils; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class BaseConstraint : IXElementConvertible { + protected BaseConstraint (ConstraintKind kind) + { + Kind = kind; + } + public ConstraintKind Kind { get; private set; } + + public static BaseConstraint FromXElement (TypeAliasFolder folder, XElement elem) + { + if (elem == null) + return null; + if ((string)elem.Attribute ("relationship") == "inherits") { + return new InheritanceConstraint ((string)elem.Attribute ("name"), (string)elem.Attribute ("from"), folder); + } else { + return new EqualityConstraint ((string)elem.Attribute ("firsttype"), (string)elem.Attribute ("secondtype"), folder); + } + } + + public XElement ToXElement () + { + var inh = this as InheritanceConstraint; + if (inh != null) { + return new XElement ("where", new XAttribute ("relationship", "inherits"), + new XAttribute ("name", inh.Name), + new XAttribute ("from", inh.Inherits)); + } else { + var eq = (EqualityConstraint)this; + return new XElement ("where", new XAttribute ("relationship", "equals"), + new XAttribute ("firsttype", eq.Type1), + new XAttribute ("secondtype", eq.Type2)); + } + } + + internal string EffectiveTypeName () + { + var inh = this as InheritanceConstraint; + if (inh != null) + return inh.Name; + var eq = (EqualityConstraint)this; + string [] pieces = eq.Type1.Split ('.'); + // T, T.U + if (pieces.Length == 1 || pieces.Length == 2) { + return pieces [0]; + } + // Module.T.U + else if (pieces.Length > 2) { + return pieces [1]; + } + return null; + } + + public static BaseConstraint CopyOf (BaseConstraint baseConstraint) + { + if (baseConstraint is InheritanceConstraint inh) { + return new InheritanceConstraint (inh.Name, inh.Inherits); + + } else if (baseConstraint is EqualityConstraint eq) { + return new EqualityConstraint (eq.Type1, eq.Type2); + } + throw new NotImplementedException ($"Unknown constraint type {baseConstraint.GetType ().Name}"); + } + } + + public class InheritanceConstraint : BaseConstraint { + public InheritanceConstraint (string name, string inheritsTypeSpecString, TypeAliasFolder folder = null) + : base (ConstraintKind.Inherits) + { + Name = Exceptions.ThrowOnNull (name, nameof (name)); + Inherits = inheritsTypeSpecString; + if (folder != null) + InheritsTypeSpec = folder.FoldAlias (null, InheritsTypeSpec); + } + + public InheritanceConstraint (string name, TypeSpec inheritsTypeSpecString) + : this (name, inheritsTypeSpecString.ToString ()) + { + + } + + public string Name { get; private set; } + string inheritsStr; + TypeSpec inheritsSpec; + public string Inherits { + get { + return inheritsStr; + } + set { + inheritsStr = value; + if (value != null) { + inheritsSpec = TypeSpecParser.Parse (value); + } else { + inheritsSpec = null; + } + } + } + public TypeSpec InheritsTypeSpec { + get { + return inheritsSpec; + } + set { + inheritsSpec = value; + if (value != null) { + inheritsStr = value.ToString (); + } else { + inheritsStr = null; + } + } + } + } + + public class EqualityConstraint : BaseConstraint { + public EqualityConstraint (string type1, string type2, TypeAliasFolder folder = null) + : base (ConstraintKind.Equal) + { + Type1 = type1; + Type2 = type2; + if (folder != null) { + Type1Spec = folder.FoldAlias (null, Type1Spec); + Type2Spec = folder.FoldAlias (null, Type2Spec); + } + } + string type1Str; + TypeSpec type1Spec; + public string Type1 { + get { + return type1Str; + } + set { + type1Str = value; + if (value != null) { + type1Spec = TypeSpecParser.Parse (value); + } else { + type1Spec = null; + } + } + } + public TypeSpec Type1Spec { + get { + return type1Spec; + } + set { + type1Spec = value; + if (value != null) { + type1Str = value.ToString (); + } else { + type1Str = null; + } + } + } + string type2Str; + TypeSpec type2Spec; + public string Type2 { + get { + return type2Str; + } + set { + type2Str = value; + if (value != null) { + type2Spec = TypeSpecParser.Parse (value); + } else { + type2Spec = null; + } + } + } + public TypeSpec Type2Spec { + get { + return type2Spec; + } + set { + type2Spec = value; + if (value != null) { + type2Str = value.ToString (); + } else { + type2Str = null; + } + } + } + + + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs new file mode 100644 index 000000000000..d5b2dc0c64b7 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs @@ -0,0 +1,561 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using System.Text; +using SwiftReflector.ExceptionTools; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftXmlReflection { + public class BaseDeclaration { + protected BaseDeclaration () + { + Generics = new GenericDeclarationCollection (); + Attributes = new List (); + } + + protected BaseDeclaration (BaseDeclaration other) + { + Name = other.Name; + Access = other.Access; + Module = other.Module; + Parent = other.Parent; + ParentExtension = other.ParentExtension; + Generics = new GenericDeclarationCollection (); + Attributes = new List (); + } + + public string Name { get; set; } + public Accessibility Access { get; set; } + public ModuleDeclaration Module { get; set; } + public BaseDeclaration Parent { get; set; } + public GenericDeclarationCollection Generics { get; private set; } + public ExtensionDeclaration ParentExtension { get; set; } + public bool IsExtension { get { return ParentExtension != null; } } + public bool ContainsGenericParameters { + get { + return Generics.Count () > 0; + } + } + public List Attributes { get; private set; } + + public bool IsTypeSpecBoundGeneric (TypeSpec sp) + { + if (sp.ContainsGenericParameters) { + foreach (var gen in sp.GenericParameters) { + if (IsTypeSpecGeneric (gen)) + return false; + } + return true; + } + return false; + } + + public bool IsTypeSpecAssociatedType (NamedTypeSpec named) + { + var proto = ThisOrParentProtocol (this); + if (proto == null) + return false; + if (named.ContainsGenericParameters) { + foreach (var gen in named.GenericParameters) { + if (gen is NamedTypeSpec namedGen && IsTypeSpecAssociatedType (namedGen)) + return true; + } + } + return proto.AssociatedTypeNamed (named.NameWithoutModule) != null; + } + + public bool IsNested => this is TypeDeclaration && Parent != null; + + public ProtocolDeclaration GetConstrainedProtocolWithAssociatedType (NamedTypeSpec named, TypeMapper typeMapper) + { + var depthIndex = GetGenericDepthAndIndex (named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); + if (genDecl == null) + return null; + if (genDecl.Constraints.Count != 1) + return null; + var inheritance = genDecl.Constraints [0] as InheritanceConstraint; + if (inheritance == null) + return null; + var entity = typeMapper.GetEntityForTypeSpec (inheritance.InheritsTypeSpec); + if (entity == null) + return null; + var proto = entity.Type as ProtocolDeclaration; + if (proto == null || !proto.HasAssociatedTypes) + return null; + return proto; + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromNamedTypeSpec (NamedTypeSpec named) + { + var proto = ThisOrParentProtocol (this); + return proto.AssociatedTypeNamed (named.NameWithoutModule); + } + + public ProtocolDeclaration AsProtocolOrParentAsProtocol () + { + return ThisOrParentProtocol (this); + } + + public BaseDeclaration AsTypeDeclaration () + { + return ThisOrParentTypeDeclaration (this); + } + + static ProtocolDeclaration ThisOrParentProtocol (BaseDeclaration self) + { + if (self == null) + return null; + + do { + if (self is ProtocolDeclaration decl) + return decl; + self = self.Parent; + } while (self != null); + return null; + } + + static TypeDeclaration ThisOrParentTypeDeclaration (BaseDeclaration self) + { + if (self == null) + return null; + + do { + if (self is TypeDeclaration decl) + return decl; + self = self.Parent; + } while (self != null); + return null; + } + + + public bool IsProtocolWithAssociatedTypesFullPath (NamedTypeSpec named, TypeMapper typeMap) + { + if (named == null) + return false; + return OwningProtocolFromGenericWithFullPath (named, typeMap) != null; + } + + public ProtocolDeclaration OwningProtocolFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap) + { + AssociatedTypeDeclaration assoc = null; + return OwningProtocolAndAssociateTypeFromGenericWithFullPath (named, typeMap, out assoc); + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap) + { + AssociatedTypeDeclaration assoc = null; + OwningProtocolAndAssociateTypeFromGenericWithFullPath (named, typeMap, out assoc); + return assoc; + } + + ProtocolDeclaration OwningProtocolAndAssociateTypeFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap, out AssociatedTypeDeclaration assoc) + { + assoc = null; + if (named.Name.Contains (".")) { + var parts = named.Name.Split ('.'); + if (IsTypeSpecGeneric (parts [0])) { + // I make assertions about why things can't happen. Here's why: + // If we have func foo(a:T b:T.Foo) + // it means that if the T part of T.Foo is a generic, then T HAS to be + // constrained to a protocol with associated types + // If T.Foo is a path to an associated type, then it + var depthIndex = GetGenericDepthAndIndex (parts [0]); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); + if (genDecl.Constraints.Count != 1) // pretty sure this can't ever happen + return null; + var inh = genDecl.Constraints [0] as InheritanceConstraint; + if (inh == null) // pretty sure this also can't ever happen + return null; + var entity = typeMap.GetEntityForTypeSpec (inh.InheritsTypeSpec); + if (entity == null) // Also can't happen + return null; + if (entity.EntityType != EntityType.Protocol) + return null; // Also can't happen + var protocol = entity.Type as ProtocolDeclaration; + if (protocol != null && protocol.HasAssociatedTypes && (assoc = protocol.AssociatedTypeNamed (parts [1])) != null) { + return protocol; + } + } + } + return null; + } + + public ProtocolDeclaration OwningProtocolFromConstrainedGeneric (NamedTypeSpec named, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex (named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); + return OwningProtocolFromConstrainedGeneric (genDecl, typeMap); + } + + public ProtocolDeclaration OwningProtocolFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) + { + var refProto = RefProtoFromConstrainedGeneric (generic, typeMap); + return refProto?.Protocol; + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric (NamedTypeSpec named, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex (named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); + return AssociatedTypeDeclarationFromConstrainedGeneric (genDecl, typeMap); + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) + { + // looking for where U == T.At1[.At2...] + if (generic.Constraints.Count != 1) + return null; + var eqConstraint = generic.Constraints [0] as EqualityConstraint; + if (eqConstraint == null) + return null; + var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; + if (namedSpec == null) + return null; + var parts = namedSpec.Name.Split ('.'); + if (parts.Length <= 1) + return null; + if (!IsTypeSpecGeneric (parts [0])) + return null; + var refProto = GetConstrainedAssociatedTypeProtocol (new NamedTypeSpec (parts [0]), typeMap); + if (refProto == null) + return null; + if (parts.Length > 2) + throw new NotImplementedException ($"Not currently supporting equality constraints of nested associated types (yet) {eqConstraint.Type1} == {eqConstraint.Type2}"); + return refProto.Protocol.AssociatedTypeNamed (parts [1]); + } + + public GenericReferenceAssociatedTypeProtocol RefProtoFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) + { + // looking for where U == T.At1[.At2...] + if (generic.Constraints.Count != 1) + return null; + var eqConstraint = generic.Constraints [0] as EqualityConstraint; + if (eqConstraint == null) + return null; + var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; + if (namedSpec == null) + return null; + var parts = namedSpec.Name.Split ('.'); + if (parts.Length <= 1) + return null; + if (!IsTypeSpecGeneric (parts [0])) + return null; + return GetConstrainedAssociatedTypeProtocol (new NamedTypeSpec (parts [0]), typeMap); + } + + public bool IsEqualityConstrainedByAssociatedType (NamedTypeSpec name, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex (name); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return false; + var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); + return IsEqualityConstrainedByAssociatedType (genDecl, typeMap); + } + + public bool IsEqualityConstrainedByAssociatedType (GenericDeclaration generic, TypeMapper typeMap) + { + return AssociatedTypeDeclarationFromConstrainedGeneric (generic, typeMap) != null; + } + + public GenericReferenceAssociatedTypeProtocol GetConstrainedAssociatedTypeProtocol (NamedTypeSpec spec, TypeMapper typeMap) + { + // we're looking for the pattern T, where T is a generic or contains a generic (Foo) + // and there exists a where T : SomeProtocol + if (spec == null) + return null; + GenericReferenceAssociatedTypeProtocol result = null; + if (spec.ContainsGenericParameters) { + foreach (var gen in spec.GenericParameters) { + // recurse on generic element + result = GetConstrainedAssociatedTypeProtocol (gen as NamedTypeSpec, typeMap); + if (result != null) + break; + } + } else { + // which declaration has this generic + var owningContext = FindOwningContext (this, spec); + if (owningContext != null) { + foreach (var genPart in Generics) { + if (genPart.Name != spec.Name) + continue; + // genPart is the one we care about - now look for a constraint. + foreach (var constraint in genPart.Constraints) { + // Is it inheritance? + if (constraint is InheritanceConstraint inheritance) { + // Find the entity in the database + var entity = typeMap.TypeDatabase.EntityForSwiftName (inheritance.Inherits); + // Is it a protocol and it has associated types + if (entity != null && entity.Type is ProtocolDeclaration proto && (proto.HasAssociatedTypes || proto.HasDynamicSelfInArguments)) + result = new GenericReferenceAssociatedTypeProtocol () { + GenericPart = spec, + Protocol = proto + }; + } + } + if (result != null) + break; + } + } + } + return result; + } + + static BaseDeclaration FindOwningContext (BaseDeclaration context, NamedTypeSpec spec) + { + while (context != null) { + foreach (var genPart in context.Generics) { + if (genPart.Name == spec.Name) + return context; + } + context = context.Parent; + } + return null; + } + + public bool IsTypeSpecGeneric (TypeSpec sp) + { + if (sp.ContainsGenericParameters) { + foreach (var gen in sp.GenericParameters) { + if (IsTypeSpecGeneric (gen)) + return true; + } + } + + if (sp is NamedTypeSpec named) { + return IsTypeSpecGeneric (named.Name); + } else if (sp is ClosureTypeSpec closure) { + return IsTypeSpecGeneric (closure.Arguments) || IsTypeSpecGeneric (closure.ReturnType); + } else if (sp is TupleTypeSpec tuple) { + foreach (var tupSpec in tuple.Elements) { + if (IsTypeSpecGeneric (tupSpec)) + return true; + } + return false; + } else if (sp is ProtocolListTypeSpec) { + // protocol list type specs can't be generic. + return false; + } else { + throw new NotImplementedException ($"Unknown TypeSpec type {sp.GetType ().Name}"); + } + } + + public bool IsTypeSpecGenericReference (TypeSpec sp) + { + if (sp.ContainsGenericParameters) + return false; + var ns = sp as NamedTypeSpec; + return ns != null && IsTypeSpecGeneric (ns.Name); + } + + public bool IsTypeSpecGenericMetatypeReference (TypeSpec sp) + { + if (sp.ContainsGenericParameters) + return false; + string notUsed; + return sp is NamedTypeSpec ns && IsTypeSpecGenericMetatypeReference (ns.Name, out notUsed); + } + + public bool IsTypeSpecGenericMetatypeReference (string typeSpecName, out string genericPart) + { + if (typeSpecName.Contains ('.')) { + var parts = typeSpecName.Split ('.'); + if (parts.Length == 2 && parts [1] == "Type") { + genericPart = parts [0]; + return true; + } + } + genericPart = null; + return false; + } + + public bool IsTypeSpecGeneric (string typeSpecName) + { + string genericPart; + if (IsTypeSpecGenericMetatypeReference (typeSpecName, out genericPart)) { + return IsTypeSpecGeneric (genericPart); + } else { + foreach (GenericDeclaration gendecl in Generics) { + if (typeSpecName == gendecl.Name) + return true; + } + if (Parent != null) { + return Parent.IsTypeSpecGeneric (typeSpecName); + } else { + return false; + } + } + } + + public int GetTotalDepth () + { + int depth = 0; + BaseDeclaration bd = this; + while (bd.Parent != null) { + if (Parent.ContainsGenericParameters) + depth++; + bd = bd.Parent; + } + return depth; + } + + public Tuple GetGenericDepthAndIndex (string name) + { + return GetGenericDepthAndIndex (name, GetTotalDepth ()); + } + + public Tuple GetGenericDepthAndIndex (TypeSpec spec) + { + var ns = spec as NamedTypeSpec; + if (ns == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 5, $"Can't get generic depth from a {spec.GetType ().Name}."); + return GetGenericDepthAndIndex (ns.Name); + } + + Tuple GetGenericDepthAndIndex (string name, int depth) + { + string genericPart; + if (IsTypeSpecGenericMetatypeReference (name, out genericPart)) { + return GetGenericDepthAndIndex (genericPart, depth); + } else { + for (int i = 0; i < Generics.Count; i++) { + if (Generics [i].Name == name) + return new Tuple (depth, i); + } + if (Parent != null) { + return Parent.GetGenericDepthAndIndex (name, depth - 1); + } + return new Tuple (-1, -1); + } + } + + public GenericDeclaration GetGeneric (int depth, int index) + { + var parentsToWalk = GetMaxDepth () - depth; + BaseDeclaration decl = this; + do { + // skip runs of no generics + while (!decl.ContainsGenericParameters) { + decl = decl.Parent; + } + if (parentsToWalk > 0) { + parentsToWalk--; + decl = decl.Parent; + } + } while (parentsToWalk > 0); + return decl.Generics [index]; + } + + + int GetMaxDepth (int depth) + { + depth += (ContainsGenericParameters ? 1 : 0); + if (Parent == null) + return depth; + return Parent.GetMaxDepth (depth); + } + + public int GetMaxDepth() + { + return GetMaxDepth (-1); + } + + public bool IsPublicOrOpen { + get { + return Access == Accessibility.Public || Access == Accessibility.Open; + } + } + + + public static BaseDeclaration FromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + var generics = GenericDeclaration.FromXElement (folder, elem.Element ("genericparameters")); + BaseDeclaration decl = null; + switch (elem.Name.ToString ()) { + case "func": + decl = FunctionDeclaration.FuncFromXElement (folder, elem, module, parent); + break; + case "typedeclaration": + decl = TypeDeclaration.TypeFromXElement (folder, elem, module, parent); + break; + case "property": + decl = PropertyDeclaration.PropFromXElement (folder, elem, module, parent); + break; + default: + decl = new BaseDeclaration { + Name = (string)elem.Attribute ("name"), + Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")) + }; + break; + } + decl.Generics.AddRange (generics); + decl.Attributes.AddRange (AttributesFromXElement (elem.Element ("attributes"))); + return decl; + } + + internal static IEnumerable AttributesFromXElement (XElement elem) + { + if (elem == null) + return Enumerable.Empty (); + return elem.Elements ("attribute").Select (attr => AttributeDeclaration.FromXElement (attr)); + } + + public virtual string ToFullyQualifiedName (bool includeModule = true) + { + var sb = new StringBuilder (); + BaseDeclaration decl = this; + // recursion? We don't need to stinking recursion! + while (decl != null) { + TypeDeclaration typeDecl = decl as TypeDeclaration; + // unrooted types have no parent, but do have a fully qualified name + if (typeDecl != null && typeDecl.IsUnrooted) { + sb.Insert (0, typeDecl.ToFullyQualifiedName (false)); + break; + } else { + sb.Insert (0, decl.Name); + decl = decl.Parent; + if (decl != null) + sb.Insert (0, '.'); + } + } + if (includeModule) { + sb.Insert (0, '.').Insert (0, Module.Name); + } + return sb.ToString (); + } + + public virtual string ToFullyQualifiedNameWithGenerics () + { + var sb = new StringBuilder (ToFullyQualifiedName ()); + if (ContainsGenericParameters) { + sb.Append ("<"); + for (int i = 0; i < Generics.Count; i++) { + if (i > 0) + sb.Append (", "); + sb.Append (Generics [i].Name); + } + sb.Append (">"); + } + return sb.ToString (); + } + + public override string ToString () + { + return ToFullyQualifiedNameWithGenerics (); + } + } + +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs new file mode 100644 index 000000000000..93e3d167183e --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using SyntaxDynamo.CSLang; + +namespace SwiftReflector.SwiftXmlReflection { + public class ClassDeclaration : TypeDeclaration { + public ClassDeclaration () + : base () + { + Kind = TypeKind.Class; + CSharpMethods = new List (); + CSharpProperties = new List (); + } + + protected override TypeDeclaration UnrootedFactory () + { + return new ClassDeclaration (); + } + + // These are strictly for imported members from C# dll's. + // These members should not get serialized. + public bool IsImportedBinding { get; set; } + public List CSharpMethods { get; } + public List CSharpProperties { get; } + } + +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs new file mode 100644 index 000000000000..a61fc5d2d856 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftReflector.ExceptionTools; +using System.Xml.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + public class EnumDeclaration : TypeDeclaration { + public EnumDeclaration () + : base () + { + Kind = TypeKind.Enum; + Elements = new List (); + } + + protected override TypeDeclaration UnrootedFactory () + { + return new EnumDeclaration (); + } + + protected override void CompleteUnrooting (TypeDeclaration unrooted) + { + base.CompleteUnrooting (unrooted); + EnumDeclaration enumDecl = unrooted as EnumDeclaration; + if (enumDecl == null) + throw new ArgumentException ("unrooted type was not constructed by EnumDeclaration"); + enumDecl.Elements.AddRange (Elements); + } + + public List Elements { get; private set; } + public bool ElementIsGeneric (EnumElement element) + { + return IsTypeSpecGeneric (element.TypeSpec); + } + + public bool HasRawType { get { return rawTypeName != null && RawTypeSpec != null; } } + + string rawTypeName; + public string RawTypeName { + get { + return rawTypeName; + } + set { + rawTypeName = value; + if (value == null) + RawTypeSpec = null; + else { + try { + RawTypeSpec = TypeSpecParser.Parse (rawTypeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 8, $"Unable to parse type name '{rawTypeName}': {ex.Message}"); + } + } + } + } + public TypeSpec RawTypeSpec { get; private set; } + + public bool IsTrivial { + get { + if (HasRawType) + return false; + if (Inheritance.Count > 0) + return false; + foreach (EnumElement elem in Elements) { + if (elem.HasType) + return false; + } + return true; + } + } + + public bool IsIntegral { + get { + if (HasRawType) { + return TypeSpec.IsIntegral (RawTypeSpec); + } + foreach (EnumElement elem in Elements) { + if (elem.HasType && !TypeSpec.IsIntegral (elem.TypeSpec)) + return false; + } + return true; + } + } + + public bool IsHomogenous { + get { + if (Elements.Count == 0) + return true; + TypeSpec firstSpec = Elements [0].TypeSpec; + for (int i = 1; i < Elements.Count; i++) { + TypeSpec nextSpec = Elements [i].TypeSpec; + if (firstSpec == null) { + if (firstSpec != nextSpec) + return false; + } else { + if (!firstSpec.Equals (nextSpec)) + return false; + } + } + return true; + } + } + + public EnumElement this [string s] { + get { + return Elements.FirstOrDefault (elem => elem.Name == s); + } + } + + + protected override void GatherXObjects (List xobjects) + { + base.GatherXObjects (xobjects); + if (HasRawType) + xobjects.Add (new XAttribute ("rawType", RawTypeName)); + IEnumerable elems = Elements.Select (e => e.ToXElement ()); + xobjects.Add (new XElement ("elements", elems.ToArray ())); + } + + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs new file mode 100644 index 000000000000..e8177e344b79 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using SwiftReflector.IOUtils; +using System.Xml.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class EnumElement : IXElementConvertible { + public EnumElement (string name, string typeName, long? value) + { + Name = Exceptions.ThrowOnNull (name, nameof(name)); + TypeName = typeName; + Value = value; + } + + public string Name { get; set; } + public bool HasType { get { return typeName != null && TypeSpec != null; } } + string typeName; + public string TypeName { + get { + return typeName; + } + set { + typeName = value; + if (value == null) + TypeSpec = null; + else { + try { + TypeSpec = TypeSpecParser.Parse (typeName); + } catch (RuntimeException ex) { + ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 9, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + } + public TypeSpec TypeSpec { get; private set; } + public long? Value { get; private set; } + + #region IXElementConvertible implementation + public XElement ToXElement () + { + XElement elem = new XElement ("element", + new XAttribute ("name", Name)); + if (HasType) + elem.Add (new XAttribute ("type", TypeName)); + if (Value.HasValue) + elem.Add ("intValue", Value.Value); + return elem; + } + #endregion + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/Enums.cs b/src/SwiftReflector/SwiftXmlReflection/Enums.cs new file mode 100644 index 000000000000..19a2909b9b8e --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/Enums.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SwiftReflector.SwiftXmlReflection { + public enum TypeKind { + Unknown = 0, + Class, + Struct, + Enum, + Protocol + } + + public enum Accessibility { + Unknown = 0, + Public, + Private, + Internal, + Open, + } + + public enum StorageKind { + Unknown = 0, + Addressed, + AddressedWithObservers, + AddressedWithTrivialAccessors, + Computed, + ComputedWithMutableAddress, + Inherited, + InheritedWithObservers, + Stored, + StoredWithObservers, + StoredWithTrivialAccessors, + Coroutine, + MutableAddressor, + } + + public enum TypeSpecKind { + Named = 0, + Tuple, + Closure, + ProtocolList, + } + + public enum TypeTokenKind { + TypeName, + Comma, + LeftParenthesis, + RightParenthesis, + LeftAngle, + RightAngle, + LeftBracket, + RightBracket, + Arrow, + At, + QuestionMark, + TypeLabel, + Colon, + ExclamationPoint, + Period, + Ampersand, + Done, + } + + public enum InheritanceKind { + Class, + Protocol + } + + public enum ConstraintKind { + Inherits, + Equal + } + + public enum AttributeParameterKind { + None, + Label, + Literal, + Sublist, + Unknown, + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs new file mode 100644 index 000000000000..3cbd7e61368c --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.ExceptionTools; +using SwiftReflector.IOUtils; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class ExtensionDeclaration : IXElementConvertible { + + public ExtensionDeclaration () + { + Inheritance = new List (); + Members = new List (); + } + + public ExtensionDeclaration (ExtensionDeclaration other) + : this () + { + Inheritance.AddRange (other.Inheritance); + Members.AddRange (other.Members); + ExtensionOnTypeName = other.ExtensionOnTypeName; + Module = other.Module; + } + + public ModuleDeclaration Module { get; set; } + public List Inheritance { get; set; } + string extensionOnTypeName; + public string ExtensionOnTypeName { + get { + return extensionOnTypeName; + } + set { + extensionOnTypeName = Exceptions.ThrowOnNull (value, "value"); + try { + ExtensionOnType = TypeSpecParser.Parse (extensionOnTypeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase, $"Unable to parse type name '{extensionOnTypeName}': {ex.Message}"); + } + + } + } + public TypeSpec ExtensionOnType { get; private set; } + public List Members { get; set; } + + public XElement ToXElement () + { + var xobjects = new List (); + GatherXObjects (xobjects); + XElement typeDecl = new XElement ("extension", xobjects.ToArray ()); + return typeDecl; + } + + void GatherXObjects (List xobjects) + { + xobjects.Add (new XAttribute ("onType", ExtensionOnTypeName)); + List memcontents = new List (Members.Select (m => m.ToXElement ())); + xobjects.Add (new XElement ("members", memcontents.ToArray ())); + List inherits = new List (Inheritance.Select (i => i.ToXElement ())); + xobjects.Add (new XElement ("inherits", inherits.ToArray ())); + } + + public static ExtensionDeclaration FromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module) + { + var decl = new ExtensionDeclaration (); + decl.Module = module; + decl.ExtensionOnTypeName = (string)elem.Attribute ("onType"); + decl.ExtensionOnType = folder.FoldAlias (null, decl.ExtensionOnType); + if (elem.Element ("members") != null) { + var members = from mem in elem.Element ("members").Elements () + select Member.FromXElement (folder, mem, module, null) as Member; + decl.Members.AddRange (members); + foreach (var member in decl.Members) { + member.ParentExtension = decl; + } + } + if (elem.Element ("inherits") != null) { + var inherits = from inherit in elem.Element ("inherits").Elements () + select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement (folder, inherit) as Inheritance; + decl.Inheritance.AddRange (inherits); + } + return decl; + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs new file mode 100644 index 000000000000..926e2319cd20 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Xml.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + + public static class ExtensionMethods { + // surprise! You'd think that you could write this code: + // public static T DefaultedAttribute(this XElement elem, XName name, T defaultValue = default(T)) + // { + // XAttribute attr = elem.Attribute (name); + // if (attr == null) + // return defaultValue; + // return (T)attr; + // } + // but the last cast won't work because generics aren't templates. + + // So instead, we get to repeat ourselves a lot. + + public static bool BoolAttribute (this XElement elem, XName name, bool defaultValue = default (bool)) + { + XAttribute attr = elem.Attribute (name); + if (attr == null) + return defaultValue; + return (bool)attr; + } + + public static double DoubleAttribute (this XElement elem, XName name, double defaultValue = default (double)) + { + XAttribute attr = elem.Attribute (name); + if (attr == null) + return defaultValue; + return (double)attr; + } + + public static bool IsPrivateOrInternal (this Accessibility a) + { + return a == Accessibility.Private || a == Accessibility.Internal; + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs new file mode 100644 index 000000000000..4bbbdbac5f3a --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs @@ -0,0 +1,471 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using SwiftReflector.ExceptionTools; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class FunctionDeclaration : Member { + public const string kConstructorName = ".ctor"; + public const string kDestructorName = ".dtor"; + public const string kPropertyGetterPrefix = "get_"; + public const string kPropertySetterPrefix = "set_"; + public const string kPropertyMaterializerPrefix = "materializeforset_"; + public const string kPropertySubscriptGetterName = "get_subscript"; + public const string kPropertySubscriptSetterName = "set_subscript"; + public const string kPropertySubscriptMaterializerName = "materializeforset_subscript"; + + static string [] subscriptNames = new string [] { + kPropertySubscriptGetterName, + kPropertySubscriptSetterName, + kPropertySubscriptMaterializerName, + }; + static bool IsSubscriptName (string s) + { + return Array.IndexOf (subscriptNames, s) >= 0; + } + + public FunctionDeclaration () + : base () + { + ParameterLists = new List> (); + } + + public FunctionDeclaration (FunctionDeclaration other) + : base (other) + { + ParameterLists = CopyOf (other.ParameterLists); + ReturnTypeName = other.ReturnTypeName; + IsProperty = other.IsProperty; + IsStatic = other.IsStatic; + IsFinal = other.IsFinal; + HasThrows = other.HasThrows; + IsDeprecated = other.IsDeprecated; + IsUnavailable = other.IsUnavailable; + OperatorType = other.OperatorType; + IsOptional = other.IsOptional; + ObjCSelector = other.ObjCSelector; + IsRequired = other.IsRequired; + IsConvenienceInit = other.IsConvenienceInit; + IsAsync = other.IsAsync; + foreach (var genDecl in other.Generics) { + Generics.Add (new GenericDeclaration (genDecl)); + } + } + + string returnTypeName; + public string ReturnTypeName { + get { return returnTypeName; } + set { + returnTypeName = Exceptions.ThrowOnNull (value, "value"); + try { + ReturnTypeSpec = TypeSpecParser.Parse (returnTypeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 1, $"Unable to parse type name '{returnTypeName}': {ex.Message}"); + } + } + } + + + // When writing an override, we need to keep around the function in the override + // this member should never get serialized. Ever. + public FunctionDeclaration OverrideSurrogateFunction { get; set; } + + + public TypeSpec ReturnTypeSpec { get; private set; } + + public bool IsRequired { get; set; } + public string ObjCSelector { get; set; } + public bool IsOptional { get; set; } + public bool HasThrows { get; set; } + public bool IsAsync { get; set; } + public bool IsProperty { get; set; } + public string PropertyName { get { return Name.Substring (kPropertyGetterPrefix.Length); } } + public bool IsStatic { get; set; } + public bool IsFinal { get; set; } + public bool IsOperator { get { return OperatorType != OperatorType.None; } } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsConvenienceInit { get; set; } + public bool IsVirtualClassMethod { get { return IsStatic && Access == Accessibility.Open; } } + public bool IsSubscript { + get { + return IsProperty && IsSubscriptName (Name); + } + } + public OperatorType OperatorType { get; set; } + public bool IsSubscriptGetter { + get { + return IsProperty && Name == kPropertySubscriptGetterName; + } + } + public bool IsSubscriptSetter { + get { + return IsProperty && Name == kPropertySubscriptSetterName; + } + } + // in practice, this is useless since it is near impossible to disambiguate it + // and it has no actual use from our point of view. Materializers are code used + // internally by the compiler and we don't really have access to this. + public bool IsSubscriptMaterializer { + get { + return IsProperty && Name == kPropertySubscriptMaterializerName; + } + } + + public TypeSpec PropertyType { + get { + if (!IsProperty) + throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 17, $"Attempt to get property type for a function named {this.Name}"); + // newValue should be the first argument in the last argument list. + return ParameterLists.Last () [0].TypeSpec; + } + } + + public List> ParameterLists { get; private set; } + + public bool IsTypeSpecGeneric (ParameterItem item) + { + return IsTypeSpecGeneric (item.TypeSpec); + } + + public int GenericParameterCount { + get { + return ParameterLists.Last ().Sum (pi => IsTypeSpecGeneric (pi) ? 1 : 0); + } + } + + public bool MatchesSignature (FunctionDeclaration other, bool ignoreFirstParameterListIfPresent) + { + if (!TypeSpec.BothNullOrEqual (this.ReturnTypeSpec, other.ReturnTypeSpec)) + return false; + if (this.ParameterLists.Count != other.ParameterLists.Count) + return false; + int startIndex = ignoreFirstParameterListIfPresent && this.ParameterLists.Count > 1 ? 1 : 0; + + for (int i = startIndex; i < this.ParameterLists.Count; i++) { + if (!ParameterItem.AreEqualIgnoreNamesReferencesInvariant (this, this.ParameterLists [i], other, other.ParameterLists [i], true)) + return false; + } + return true; + } + + public bool IsConstructor { get { return Name == kConstructorName; } } + public bool IsDestructor { get { return Name == kDestructorName; } } + public bool IsConstructorOrDestructor { get { return IsConstructor || IsDestructor; } } + public bool IsGetter { get { return IsProperty && Name.StartsWith (kPropertyGetterPrefix); } } + public bool IsSetter { get { return IsProperty && Name.StartsWith (kPropertySetterPrefix); } } + public bool IsMaterializer { get { return IsProperty && Name.StartsWith (kPropertyMaterializerPrefix); } } + + public bool IsOptionalConstructor { + get { + if (Name != kConstructorName) + return false; + var namedSpec = ReturnTypeSpec as NamedTypeSpec; + if (namedSpec == null) + return false; + if (namedSpec.Name != "Swift.Optional") + return false; + if (namedSpec.GenericParameters.Count != 1) + return false; + // previously we did a name check on the parent but in the case of + // a virtual class, the name could be the proxy class that we make + // and won't necessarily match. + return true; + } + } + + public bool IsVariadic { + get { + return ParameterLists.Last ().Any (pi => pi.IsVariadic); + } + } + + public FunctionDeclaration MatchingSetter (IEnumerable decls) + { + if (!IsProperty) + return null; + if (IsSubscript) { + return decls.Where (f => f.IsSubscriptSetter && SubscriptParametersMatch (this, f)).FirstOrDefault (); + } else { + return decls.Where (f => f.IsSetter && f.PropertyName == PropertyName).FirstOrDefault (); + } + } + + static bool SubscriptParametersMatch (FunctionDeclaration getter, FunctionDeclaration setter) + { + if (getter.ParameterLists.Count != 2 || setter.ParameterLists.Count != 2) + return false; + TypeSpec returnType = getter.ReturnTypeSpec; + if (getter.ParameterLists [1].Count != setter.ParameterLists [1].Count - 1) + return false; + if (!returnType.Equals (setter.ParameterLists [1] [0].TypeSpec)) + return false; + + return ParameterItem.AreEqualIgnoreNamesReferencesInvariant (getter, getter.ParameterLists [1], + setter, setter.ParameterLists [1].Skip (1).ToList (), true); + } + + + public bool ContainsBoundGenericClosure () + { + foreach (var arg in ParameterLists.Last ()) { + if (arg.TypeSpec.ContainsBoundGenericClosure ()) + return true; + } + return ReturnTypeSpec.ContainsBoundGenericClosure (); + } + + + public static FunctionDeclaration FuncFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + FunctionDeclaration decl = new FunctionDeclaration { + Name = (string)elem.Attribute ("name"), + Module = module, + Parent = parent, + Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")), + ReturnTypeName = Exceptions.ThrowOnNull ((string)elem.Attribute ("returnType"), "returnType"), + IsAsync = elem.BoolAttribute ("isAsync"), + IsProperty = elem.BoolAttribute ("isProperty"), + IsStatic = elem.BoolAttribute ("isStatic"), + IsFinal = elem.BoolAttribute ("isFinal"), + OperatorType = OperatorTypeFromElement ((string)elem.Attribute ("operatorKind")), + HasThrows = elem.BoolAttribute ("hasThrows"), + IsDeprecated = elem.BoolAttribute ("isDeprecated"), + IsUnavailable = elem.BoolAttribute ("isUnavailable"), + IsOptional = elem.BoolAttribute ("isOptional"), + ObjCSelector = (string)elem.Attribute ("objcSelector"), + IsRequired = elem.BoolAttribute ("isRequired"), + IsConvenienceInit = elem.BoolAttribute ("isConvenienceInit") + }; + decl.ReturnTypeSpec = folder.FoldAlias (parent, decl.ReturnTypeSpec); + decl.ParameterLists.AddRange (ParameterItem.ParameterListListFromXElement (folder, elem.Element ("parameterlists"))); + if (decl.IsProperty && (decl.IsSetter || decl.IsSubscriptSetter)) { + decl.ParameterLists [decl.ParameterLists.Count - 1] = + MassageLastPropertySetterParameterList (decl.ParameterLists.Last ()); + } + return decl; + } + + static List MassageLastPropertySetterParameterList (List list) + { + if (list.Count == 0) + return list; // should never happen, but... + + if (list.Any (pi => pi.PublicName == "newValue")) + return list; // also should never happen, but... + + var firstParam = list [0]; + var firstParamName = firstParam.NameIsRequired ? firstParam.PublicName : firstParam.PrivateName; + // why the check on both value and newValue? Because we want both the public and private names to be newValue + if (firstParamName == "value" || firstParamName == "newValue") // because swift reflects this incorrectly + { + firstParam.PublicName = firstParam.PrivateName = "newValue"; + } + + return list; + } + + + protected override XElement MakeXElement () + { + XElement theFunc = new XElement ("func", + new XAttribute ("name", Name), + new XAttribute ("accessibility", TypeDeclaration.ToString (Access)), + new XAttribute ("returnType", ReturnTypeName), + new XAttribute ("isAsync", BoolString (IsAsync)), + new XAttribute ("isProperty", BoolString (IsProperty)), + new XAttribute ("isStatic", BoolString (IsStatic)), + new XAttribute ("isFinal", BoolString (IsFinal)), + new XAttribute ("isDeprecated", BoolString (IsDeprecated)), + new XAttribute ("isUnavailable", BoolString (IsUnavailable)), + new XAttribute ("isOptional", BoolString (IsOptional)), + new XAttribute ("operatorKind", OperatorType.ToString()), + new XAttribute ("hasThrows", BoolString (HasThrows)), + new XAttribute ("isRequired", BoolString (IsRequired)), + new XAttribute ("isConvenienceInit", BoolString (IsConvenienceInit)), + new XElement ("parameterlists", MakeParamListXElement ())); + if (!String.IsNullOrEmpty (ObjCSelector)) + theFunc.Add (new XAttribute ("objcSelector", ObjCSelector)); + return theFunc; + } + + XElement [] MakeParamListXElement () + { + List plists = new List (); + int index = 0; + foreach (List list in ParameterLists) { + XElement thisList = new XElement ("parameterlist", + new XAttribute ("index", index), + list.Select ((pi, i) => { + XElement elem = pi.ToXElement (); + elem.Add (new XAttribute ("index", i)); + return elem; + }).ToArray ()); + plists.Add (thisList); + index++; + } + return plists.ToArray (); + } + + static List> CopyOf (List> src) + { + List> dst = new List> (); + dst.AddRange (src.Select (l => CopyOf (l))); + return dst; + } + + static List CopyOf (List src) + { + List dst = new List (); + dst.AddRange (src.Select (pi => new ParameterItem (pi))); + return dst; + } + + public static OperatorType OperatorTypeFromElement (string type) + { + var enumType = OperatorType.None; + if (Enum.TryParse (type, out enumType)) + return enumType; + return OperatorType.None; + } + + static string BoolString (bool b) + { + return b ? "true" : "false"; + } + + string PropertyKindString { + get { + if (IsSubscriptGetter || IsGetter) { + return "get"; + } else if (IsSubscriptSetter || IsSetter) { + return "set"; + } else if (IsSubscriptMaterializer || IsMaterializer) { + return "materialize"; + } + return ""; + } + } + + public override bool HasDynamicSelf { + get { + var types = ParameterLists.Last ().Select (p => p.TypeSpec).ToList (); + if (!TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec)) + types.Add (ReturnTypeSpec); + return TypeSpec.AnyHasDynamicSelf (types); + } + } + + public override bool HasDynamicSelfInReturnOnly { + get { + if (IsProperty && !IsSubscript) + return false; + if (TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec) || !ReturnTypeSpec.HasDynamicSelf) + return false; + var types = ParameterLists.Last ().Select (p => p.TypeSpec).ToList (); + return !TypeSpec.AnyHasDynamicSelf (types); + } + } + + public override bool HasDynamicSelfInArguments { + get { + return TypeSpec.AnyHasDynamicSelf (ParameterLists.Last ().Select (p => p.TypeSpec).ToList ()); + } + } + + public FunctionDeclaration MacroReplaceType (string toFind, string replaceWith, bool skipThisArgument) + { + var newFunc = new FunctionDeclaration (this); + if (!TypeSpec.IsNullOrEmptyTuple (newFunc.ReturnTypeSpec)) { + newFunc.ReturnTypeName = newFunc.ReturnTypeSpec.ReplaceName (toFind, replaceWith).ToString (); + } + for (int i = 0; i < newFunc.ParameterLists.Last ().Count; i++) { + var arg = newFunc.ParameterLists.Last () [i]; + if (skipThisArgument && arg.PublicName == "this") + continue; + arg.TypeSpec = arg.TypeSpec.ReplaceName (toFind, replaceWith); + } + return newFunc; + } + + internal string ParametersToString () + { + var builder = new StringBuilder (); + var first = true; + foreach (var parm in ParameterLists.Last ()) { + if (!first) { + builder.Append (", "); + } else { + first = false; + } + // forms + // public_name private_name: [inout] Type + // public_name: [inout] Type + // _ private_name: [inout] Type + if (parm.PublicName == parm.PrivateName) { + builder.Append (parm.PublicName); + } else if (parm.NameIsRequired) { + builder.Append (parm.PublicName).Append (" ").Append (parm.PrivateName); + } else { + builder.Append ("_ ").Append (parm.PrivateName); + } + builder.Append (": "); + if (parm.IsInOut || parm.TypeSpec.IsInOut) + builder.Append ("inout "); + builder.Append (parm.TypeSpec); + } + return builder.ToString (); + } + + public override string ToString () + { + // Forms: + // access [modfiers] var Name: Type { [get | set] } [throws] + // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] + // access [modifiers] Name(args) -> Type [throws] + + var builder = new StringBuilder (); + builder.Append (Access).Append (" "); + if (IsFinal) + builder.Append ("final "); + if (IsStatic) + builder.Append ("static "); + + + if (IsProperty) { + if (IsSubscript) { + builder.Append (Parent.ToString ()).Append (".subscript"); + builder.Append (" [").Append (ParametersToString ()).Append ("] -> "); + } else { + builder.Append ("var ").Append (Parent.ToString ()).Append (".").Append (PropertyName); + builder.Append (": "); + } + builder.Append (ReturnTypeName).Append (" { ").Append (PropertyKindString).Append (" }"); + if (HasThrows) { + builder.Append (" throws"); + } + } else { + builder.Append (base.ToString ()); + builder.Append (" (").Append (ParametersToString ()).Append (")"); + if (HasThrows) { + builder.Append (" throws"); + } + + builder.Append (" -> "); + if (TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec)) { + builder.Append ("()"); + } else { + builder.Append (ReturnTypeSpec); + } + } + return builder.ToString (); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs new file mode 100644 index 000000000000..818b79522f3a --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Xml.Linq; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftXmlReflection { + public class GenericDeclaration { + public GenericDeclaration () + { + Constraints = new List (); + } + + public GenericDeclaration (string name) + : this () + { + Name = name; + } + + public GenericDeclaration (GenericDeclaration other) + : this () + { + Name = other.Name; + foreach (var constraint in other.Constraints) { + Constraints.Add (BaseConstraint.CopyOf (constraint)); + } + } + + + public string Name { get; set; } + public List Constraints { get; private set; } + + public bool IsProtocolConstrained (TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) { + ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); + } else { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType != EntityType.Protocol) + return false; + } + return true; + } + + public bool IsAssociatedTypeProtocolConstrained (TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) { + ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); + } else { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType != EntityType.Protocol) + return false; + if (ent.Type is ProtocolDeclaration proto && !proto.IsExistential) + return true; + } + return false; + } + + public bool IsClassConstrained (TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) { + ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); + } else { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType == EntityType.Class) + return true; + } + return false; + + } + + public static List FromXElement (TypeAliasFolder folder, XElement generic) + { + List decls = new List (); + if (generic == null) + return decls; + decls.AddRange (from decl in generic.Descendants ("param") select new GenericDeclaration ((string)decl.Attribute ("name"))); + + var constraints = from constr in generic.Descendants ("where") select BaseConstraint.FromXElement (folder, constr); + foreach (BaseConstraint constr in constraints) { + GenericDeclaration decl = FindGenericDeclFor (constr, decls); + if (decl != null) + decl.Constraints.Add (constr); + } + + return decls; + } + + static GenericDeclaration FindGenericDeclFor (BaseConstraint constraint, List decls) + { + string nameToMatch = constraint.EffectiveTypeName (); + if (nameToMatch == null) + return null; + return decls.FirstOrDefault (d => d.Name == nameToMatch); + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs new file mode 100644 index 000000000000..1c66b0737dfa --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.IOUtils; + +namespace SwiftReflector.SwiftXmlReflection { + public class GenericDeclarationCollection : List, IXElementConvertible { + public GenericDeclarationCollection () + : base () + { + } + + public GenericDeclarationCollection (int capacity) + : base (capacity) + { + } + + public XElement ToXElement () + { + if (Count == 0) + return null; + XElement genparms = new XElement ("genericparameters"); + + foreach (GenericDeclaration decl in this) { + XElement param = new XElement ("param", new XAttribute ("name", decl.Name)); + genparms.Add (param); + } + foreach (GenericDeclaration decl in this) { + if (decl.Constraints.Count > 0) { + foreach (BaseConstraint bc in decl.Constraints) { + XElement bcel = bc.ToXElement (); + if (bcel != null) + genparms.Add (bcel); + } + } + } + return genparms; + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs b/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs new file mode 100644 index 000000000000..2924d1300303 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SwiftReflector.SwiftXmlReflection { + public class GenericReferenceAssociatedTypeProtocol { + public NamedTypeSpec GenericPart { get; set; } + public ProtocolDeclaration Protocol { get; set; } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs new file mode 100644 index 000000000000..32adc91891ef --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.IOUtils; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class Inheritance : IXElementConvertible { + public Inheritance (string inheritedTypeName, InheritanceKind inheritanceKind) + { + this.InheritanceKind = inheritanceKind; + InheritedTypeName = inheritedTypeName; + } + + public InheritanceKind InheritanceKind { get; private set; } + + string inheritedTypeName; + public string InheritedTypeName { + get { return inheritedTypeName; } + set { + inheritedTypeName = Exceptions.ThrowOnNull (value, nameof(value)); + try { + InheritedTypeSpec = TypeSpecParser.Parse (inheritedTypeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 7, $"Unable to parse type name '{inheritedTypeName}': {ex.Message}"); + } + } + } + public TypeSpec InheritedTypeSpec { get; private set; } + + public static Inheritance FromXElement (TypeAliasFolder folder, XElement elem) + { + string typeName = (string)elem.Attribute ("type"); + string inheritanceKindStr = (string)elem.Attribute ("inheritanceKind"); + InheritanceKind kind = ToInheritanceKind (inheritanceKindStr); + var inheritance = new Inheritance (typeName, kind); + inheritance.InheritedTypeSpec = folder.FoldAlias (null, inheritance.InheritedTypeSpec); + return inheritance; + } + + public XElement ToXElement () + { + return new XElement ("inherit", new XAttribute ("type", InheritedTypeName), + new XAttribute ("inheritanceKind", ToString (InheritanceKind))); + } + + static string ToString (InheritanceKind kind) + { + switch (kind) { + case InheritanceKind.Class: + return "class"; + case InheritanceKind.Protocol: + return "protocol"; + default: + throw new ArgumentOutOfRangeException (nameof(kind)); + } + } + + static InheritanceKind ToInheritanceKind (string kindStr) + { + Exceptions.ThrowOnNull (kindStr, nameof(kindStr)); + switch (kindStr) { + case "protocol": + return InheritanceKind.Protocol; + case "class": + return InheritanceKind.Class; + default: + throw new ArgumentOutOfRangeException (nameof (kindStr), String.Format ("Expected either protocol or class, but got {0}.", + kindStr)); + } + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/Member.cs b/src/SwiftReflector/SwiftXmlReflection/Member.cs new file mode 100644 index 000000000000..a32859f3d383 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/Member.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Xml.Linq; +using SwiftReflector.IOUtils; + +namespace SwiftReflector.SwiftXmlReflection { + public abstract class Member : BaseDeclaration, IXElementConvertible { + protected Member () + : base () + { + } + + protected Member (Member other) + : base (other) + { + } + + public bool IsProtocolMember { get { return Parent != null && Parent is ProtocolDeclaration; } } + + #region IXElementConvertible implementation + + public XElement ToXElement () + { + return MakeXElement (); + } + + protected virtual XElement MakeXElement () + { + throw new NotImplementedException (); + } + #endregion + + public abstract bool HasDynamicSelf { + get; + } + + public abstract bool HasDynamicSelfInReturnOnly { + get; + } + + public abstract bool HasDynamicSelfInArguments { + get; + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs new file mode 100644 index 000000000000..8d8ed94c94c1 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftXmlReflection { + public class ModuleDeclaration { + public ModuleDeclaration () + { + Declarations = new List (); + Extensions = new List (); + Operators = new List (); + TypeAliases = new List (); + } + + public ModuleDeclaration (string name) + : this () + { + Name = name; + } + + public string Name { get; set; } + public bool IsUnrooted { get; private set; } + + public ModuleDeclaration MakeUnrooted () + { + if (IsUnrooted) + return this; + ModuleDeclaration unrooted = new ModuleDeclaration (); + unrooted.IsUnrooted = true; + unrooted.Name = Name; + return unrooted; + } + + public List Declarations { get; private set; } + public List TypeAliases { get; private set; } + + public static ModuleDeclaration FromXElement (XElement elem, TypeDatabase typeDatabase) + { + ModuleDeclaration decl = new ModuleDeclaration { + Name = (string)elem.Attribute ("name"), + SwiftCompilerVersion = new Version((string)elem.Attribute("swiftVersion") ?? "3.1") + }; + + decl.TypeAliases.AddRange (elem.Descendants ("typealias").Select (al => TypeAliasDeclaration.FromXElement (decl.Name, al))); + var folder = new TypeAliasFolder (decl.TypeAliases); + folder.AddDatabaseAliases (typeDatabase); + + // non extensions + foreach (var child in elem.Elements()) { + if (child.Name == "extension") { + decl.Extensions.Add (ExtensionDeclaration.FromXElement (folder, child, decl)); + } else if (child.Name == "operator") { + decl.Operators.Add (OperatorDeclaration.FromXElement (child, child.Attribute ("moduleName")?.Value)); + } else { + decl.Declarations.Add (BaseDeclaration.FromXElement (folder, child, decl, null)); + } + } + return decl; + } + + public Version SwiftCompilerVersion { get; set; } + public bool IsEmpty () + { + return Declarations.Count == 0 && Extensions.Count == 0; + } + + public IEnumerable Classes { get { return Declarations.OfType ().Where (cd => !(cd is ProtocolDeclaration)); } } + public IEnumerable Structs { get { return Declarations.OfType (); } } + public IEnumerable Enums { get { return Declarations.OfType (); } } + public IEnumerable Protocols { get { return Declarations.OfType (); } } + public IEnumerable Functions { get { return Declarations.OfType (); } } + public IEnumerable Properties { get { return Declarations.OfType (); } } + public IEnumerable TopLevelFunctions { get { return Functions.Where (f => f.Parent == null && f.Access == Accessibility.Public || f.Access == Accessibility.Open); } } + public IEnumerable TopLevelProperties { get { return Properties.Where (p => p.Parent == null && p.Access == Accessibility.Public || p.Access == Accessibility.Open); } } + public List Extensions { get; private set; } + public List Operators { get; private set; } + + + public bool IsCompilerCompatibleWith(Version targetCompilerVersion) + { + // yes, this could be an equality comparison, but I expect some + // level of backwards compatability at some point, so flesh it out now. + switch (SwiftCompilerVersion.Major) { + case 2: + return false; // No. Just no. + case 3: + return targetCompilerVersion.Major == 3; + case 4: + return targetCompilerVersion.Major == 4; + case 5: + return targetCompilerVersion.Major == 5; + default: + return false; // not yet, thanks. + } + } + + public List AllClasses { + get { + return AllFooHelper (); + } + } + + public List AllStructs { + get { + return AllFooHelper (); + } + } + + public List AllEnums { + get { + return AllFooHelper (); + } + } + + public List AllProtocols { + get { + // no chicanery here - all protocol definitions are top-level + return Protocols.ToList (); + } + } + + List AllFooHelper () where T : TypeDeclaration + { + List ts = new List (); + AddAllInto (Classes, ts); + AddAllInto (Structs, ts); + AddAllInto (Enums, ts); + return ts; + } + + + void AddAllInto (IEnumerable someTypes, List repository) where T : TypeDeclaration + { + foreach (TypeDeclaration t in someTypes) { + if (t is T) + repository.Add ((T)t); + AddAllInto (t.InnerClasses, repository); + AddAllInto (t.InnerStructs, repository); + AddAllInto (t.InnerEnums, repository); + } + } + + + public List AllTypesAndTopLevelDeclarations { + get { + List decls = new List (); + AddAllDeclsInto (Declarations, decls); + return decls; + } + } + + void AddAllDeclsInto (IEnumerable someDecls, List allDecls) + { + foreach (BaseDeclaration d in someDecls) { + allDecls.Add (d); + TypeDeclaration t = d as TypeDeclaration; + if (t != null) { + AddAllDeclsInto (t.InnerClasses, allDecls); + AddAllDeclsInto (t.InnerStructs, allDecls); + AddAllDeclsInto (t.InnerEnums, allDecls); + } + } + } + + public List AllTypes { + get { + List types = new List (); + AddAllTypesInto (Declarations.OfType (), types); + return types; + } + } + + void AddAllTypesInto (IEnumerable someTypes, List allTypes) + { + foreach (TypeDeclaration t in someTypes) { + allTypes.Add (t); + AddAllTypesInto (t.InnerClasses, allTypes); + AddAllTypesInto (t.InnerStructs, allTypes); + AddAllTypesInto (t.InnerEnums, allTypes); + } + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs new file mode 100644 index 000000000000..c45f5e86d699 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Xml.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + public class OperatorDeclaration { + public OperatorDeclaration () + { + } + + public string ModuleName { get; private set; } + public string Name { get; private set; } + public OperatorType OperatorType { get; private set; } + public string PrecedenceGroup { get; private set; } + + public XElement ToXElement () + { + var xobjects = new List (); + GatherXObjects (xobjects); + XElement typeDecl = new XElement ("operator", xobjects.ToArray ()); + return typeDecl; + } + + void GatherXObjects (List xobjects) + { + xobjects.Add (new XAttribute ("name", Name)); + if (PrecedenceGroup != null) + xobjects.Add (new XAttribute ("precedenceGroup", PrecedenceGroup)); + xobjects.Add (new XAttribute ("operatorKind", OperatorType.ToString ())); + } + + public static OperatorDeclaration FromXElement (XElement elem, string module) + { + return new OperatorDeclaration () { + ModuleName = module ?? elem.Attribute ("moduleName")?.Value ?? "", + Name = elem.Attribute ("name").Value, + PrecedenceGroup = NullOnNullOrEmpty (elem.Attribute ("precedenceGroup")?.Value), + OperatorType = FunctionDeclaration.OperatorTypeFromElement ((string)elem.Attribute ("operatorKind")) + }; + } + + static string NullOnNullOrEmpty (string s) + { + return String.IsNullOrEmpty (s) ? null : s; + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs new file mode 100644 index 000000000000..b319cae0085b --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.Inventory; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.ExceptionTools; +using SwiftReflector.IOUtils; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class ParameterItem : IXElementConvertible { + public static string kInOutMarker = "inout "; + public ParameterItem () + { + } + + public ParameterItem (ParameterItem pi) + { + PublicName = pi.PublicName; + PrivateName = pi.PrivateName; + TypeName = pi.TypeName; + IsInOut = pi.IsInOut; + IsVariadic = pi.IsVariadic; + } + + public string PublicName { get; set; } + public string PrivateName { get; set; } + public bool NameIsRequired { get { return !String.IsNullOrEmpty (PublicName); } } + public bool IsVariadic { get; set; } + + string typeName; + public string TypeName { + get { return typeName; } + set { + typeName = Exceptions.ThrowOnNull (value, nameof(value)); + try { + typeSpec = TypeSpecParser.Parse (typeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 2, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + TypeSpec typeSpec; + public TypeSpec TypeSpec { + get { return typeSpec; } + set { + Exceptions.ThrowOnNull (value, "value"); + typeSpec = value; + typeName = value.ToString (); + } + } + public bool IsInOut { get; set; } + + #region IXElementConvertible implementation + + public XElement ToXElement () + { + return new XElement ("parameter", + new XAttribute ("publicName", PublicName), + new XAttribute ("privateName", PrivateName), + new XAttribute ("type", TypeName), + new XAttribute ("isVariadic", IsVariadic) + ); + } + + #endregion + + public static List> ParameterListListFromXElement (TypeAliasFolder folder, XElement elem) + { + var plists = from plelem in elem.Elements ("parameterlist") + orderby (int)plelem.Attribute ("index") + select ParameterListFromXElement (folder, plelem); + return plists.ToList (); + } + + public static List ParameterListFromXElement (TypeAliasFolder folder, XElement elem) + { + var indexed = from pelem in elem.Elements ("parameter") + orderby (int)pelem.Attribute ("index") + select ParameterItem.FromXElement (folder, pelem); + + return indexed.ToList (); + } + + public static ParameterItem FromXElement (TypeAliasFolder folder, XElement elem) + { + ParameterItem pi = new ParameterItem { + PublicName = (string)elem.Attribute ("publicName"), + PrivateName = (string)elem.Attribute ("privateName"), + TypeName = (string)elem.Attribute ("type"), + IsVariadic = elem.BoolAttribute ("isVariadic"), + }; + pi.IsInOut = pi.TypeSpec.IsInOut; + pi.TypeSpec = folder.FoldAlias (null, pi.TypeSpec); + return pi; + } + + public bool EqualsIgnoreName (ParameterItem other) + { + if (other == null) + return false; + return IsVariadic == other.IsVariadic && this.TypeSpec.Equals (other.TypeSpec); + } + + public bool EqualsIgnoreNamesPartialMatch (ParameterItem other) + { + if (other == null) + return false; + return this.TypeSpec.EqualsPartialMatch (other.TypeSpec); + } + + public static bool AreEqualIgnoreNames (IList pl1, IList pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) { + if (!pl1 [i].EqualsIgnoreName (pl2 [i])) + return false; + } + return true; + } + + public static bool AreEqualIgnoreNamesReferencesInvariant (FunctionDeclaration fn1, IList pl1, + FunctionDeclaration fn2, IList pl2, bool matchPartialNames) + { + if (pl1.Count != pl2.Count) { + return false; + } + + for (int i = 0; i < pl1.Count; i++) { + var p1 = SubstituteSelfFromParent (fn1, pl1 [i]); + var p2 = SubstituteSelfFromParent (fn2, pl2 [i]); + p1 = RecastAsReference (p1); + p2 = RecastAsReference (p2); + + + // Names invariant means TYPE names not parameter names + if (!ParameterNamesMatch (p1, p2)) { + // we give a pass on matching "self". + // this is done because "self" is a keyword in swift + // and when matching a wrapper function, we can't call + // a parameter "self" but have to call it "thisN" where + // N is either an empty string or a number. + // This is because there might be a real parameter named "this" + // and we had to rename it. + // The end result is that we can't use a "this" test, but we + // can use a "self" test. + var parmName1 = p1.NameIsRequired ? p1.PublicName : p1.PrivateName; + var parmName2 = p2.NameIsRequired ? p2.PublicName : p2.PrivateName; + if (parmName1 != "self" && parmName2 != "self") + return false; + } + if (fn1.IsTypeSpecGeneric (p1)) { + if (!fn2.IsTypeSpecGeneric (p2)) + return false; + continue; + } + if (!p1.EqualsIgnoreName (p2)) { + if (matchPartialNames) { + if (!p1.EqualsIgnoreNamesPartialMatch (p2)) + return false; + } else { + return false; + } + } + } + return true; + } + + static ParameterItem SubstituteSelfFromParent (FunctionDeclaration func, ParameterItem p) + { + if (func.Parent == null || !p.TypeSpec.HasDynamicSelf) + return p; + p = new ParameterItem (p); + p.TypeSpec = p.TypeSpec.ReplaceName ("Self", func.Parent.ToFullyQualifiedNameWithGenerics ()); + return p; + } + + static ParameterItem RecastAsReference (ParameterItem p) + { + if (p.IsInOut) { + if (!p.TypeSpec.IsInOut) + p.TypeSpec.IsInOut = true; + return p; + } + if (p.TypeSpec is NamedTypeSpec && p.TypeSpec.ContainsGenericParameters) { + NamedTypeSpec named = (NamedTypeSpec)p.TypeSpec; + // special case - turn UnsafePointer into inout T for matching purposes + if (named.Name == "Swift.UnsafePointer" || named.Name == "Swift.UnsafeMutablePointer") { + p = new ParameterItem (p); + p.TypeSpec = p.TypeSpec.GenericParameters [0]; + p.IsInOut = true; + p.TypeSpec.IsInOut = true; + } + } + return p; + } + + static bool ParameterNamesMatch (ParameterItem p1, ParameterItem p2) + { + // parameters are considered matching if and only if their public names match. + // The following are all DISTINCT + // public func foo (a b: Int) { } + // public func foo (c b: Int) { } + // public func foo (b: Int) { } - the public name is b + // public func foo (_ b: Int) { } - the public name is null or empty + + return p1.PublicName == p2.PublicName; + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs new file mode 100644 index 000000000000..0c0224659dd8 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Xml.Linq; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class PropertyDeclaration : Member { + public PropertyDeclaration () + { + } + + public PropertyDeclaration (PropertyDeclaration other) + : base (other) + { + TypeName = other.TypeName; + Storage = other.Storage; + IsStatic = other.IsStatic; + IsLet = other.IsLet; + IsDeprecated = other.IsDeprecated; + IsUnavailable = other.IsUnavailable; + IsOptional = other.IsOptional; + } + + string typeName; + public string TypeName { + get { + return typeName; + } + set { + typeName = Exceptions.ThrowOnNull (value, nameof(value)); + try { + TypeSpec = TypeSpecParser.Parse (typeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 3, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + public TypeSpec TypeSpec { get; private set; } + public StorageKind Storage { get; set; } + public bool IsStatic { get; set; } + public bool IsLet { get; set; } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsOptional { get; set; } + public bool IsAsync { + get { + var getter = GetGetter (); + return getter == null ? false : getter.IsAsync; + } + } + + public FunctionDeclaration GetGetter () + { + return SearchForPropertyAccessor (FunctionDeclaration.kPropertyGetterPrefix); + } + + public FunctionDeclaration GetSetter () + { + return SearchForPropertyAccessor (FunctionDeclaration.kPropertySetterPrefix); + } + + + FunctionDeclaration SearchForPropertyAccessor (string prefix) + { + var funcs = GetFunctionsToSearch (); + return funcs.FirstOrDefault (f => f.IsProperty && + f.IsStatic == IsStatic && + f.Name.StartsWith (prefix, StringComparison.Ordinal) && + (f.Name.Length == prefix.Length + Name.Length) && + string.CompareOrdinal (f.Name, prefix.Length, Name, 0, Name.Length) == 0); + } + + IEnumerable GetFunctionsToSearch () + { + if (Parent == null) { + return Module.Functions; + } else { + TypeDeclaration parent = Parent as TypeDeclaration; + if (parent == null) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 4, $"Expected property parent to be a TypeDeclaration, but was a {Parent.GetType ().Name}"); + } + return parent.Members.OfType (); + } + } + + public static PropertyDeclaration PropFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + var property = new PropertyDeclaration { + Name = (string)elem.Attribute ("name"), + Module = module, + Parent = parent, + Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")), + TypeName = (string)elem.Attribute ("type"), + Storage = StorageKindFromString ((string)elem.Attribute ("storage")), + IsStatic = elem.BoolAttribute ("isStatic"), + IsLet = elem.BoolAttribute ("isLet"), + IsDeprecated = elem.BoolAttribute("isDeprecated"), + IsUnavailable = elem.BoolAttribute("isUnavailable"), + IsOptional = elem.BoolAttribute("isOptional") + + }; + + property.TypeSpec = folder.FoldAlias (parent, property.TypeSpec); + + return property; + } + + protected override XElement MakeXElement () + { + return new XElement ("property", + new XAttribute ("name", Name), + new XAttribute ("accessibility", Access), + new XAttribute ("type", TypeName), + new XAttribute ("storage", Storage), + new XAttribute ("isStatic", IsStatic), + new XAttribute ("isLet", IsLet), + new XAttribute ("isDeprecated", IsDeprecated), + new XAttribute ("isUnavailable", IsUnavailable), + new XAttribute ("isOptional", IsOptional) + ); + } + + public static StorageKind StorageKindFromString (string value) + { + if (value == null) + return StorageKind.Unknown; + StorageKind storage; + Enum.TryParse (value, out storage); + return storage; + } + + public override string ToString () + { + // Forms: + // access [modfiers] var Name: Type { [get | set] } [throws] + // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] + // access [modifiers] Name(args) -> Type [throws] + + var getter = GetGetter (); + var builder = new StringBuilder (); + builder.Append (Access).Append (" "); + if (IsStatic) + builder.Append ("static "); + if (getter.IsSubscript) { + builder.Append ("subscript ").Append (base.ToString ()); + builder.Append (" [").Append (getter.ParametersToString ()).Append ("]:"); + } else { + builder.Append ("var ").Append (Parent.ToString ()).Append (".").Append (getter.PropertyName); + builder.Append (": "); + } + + builder.Append (getter.ReturnTypeName); + if (GetSetter () != null) { + builder.Append (" { get set }"); + } else { + builder.Append (" { get }"); + } + if (getter.HasThrows) { + builder.Append (" throws"); + } + return builder.ToString (); + } + + public override bool HasDynamicSelf => this.TypeSpec.HasDynamicSelf; + public override bool HasDynamicSelfInReturnOnly => false; + public override bool HasDynamicSelfInArguments => HasDynamicSelf; + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs new file mode 100644 index 000000000000..da245914af25 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; + +namespace SwiftReflector.SwiftXmlReflection { + public class ProtocolDeclaration : ClassDeclaration { + public ProtocolDeclaration () + { + Kind = TypeKind.Protocol; + AssociatedTypes = new List (); + } + + protected override TypeDeclaration UnrootedFactory () + { + return new ProtocolDeclaration (); + } + + protected override void GatherXObjects (List xobjects) + { + base.GatherXObjects (xobjects); + if (AssociatedTypes.Count <= 0) + return; + var assocTypes = new List (); + foreach (var assoc in AssociatedTypes) { + var contents = new List (); + assoc.GatherXObjects (contents); + assocTypes.Add (new XElement ("associatedtype", contents.ToArray ())); + } + xobjects.Add (new XElement ("associatedtypes", assocTypes.ToArray ())); + } + + protected override void CompleteUnrooting (TypeDeclaration unrooted) + { + base.CompleteUnrooting (unrooted); + if (unrooted is ProtocolDeclaration pd) { + pd.AssociatedTypes.AddRange (AssociatedTypes); + } + } + + public List AssociatedTypes { get; private set; } + + public bool HasAssociatedTypes => AssociatedTypes.Count > 0; + + public AssociatedTypeDeclaration AssociatedTypeNamed (string name) + { + return AssociatedTypes.FirstOrDefault (at => at.Name == name); + } + + public bool HasDynamicSelf { + // you shouldn't cache this. This type is mutable, so that would be bad + get => Members.Any (m => m.HasDynamicSelf); + } + + public bool HasDynamicSelfInReturnOnly { + get => Members.Any (m => m.HasDynamicSelfInReturnOnly) && !HasDynamicSelfInArguments; + } + + public bool HasDynamicSelfInArguments { + get => Members.Any (m => m.HasDynamicSelfInArguments); + } + + public bool IsExistential { + get => !(HasAssociatedTypes || HasDynamicSelfInArguments); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/Reflector.cs b/src/SwiftReflector/SwiftXmlReflection/Reflector.cs new file mode 100644 index 000000000000..c1ee002a214b --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/Reflector.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Xml.Linq; +using System.Collections.Generic; +using SwiftReflector.ExceptionTools; +using System.IO; +using SwiftReflector.IOUtils; +using System.Diagnostics; +using System.Text; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftXmlReflection { + public class Reflector { + public const double kCurrentVersion = 1.0; + const double kNextMajorVersion = 2.0; + + public static List FromXml (XDocument doc, TypeDatabase typeDatabase) + { + var xamreflect = doc.Element ("xamreflect"); + var version = xamreflect.DoubleAttribute ("version"); + + if (version < kCurrentVersion || version >= kNextMajorVersion) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 5, $"Unsupported xamreflect version {version}. Current is {kCurrentVersion}"); + } + + try { + List modules = (from module in xamreflect.Descendants ("module") + select ModuleDeclaration.FromXElement (module, typeDatabase)).ToList (); + return modules; + } catch (Exception e) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 6, $"Error while reading XML reflection information: {e.Message}"); + } + } + + public static List FromXml (Stream stm, TypeDatabase typeDatabase) + { + var doc = XDocument.Load (stm); + return FromXml (doc, typeDatabase); + } + + public static List FromXmlFile (string path, TypeDatabase typeDatabase) + { + try { + using (FileStream stm = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)) { + return FromXml (stm, typeDatabase); + } + } catch (Exception e) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 10, e, $"Failed to load xml file '{path}': {e.Message}"); + } + } + + public static List FromXml (string xmlText, TypeDatabase typeDatabase) + { + using (StringReader reader = new StringReader (xmlText)) { + var doc = XDocument.Load (reader); + return FromXml (doc, typeDatabase); + } + } + + public static List FromModules (string executablePath, List searchDirectories, List modules, + IFileProvider provider, string outfileName, out string fullOutputPath) + { + fullOutputPath = PathToXmlFromModules (executablePath, searchDirectories, modules, provider, outfileName); + return FromXmlFile (fullOutputPath, null); + } + + public static string PathToXmlFromModules (string executablePath, List searchDirectories, List modules, + IFileProvider provider, string outfileName) + { + string fullOutputPath = provider.ProvideFileFor (outfileName); + try { + return PathToXmlFromModules (executablePath, searchDirectories, modules, fullOutputPath); + } finally { + provider.NotifyFileDone (outfileName, fullOutputPath); + } + } + + // returns the path to the output XML file + public static string PathToXmlFromModules (string executablePath, List searchDirectories, List modules, + string outfilePath) + { + var args = BuildArgs (searchDirectories, modules, outfilePath); + ExecAndCollect.Run (executablePath, args); + return outfilePath; + } + + static string BuildArgs (List searchDirectories, List modules, string outfilePath) + { + StringBuilder sb = new StringBuilder (); + + // -xamreflect [-I dir]* -o outfilePath module1 [module2 ...] + + sb.Append ("-xamreflect "); + + foreach (string s in searchDirectories) { + sb.Append ("-I "); + sb.Append (QuoteIfNeeded (s)); + } + if (sb.Length > 0) + sb.Append (" "); + sb.Append ("-o ").Append (QuoteIfNeeded (outfilePath)); + sb.Append (" "); + foreach (string s in modules) { + sb.Append (QuoteIfNeeded (s)); + } + return sb.ToString (); + } + + static string QuoteIfNeeded (string s) + { + throw new NotImplementedException (); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs new file mode 100644 index 000000000000..e3f880e012f6 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.ExceptionTools; + +namespace SwiftReflector.SwiftXmlReflection { + public class ShamDeclaration : TypeDeclaration { + public ShamDeclaration (string fullName, EntityType type) + { + fullUnrootedName = fullName; + Tuple modName = fullName.SplitModuleFromName (); + unrootedName = modName.Item2; + IsUnrooted = true; + TypeKind kind = TypeKind.Unknown; + switch (type) { + case EntityType.Scalar: + kind = TypeKind.Struct; + break; + case EntityType.Class: + kind = TypeKind.Class; + break; + case EntityType.Struct: + kind = TypeKind.Struct; + break; + case EntityType.Enum: + case EntityType.TrivialEnum: + kind = TypeKind.Enum; + break; + default: + break; + } + Kind = kind; + Module = new ModuleDeclaration (); + Module.Name = modName.Item1; + } + + protected override void GatherXObjects (System.Collections.Generic.List xobjects) + { + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 1, $"Attempt to serialize a sham type for {this.ToFullyQualifiedName (true)}. Likely this type was never fully realized."); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs new file mode 100644 index 000000000000..3dcd1173b061 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SwiftReflector.SwiftXmlReflection { + public class StructDeclaration : TypeDeclaration { + public StructDeclaration () + { + Kind = TypeKind.Struct; + } + + protected override TypeDeclaration UnrootedFactory () + { + return new StructDeclaration (); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs new file mode 100644 index 000000000000..bd5a73b3c68f --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace SwiftReflector.SwiftXmlReflection { + // this is a pseudo class. + public class SubscriptDeclaration { + public SubscriptDeclaration (FunctionDeclaration getter, FunctionDeclaration setter, FunctionDeclaration materializer) + { + Getter = getter; + Setter = setter; + Materializer = materializer; + } + + public FunctionDeclaration Getter { get; set; } + public FunctionDeclaration Setter { get; set; } + public FunctionDeclaration Materializer { get; set; } + public bool IsAsync => Getter.IsAsync; + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs new file mode 100644 index 000000000000..521afacadfe5 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Xml.Linq; +using SyntaxDynamo; +using SwiftReflector.ExceptionTools; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeAliasDeclaration { + public TypeAliasDeclaration () + { + } + + public Accessibility Access { get; private set; } + + string typeName; + public string TypeName { + get { return typeName; } + set { + typeName = Exceptions.ThrowOnNull (value, nameof (value)); + if (typeName.IndexOf (':') >= 0) + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 12, $"typealias {value} has a generic constraint which is not supported"); + try { + typeSpec = TypeSpecParser.Parse (typeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias name '{value}': {ex.Message}"); + } + } + } + + TypeSpec typeSpec; + public TypeSpec TypeSpec { + get { return typeSpec; } + set { + Exceptions.ThrowOnNull (value, nameof (value)); + typeSpec = value; + typeName = value.ToString (); + } + } + + string targetTypeName; + public string TargetTypeName { + get { return targetTypeName; } + set { + targetTypeName = Exceptions.ThrowOnNull (value, nameof (value)); + try { + targetTypeSpec = TypeSpecParser.Parse (targetTypeName); + } catch (RuntimeException ex) { + throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias target name '{value}': {ex.Message}"); + } + } + } + + TypeSpec targetTypeSpec; + public TypeSpec TargetTypeSpec { + get { return targetTypeSpec; } + set { + Exceptions.ThrowOnNull (value, nameof (value)); + targetTypeSpec = value; + targetTypeName = value.ToString (); + } + } + + public String ModuleName { + get { + var spec = TypeSpec as NamedTypeSpec; + return spec?.Module; + } + } + + public XElement ToXElement () + { + return new XElement ("typealias", new XAttribute ("name", TypeName), + new XAttribute ("type", TargetTypeName)); + } + + public static TypeAliasDeclaration FromXElement (string moduleName, XElement element) + { + var aliasName = element.Attribute ("name").Value; + if (!aliasName.Contains (".")) { + Exceptions.ThrowOnNull (moduleName, nameof (moduleName)); + aliasName = $"{moduleName}.{aliasName}"; + } + return new TypeAliasDeclaration () { + Access = TypeDeclaration.AccessibilityFromString ((string)element.Attribute ("accessibility")), + TypeName = aliasName, + TargetTypeName = element.Attribute ("type").Value + }; + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs b/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs new file mode 100644 index 000000000000..8985e7b5fe31 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs @@ -0,0 +1,259 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeAliasFolder { + Dictionary aliases; + + public TypeAliasFolder (IList aliases) + { + this.aliases = new Dictionary (); + foreach (var alias in aliases) { + this.aliases.Add (AliasKey (alias.TypeSpec), alias); + } + } + + public void AddDatabaseAliases (TypeDatabase typeDatabase) + { + if (typeDatabase == null) + return; + foreach (var moduleName in typeDatabase.ModuleNames) { + var moduleDB = typeDatabase.ModuleDatabaseForModuleName (moduleName); + foreach (var alias in moduleDB.TypeAliases) { + this.aliases.Add (AliasKey (alias.TypeSpec), alias); + } + } + } + + public TypeSpec FoldAlias (BaseDeclaration context, TypeSpec original) + { + if (aliases.Count == 0) + return original; + + var changed = false; + while (true) { + original = FoldAlias (context, original, out changed); + if (!changed) + return original; + } + } + + TypeSpec FoldAlias (BaseDeclaration context, TypeSpec spec, out bool changed) + { + switch (spec.Kind) { + case TypeSpecKind.Named: + return FoldAlias (context, spec as NamedTypeSpec, out changed); + case TypeSpecKind.Closure: + return FoldAlias (context, spec as ClosureTypeSpec, out changed); + case TypeSpecKind.ProtocolList: + return FoldAlias (context, spec as ProtocolListTypeSpec, out changed); + case TypeSpecKind.Tuple: + return FoldAlias (context, spec as TupleTypeSpec, out changed); + default: + throw new ArgumentOutOfRangeException (nameof (spec)); + } + + } + + TypeSpec FoldAlias (BaseDeclaration context, TupleTypeSpec spec, out bool changed) + { + changed = false; + TypeSpec [] newContents = spec.Elements.ToArray (); + for (int i = 0; i < newContents.Length; i++) { + var elemChanged = false; + newContents [i] = FoldAlias (context, newContents [i], out elemChanged); + changed = changed || elemChanged; + } + if (changed) { + var newTuple = new TupleTypeSpec (newContents); + newTuple.Attributes.AddRange (spec.Attributes); + return newTuple; + } + return spec; + } + + TypeSpec FoldAlias (BaseDeclaration context, ClosureTypeSpec spec, out bool changed) + { + var returnChanged = false; + var returnSpec = FoldAlias (context, spec.ReturnType, out returnChanged); + + var argsChanged = false; + var args = FoldAlias (context, spec.Arguments, out argsChanged); + + changed = returnChanged || argsChanged; + if (changed) { + var newSpec = new ClosureTypeSpec (args, returnSpec); + newSpec.Attributes.AddRange (spec.Attributes); + return newSpec; + } + return spec; + } + + TypeSpec FoldAlias (BaseDeclaration context, ProtocolListTypeSpec spec, out bool changed) + { + changed = false; + var protos = new NamedTypeSpec [spec.Protocols.Count]; + + var protoChanged = false; + var i = 0; + foreach (var proto in spec.Protocols.Keys) { + protos [i] = FoldAlias (context, proto, out protoChanged) as NamedTypeSpec; + changed = changed || protoChanged; + } + if (changed) { + var newProtoList = new ProtocolListTypeSpec (protos); + newProtoList.Attributes.AddRange (spec.Attributes); + return newProtoList; + } + return spec; + } + + TypeSpec FoldAlias (BaseDeclaration context, NamedTypeSpec spec, out bool changed) + { + if (context == null || !context.IsTypeSpecGenericReference (spec)) { + TypeAliasDeclaration decl = null; + if (aliases.TryGetValue (spec.Name, out decl)) { + changed = true; + var newNamedSpec = RemapAliasedTypeSpec (spec, decl); + newNamedSpec.Attributes.AddRange (spec.Attributes); + return newNamedSpec; + } else { + return FoldGenerics (context, spec, out changed); + } + } else { + return FoldGenerics (context, spec, out changed); + } + } + + TypeSpec FoldGenerics (BaseDeclaration context, NamedTypeSpec spec, out bool changed) + { + changed = false; + if (!spec.ContainsGenericParameters) + return spec; + var genericsChanged = false; + var newGenerics = spec.GenericParameters.ToArray (); + for (int i = 0; i < newGenerics.Length; i++) { + var genericChanged = false; + newGenerics [i] = FoldAlias (context, newGenerics [i], out genericChanged); + genericsChanged = genericsChanged || genericChanged; + } + if (genericsChanged) { + changed = true; + var newNamedSpec = new NamedTypeSpec (spec.Name, newGenerics); + newNamedSpec.Attributes.AddRange (spec.Attributes); + return newNamedSpec; + } + return spec; + } + + TypeSpec RemapAliasedTypeSpec (NamedTypeSpec source, TypeAliasDeclaration decl) + { + // OK - in the Decl, we're going to have something like: + // Name = SomeOtherType + // or we'll have + // Name = SomeOtherType + // The first case is easy. In the second case we need to look + // at the t1 and find out where it comes from in Name<...> + // and remap it using what was provided in the source. + // But of course this get complicated. + // You could have something like this: + // typealias Foo = UnsafeMutablePointer<(Int, T)> + // So we need a map from each generic argument in Foo to + // each generic argument in source. + // Then we need to build a new TypeSpec using the declaration's target + // type substituting in elements from the map. + // and it gets more complicated because the thing we're looking at may + // be an associated type. + // + // Here's an example: + //public protocol KVPish + //{ + // associatedtype Key : Hashable + // associatedtype Value + // func contains(a: Key) -> Bool + // func get(a: Key) -> Value + //} + // + //public typealias KPHolder = Dictionary + var genericMap = new Dictionary (); + if (decl.TypeSpec.ContainsGenericParameters) { + for (int i = 0; i < decl.TypeSpec.GenericParameters.Count; i++) { + // the "parts" here are part of a formal generic declaration + // and they HAVE to be named type specs and they themselves + // won't ever be generic. They're going to just be a name. + // Future Steve: trust me. + var part = decl.TypeSpec.GenericParameters [i] as NamedTypeSpec; + genericMap.Add (part.Name, source.GenericParameters [i]); + } + } + return RemapTypeSpec (decl.TargetTypeSpec, genericMap); + } + + TypeSpec RemapTypeSpec (TypeSpec spec, Dictionary nameMap) + { + switch (spec.Kind) { + case TypeSpecKind.Closure: + return RemapTypeSpec (spec as ClosureTypeSpec, nameMap); + case TypeSpecKind.Named: + return RemapTypeSpec (spec as NamedTypeSpec, nameMap); + case TypeSpecKind.ProtocolList: + return RemapTypeSpec (spec as ProtocolListTypeSpec, nameMap); + case TypeSpecKind.Tuple: + return RemapTypeSpec (spec as TupleTypeSpec, nameMap); + default: + throw new NotImplementedException ($"Unknown type spec kind {spec.Kind}"); + } + } + + TypeSpec RemapTypeSpec (TupleTypeSpec tuple, Dictionary nameMap) + { + var tupleElems = tuple.Elements.ToArray (); + for (int i = 0; i < tupleElems.Length; i++) { + tupleElems [i] = RemapTypeSpec (tupleElems [i], nameMap); + } + return new TupleTypeSpec (tupleElems); + } + + TypeSpec RemapTypeSpec (ClosureTypeSpec clos, Dictionary nameMap) + { + var returnType = RemapTypeSpec (clos.ReturnType, nameMap); + var args = RemapTypeSpec (clos.Arguments, nameMap); + return new ClosureTypeSpec (args, returnType); + } + + TypeSpec RemapTypeSpec (ProtocolListTypeSpec proto, Dictionary nameMap) + { + return new ProtocolListTypeSpec (proto.Protocols.Keys.Select (k => RemapTypeSpec (k, nameMap) as NamedTypeSpec)); + } + + TypeSpec RemapTypeSpec (NamedTypeSpec named, Dictionary nameMap) + { + var parts = named.Name.Split ('.'); + for (int i = 0; i < parts.Length; i++) { + TypeSpec replacement; + if (nameMap.TryGetValue (parts [i], out replacement)) { + parts [i] = replacement.ToString (); + } + } + var newName = parts.InterleaveStrings ("."); + if (named.ContainsGenericParameters) { + var newParams = named.GenericParameters.Select (p => RemapTypeSpec (p, nameMap)).ToArray (); + return new NamedTypeSpec (newName, newParams); + } else { + return new NamedTypeSpec (newName); + } + } + + static string AliasKey (TypeSpec spec) + { + if (spec is NamedTypeSpec named) + return named.Name; + return spec.ToString (); + } + } +} diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs new file mode 100644 index 000000000000..092da842bf24 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs @@ -0,0 +1,538 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.IOUtils; +using SwiftReflector.ExceptionTools; +using SwiftReflector.Demangling; +using SwiftReflector.TypeMapping; +using System.Text; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeDeclaration : BaseDeclaration, IXElementConvertible { + public TypeDeclaration () + : base () + { + Kind = TypeKind.Unknown; + InnerClasses = new List (); + InnerStructs = new List (); + InnerEnums = new List (); + Members = new List (); + Inheritance = new List (); + TypeAliases = new List (); + } + + public TypeKind Kind { get; set; } + public List Inheritance { get; set; } + public List Members { get; set; } + public List InnerClasses { get; set; } + public List InnerStructs { get; set; } + public List InnerEnums { get; set; } + public List TypeAliases { get; set; } + public bool IsObjC { get; set; } + public bool IsFinal { get; set; } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsUnrooted { get; protected set; } + + public TypeDeclaration MakeUnrooted () + { + if (IsUnrooted) + return this; + + TypeDeclaration unrooted = UnrootedFactory (); + unrooted.unrootedName = ToFullyQualifiedName (false); + unrooted.fullUnrootedName = ToFullyQualifiedName (true); + unrooted.Kind = Kind; + unrooted.Inheritance.AddRange (Inheritance); + unrooted.Members.AddRange (Members); + unrooted.IsObjC = IsObjC; + unrooted.IsFinal = IsFinal; + unrooted.IsUnrooted = true; + unrooted.Name = Name; + unrooted.Access = Access; + unrooted.Module = Module.MakeUnrooted (); + unrooted.Generics.AddRange (Generics); + CompleteUnrooting (unrooted); + return unrooted; + } + + protected virtual TypeDeclaration UnrootedFactory () + { + throw new NotImplementedException (); + } + + public bool IsObjCOrInheritsObjC (TypeMapper typeMapper) + { + if (IsObjC) + return true; + if (Inheritance == null || Inheritance.Count == 0) + return false; + foreach (var inheritance in Inheritance) { + if (inheritance.InheritanceKind != InheritanceKind.Class) + continue; + var entity = typeMapper.GetEntityForTypeSpec (inheritance.InheritedTypeSpec); + if (entity == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 4, $"Unable to find entity for class inheritance type {inheritance.InheritedTypeName}"); + return entity.Type.IsObjC || entity.Type.IsObjCOrInheritsObjC (typeMapper); + } + return false; + } + + public bool IsSwiftBaseClass () + { + // this predicate determines if a TypeDeclaration is: + // * a ClassDeclaration + // * an all swift object + // * no inheritance or any inheritance is not class inheritance + if (!(this is ClassDeclaration)) + return false; + if (IsObjC) + return false; + return Inheritance == null || !Inheritance.Any (inh => inh.InheritanceKind == InheritanceKind.Class); + } + + public bool ProtectedObjCCtorIsInThis (TypeMapper typeMapper) + { + // this predicate determines if this type has a protected objc ctor in this. + // it's used to determine if, when writing the C# binding, if we need to call base () or this () + var classDecl = this as ClassDeclaration; + if (classDecl == null) + return false; + if (!IsObjC) + return false; + // no inheritance + // this : (nothing) -> IsImportedBinding + if (Inheritance == null || Inheritance.FirstOrDefault (inh => inh.InheritanceKind == InheritanceKind.Class) == null) { + // if there's no inheritance, then the protected ctor is in this if it wasn't imported + return !classDecl.IsImportedBinding; + } + // this : import -> true + // this : binding : binding : import -> false + var classInherit = Inheritance.First (inh => inh.InheritanceKind == InheritanceKind.Class); + var entity = typeMapper.GetEntityForTypeSpec (classInherit.InheritedTypeSpec); + if (entity == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 9, $"Unable to find entity for class inheritance on type {classInherit.InheritedTypeName}"); + var inheritedClass = entity.Type as ClassDeclaration; + if (inheritedClass == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 10, $"Expected a ClassDeclaration in inheritance chain but got {entity.Type.ToFullyQualifiedName (true)} of {entity.Type.GetType ().Name}"); + return inheritedClass.IsImportedBinding; + } + + protected virtual void CompleteUnrooting (TypeDeclaration unrooted) + { + } + + protected string unrootedName = null; + protected string fullUnrootedName = null; + public override string ToFullyQualifiedName (bool includeModule = true) + { + if (IsUnrooted) { + return includeModule ? fullUnrootedName : unrootedName; + } else { + return base.ToFullyQualifiedName (includeModule); + } + } + + #region IXElementConvertible implementation + + public XElement ToXElement () + { + if (!IsUnrooted) + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 0, "TypeDeclarations must be unrooted to create from XML."); + + var xobjects = new List (); + GatherXObjects (xobjects); + XElement typeDecl = new XElement ("typedeclaration", xobjects.ToArray ()); + return typeDecl; + } + + protected virtual void GatherXObjects (List xobjects) + { + XElement generics = Generics.ToXElement (); + if (generics != null) + xobjects.Add (generics); + xobjects.Add (new XAttribute ("kind", ToString (Kind))); + xobjects.Add (new XAttribute ("name", fullUnrootedName)); + xobjects.Add (new XAttribute ("module", Module.Name)); + xobjects.Add (new XAttribute ("accessibility", TypeDeclaration.ToString (Access))); + xobjects.Add (new XAttribute ("isObjC", IsObjC ? "true" : "false")); + xobjects.Add (new XAttribute ("isFinal", IsFinal ? "true" : "false")); + xobjects.Add (new XAttribute ("isDeprecated", IsDeprecated ? "true" : "false")); + xobjects.Add (new XAttribute ("isUnavailable", IsUnavailable ? "true" : "false")); + // DO NOT INCLUDE Inner[Classes,Structs,Enums] + List memcontents = new List (Members.Select (m => m.ToXElement ())); + xobjects.Add (new XElement ("members", memcontents.ToArray ())); + List inherits = new List (Inheritance.Select (i => i.ToXElement ())); + xobjects.Add (new XElement ("inherits", inherits.ToArray ())); + if (TypeAliases.Count > 0) { + var aliases = new List (TypeAliases.Select (a => a.ToXElement ())); + xobjects.Add (new XElement ("typealiases", aliases.ToArray ())); + } + } + + #endregion + + public static TypeDeclaration TypeFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent /* can be null */) + { + var decl = FromKind ((string)elem.Attribute ("kind")); + bool isUnrooted = elem.Attribute ("module") != null; + decl.Module = module; + decl.Parent = parent; + if (isUnrooted) { + decl.IsUnrooted = true; + decl.fullUnrootedName = (string)elem.Attribute ("name"); + decl.unrootedName = decl.fullUnrootedName.NameWithoutModule (); + decl.Name = decl.fullUnrootedName.Contains ('.') ? decl.fullUnrootedName.Substring (decl.fullUnrootedName.LastIndexOf ('.') + 1) + : decl.fullUnrootedName; + } else { + decl.Name = (string)elem.Attribute ("name"); + } + decl.Access = AccessibilityFromString ((string)elem.Attribute ("accessibility")); + decl.IsObjC = elem.BoolAttribute ("isObjC"); + decl.IsFinal = elem.BoolAttribute ("isFinal"); + decl.IsDeprecated = elem.BoolAttribute ("isDeprecated"); + decl.IsUnavailable = elem.BoolAttribute ("isUnavailable"); + + decl.InnerClasses.AddRange (InnerFoo (folder, elem, "innerclasses", module, decl)); + decl.InnerStructs.AddRange (InnerFoo (folder, elem, "innerstructs", module, decl)); + decl.InnerEnums.AddRange (InnerFoo (folder, elem, "innerenums", module, decl)); + if (elem.Element ("members") != null) { + var members = from mem in elem.Element ("members").Elements () + select Member.FromXElement (folder, mem, module, decl) as Member; + decl.Members.AddRange (members); + } + if (elem.Element ("inherits") != null) { + var inherits = from inherit in elem.Element ("inherits").Elements () + select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement (folder, inherit) as Inheritance; + decl.Inheritance.AddRange (inherits); + } + var typealiases = elem.Element ("typealiases"); + if (typealiases != null) { + var aliases = from alias in typealiases.Elements () + select TypeAliasDeclaration.FromXElement (module.Name, alias); + decl.TypeAliases.AddRange (aliases); + } + EnumDeclaration edecl = decl as EnumDeclaration; + if (edecl != null) { + var enumElements = (from enumElement in elem.Element ("elements").Elements () + select new EnumElement ((string)enumElement.Attribute ("name"), (string)enumElement.Attribute ("type"), + (long?)enumElement.Attribute ("intValue"))).ToList (); ; + edecl.Elements.AddRange (enumElements); + if (elem.Attribute ("rawType") != null) { + var rawType = TypeSpecParser.Parse ((string)elem.Attribute ("rawType")); + edecl.RawTypeName = folder.FoldAlias (parent, rawType).ToString (); + } + } + + var protoDecl = decl as ProtocolDeclaration; + if (protoDecl != null) { + if (elem.Element ("associatedtypes") != null) { + var assocElements = from assocElem in elem.Element ("associatedtypes").Elements () + select AssociatedTypeDeclaration.FromXElement (folder, assocElem); + protoDecl.AssociatedTypes.AddRange (assocElements); + } + } + + return decl; + } + + static IEnumerable InnerFoo (TypeAliasFolder folder, XElement parent, string innerName, ModuleDeclaration module, BaseDeclaration parDecl) where T : TypeDeclaration + { + var inner = parent.Elements (innerName).SelectMany (el => el.Elements ("typedeclaration")); + var innerList = inner.Select (elem => FromXElement (folder, elem, module, parDecl)).ToList (); + var innerCast = innerList.Cast ().ToList (); + return innerCast; + } + + static TypeDeclaration FromKind (string kind) + { + switch (kind) { + case "class": + return new ClassDeclaration (); + case "struct": + return new StructDeclaration (); + case "enum": + return new EnumDeclaration (); + case "protocol": + return new ProtocolDeclaration (); + default: + return new TypeDeclaration (); + } + } + + internal static string ToString (TypeKind kind) + { + switch (kind) { + case TypeKind.Class: + return "class"; + case TypeKind.Struct: + return "struct"; + case TypeKind.Enum: + return "enum"; + case TypeKind.Protocol: + return "protocol:"; + default: + throw new ArgumentOutOfRangeException (nameof (kind)); + } + } + + public static Accessibility AccessibilityFromString (string value) + { + if (value == null) + return Accessibility.Unknown; + Accessibility access; + Enum.TryParse (value, out access); + return access; + } + + internal static string ToString (Accessibility access) + { + return access.ToString (); + } + + public List AllVirtualMethods () + { + if (this is ProtocolDeclaration) { + return Members.OfType ().Where (decl => + !decl.IsConstructorOrDestructor && + (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Public)).ToList (); + } else { + return Members.OfType ().Where (decl => + !decl.IsConstructorOrDestructor && + (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Open)).ToList (); + } + } + + public List AllProperties () + { + return Members.OfType ().ToList (); + } + + public List AllVirtualProperties () + { + Accessibility requiredAccessibility; + if (this is ProtocolDeclaration) { + requiredAccessibility = Accessibility.Public; + } else { + requiredAccessibility = Accessibility.Open; + } + return Members.OfType ().Where (decl => { + if (decl.IsStatic) + return false; + if (decl.Access != requiredAccessibility) + return false; + var getter = decl.GetGetter (); + if (getter == null) + return false; + if (getter.IsDeprecated || getter.IsUnavailable) + return false; + return true; + }).ToList (); + } + + public List AllFinalMethods () + { + return Members.OfType ().Where (decl => + !decl.IsConstructorOrDestructor && decl.IsFinal).ToList (); + } + + public List AllMethodsNoCDTor () + { + return Members.OfType ().Where (decl => !decl.IsConstructorOrDestructor).ToList (); + } + + public List AllConstructors () + { + return Members.OfType ().Where (decl => decl.IsConstructor).ToList (); + } + + public List AllDestructors () + { + return Members.OfType ().Where (decl => decl.IsDestructor).ToList (); + } + + public List AllSubscripts () + { + var allSubFuncs = Members.OfType ().Where (decl => decl.IsSubscript).ToList (); + var allSubs = new List (); + while (allSubFuncs.Count > 0) { + int i = allSubFuncs.Count - 1; + FunctionDeclaration decl = allSubFuncs [i]; + allSubFuncs.RemoveAt (i); + if (decl.IsSubscriptMaterializer) + continue; + if (decl.IsSubscriptGetter) { + FunctionDeclaration setter = GetAndRemoveSetter (allSubFuncs, decl); + FunctionDeclaration materializer = GetAndRemoveMaterializer (allSubFuncs, decl); + allSubs.Add (new SubscriptDeclaration (decl, setter, materializer)); + } else if (decl.IsSubscriptSetter) { + FunctionDeclaration getter = GetAndRemoveGetter (allSubFuncs, decl); + FunctionDeclaration materializer = GetAndRemoveMaterializer (allSubFuncs, decl); + allSubs.Add (new SubscriptDeclaration (getter, decl, materializer)); + } + } + return allSubs; + } + + public TypeSpec ToTypeSpec () + { + NamedTypeSpec ns = new NamedTypeSpec (ToFullyQualifiedName ()); + ns.GenericParameters.AddRange (Generics.Select (gen => new NamedTypeSpec (gen.Name))); + return ns; + } + + static FunctionDeclaration GetAndRemoveMaterializer (List decls, FunctionDeclaration other) + { + // FIXME - materializers don't have enough to match on with 100% confidence + // Materializers are (probably) not needed by tom-swifty, so no big + return null; + } + + static FunctionDeclaration GetAndRemoveGetter (List decls, FunctionDeclaration other) + { + var plToMatch = new List (); + TypeSpec returnToMatch = null; + var selfToMatch = other.Parent; + + if (other.IsSetter) { + // setter - + // The arguments to a setter are + // value, arg1, arg2 ... argn + // We want to match the type of the return of the getter to the value of the setter + // as well as the parameters + List pl = other.ParameterLists.Last (); + plToMatch.AddRange (pl.GetRange (1, pl.Count - 1)); + returnToMatch = pl [0].TypeSpec; + } else { + // materializer. + // The arguments to a materializer are + // buffer, callbackStoragebuffer, arg1, arg2 ... argn + // We have no return to match. Oops. + List pl = other.ParameterLists.Last (); + plToMatch.AddRange (pl.GetRange (2, pl.Count - 2)); + returnToMatch = null; + } + + + for (int i = 0; i < decls.Count; i++) { + FunctionDeclaration getter = decls [i]; + if (getter.Parent != selfToMatch) + return null; + if (!getter.IsSubscriptGetter) + continue; + if ((returnToMatch != null && returnToMatch.Equals (getter.ReturnTypeSpec)) || returnToMatch == null) { + List targetPl = getter.ParameterLists.Last (); + if (ParmsMatch (plToMatch, targetPl)) { + decls.RemoveAt (i); + return getter; + } + } + } + return null; + } + + static FunctionDeclaration GetAndRemoveSetter (List decls, FunctionDeclaration other) + { + var plToMatch = new List (); + var selfToMatch = other.Parent; + + if (other.IsGetter) { + // getter - + // The arguments to a getter are + // arg1, arg2 ... argn + // We want to match the type of the return of the getter to the value of the setter + // as well as the parameters + List pl = other.ParameterLists.Last (); + ParameterItem item = new ParameterItem (); + item.PublicName = ""; + item.PrivateName = "retval"; + item.TypeSpec = other.ReturnTypeSpec; + item.TypeName = other.ReturnTypeName; + plToMatch.Add (item); + plToMatch.AddRange (pl); + } else { + // we don't have enough information to match on setter + // and since we don't use the materializer, NBD. + + // materializer. + // The arguments to a materializer are + // buffer, callbackStoragebuffer, arg1, arg2 ... argn + // We have no return to match. Oops. + return null; + } + + for (int i = 0; i < decls.Count; i++) { + FunctionDeclaration setter = decls [i]; + if (!setter.IsSubscriptGetter) + continue; + List targetPl = setter.ParameterLists.Last (); + if (ParmsMatch (plToMatch, targetPl)) { + decls.RemoveAt (i); + return setter; + } + } + return null; + } + + public bool VirtualMethodExistsInInheritedBoundType (FunctionDeclaration func, TypeMapper typeMapper) + { + // virtual methods are only in classes + if (!(this is ClassDeclaration)) + return false; + var classInheritance = Inheritance.FirstOrDefault (inh => inh.InheritanceKind == InheritanceKind.Class); + if (classInheritance == null) + return false; + + var inheritedEntity = typeMapper.GetEntityForTypeSpec (classInheritance.InheritedTypeSpec); + if (inheritedEntity == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 18, $"Unable to find type database entry for class {classInheritance.InheritedTypeName} while searching inheritance."); + + // if we get here, the Type has to be a ClassDeclaration + var inheritedClass = inheritedEntity.Type as ClassDeclaration; + + var methods = inheritedClass.AllVirtualMethods ().FindAll (fn => fn.Name == func.Name + && fn.ParameterLists.Last ().Count == func.ParameterLists.Last ().Count).ToList (); + foreach (var method in methods) { + if (ParmsMatchWithNames (method.ParameterLists.Last (), func.ParameterLists.Last ()) + && method.ReturnTypeSpec.Equals (func.ReturnTypeSpec)) + return true; + } + return inheritedClass.VirtualMethodExistsInInheritedBoundType (func, typeMapper); + } + + static bool ParmsMatchWithNames (List pl1, List pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) { + if (pl1 [i].PublicName != pl2 [i].PublicName) + return false; + if (pl1 [i].IsInOut != pl2 [i].IsInOut) + return false; + if (!pl1 [i].TypeSpec.Equals (pl2 [i].TypeSpec)) + return false; + } + return true; + } + + static bool ParmsMatch (List pl1, List pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) { + if (pl1 [i].IsInOut != pl2 [i].IsInOut) + return false; + if (!pl1 [i].TypeSpec.Equals (pl2 [i].TypeSpec)) + return false; + } + return true; + } + + + } + +} diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs new file mode 100644 index 000000000000..5ba78fc62604 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs @@ -0,0 +1,807 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; +using SwiftReflector.TypeMapping; +using System.Linq; +using System.Collections; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeSpecAttribute { + public TypeSpecAttribute (string name) + { + Name = name; + Parameters = new List (); + } + public string Name { get; set; } + public List Parameters { get; private set; } + public override string ToString () + { + StringBuilder sb = new StringBuilder (); + sb.Append ('@'); + sb.Append (Name); + if (Parameters.Count > 0) { + sb.Append ('('); + for (int i = 0; i < Parameters.Count; i++) { + if (i > 0) + sb.Append (", "); + sb.Append (Parameters [i]); + } + sb.Append (')'); + } + return sb.ToString (); + } + } + + public abstract class TypeSpec { + protected TypeSpec (TypeSpecKind kind) + { + Kind = kind; + GenericParameters = new List (); + Attributes = new List (); + } + + public TypeSpecKind Kind { get; private set; } + public List GenericParameters { get; private set; } + public bool ContainsGenericParameters { get { return GenericParameters.Count != 0; } } + public List Attributes { get; private set; } + public bool HasAttributes { get { return Attributes.Count != 0; } } + public bool IsInOut { get; set; } + public bool IsAny { get; set; } + public virtual bool IsEmptyTuple { get { return false; } } + protected abstract string LLToString (bool useFullName); + protected virtual string LLFinalStringParts () { return ""; } + protected abstract bool LLEquals (TypeSpec other, bool partialNameMatch); + public string TypeLabel { get; set; } + public bool IsArray { + get { + NamedTypeSpec ns = this as NamedTypeSpec; + return ns != null && ns.Name == "Swift.Array"; + } + } + + public bool IsBoundGeneric (BaseDeclaration context, TypeMapper mapper) + { + switch (this.Kind) { + case TypeSpecKind.Named: + NamedTypeSpec ns = (NamedTypeSpec)this; + Entity en = mapper.TryGetEntityForSwiftClassName (ns.Name); + if (en == null) { + if (context.IsTypeSpecGeneric (ns)) + return false; // unbound + } + foreach (TypeSpec genParm in GenericParameters) { + if (genParm.IsUnboundGeneric (context, mapper)) + return false; // unbound + } + return true; + case TypeSpecKind.Closure: + ClosureTypeSpec cs = (ClosureTypeSpec)this; + return cs.Arguments.IsBoundGeneric (context, mapper) && cs.ReturnType.IsBoundGeneric (context, mapper); + case TypeSpecKind.Tuple: + TupleTypeSpec ts = (TupleTypeSpec)this; + foreach (TypeSpec elem in ts.Elements) { + if (elem.IsUnboundGeneric (context, mapper)) + return false; + } + return true; + default: + throw new NotSupportedException ("unknown TypeSpecKind " + this.Kind.ToString ()); + } + } + + public bool IsUnboundGeneric (BaseDeclaration context, TypeMapper mapper) + { + switch (Kind) { + case TypeSpecKind.Named: + NamedTypeSpec ns = (NamedTypeSpec)this; + if (context.IsTypeSpecGeneric (ns.ToString ())) + return true; + foreach (TypeSpec genparm in GenericParameters) { + if (genparm.IsUnboundGeneric (context, mapper)) + return true; + } + return false; + case TypeSpecKind.Closure: + ClosureTypeSpec cs = (ClosureTypeSpec)this; + return cs.Arguments.IsUnboundGeneric (context, mapper) && cs.ReturnType.IsUnboundGeneric (context, mapper); + case TypeSpecKind.Tuple: + TupleTypeSpec ts = (TupleTypeSpec)this; + foreach (TypeSpec elem in ts.Elements) { + if (elem.IsUnboundGeneric (context, mapper)) + return true; + } + return false; + case TypeSpecKind.ProtocolList: + return false; + default: + throw new NotSupportedException ("unknown TypeSpecKind " + this.Kind.ToString ()); + } + } + + + public override bool Equals (object obj) + { + TypeSpec spec = obj as TypeSpec; + if (spec == null) + return false; + if (Kind != spec.Kind) + return false; + if (!ListEqual (GenericParameters, spec.GenericParameters, false)) + return false; + if (IsInOut != spec.IsInOut) + return false; + // Don't compare IsAny - it's really not important (yet) + return LLEquals (spec, false); + } + + public bool EqualsPartialMatch (TypeSpec spec) + { + if (spec == null) + return false; + if (Kind != spec.Kind) + return false; + if (!ListEqual (GenericParameters, spec.GenericParameters, true)) + return false; + if (IsInOut != spec.IsInOut) + return false; + // Don't compare IsAny - it's really not important (yet) + return LLEquals (spec, true); + } + + public virtual bool EqualsReferenceInvaraint (TypeSpec type) + { + var a = ProjectAsNonReference (this); + var b = ProjectAsNonReference (type); + + if (b.Kind != a.Kind) + return false; + if (b.GetType () != a.GetType ()) + return false; + // shouldn't do Name equality except in functions + return a.LLEquals (b, false); + } + + public TypeSpec NonReferenceCloneOf () + { + if (!IsInOut) + return this; + var ty = MemberwiseClone () as TypeSpec; + ty.IsInOut = false; + return ty; + } + + static TypeSpec ProjectAsNonReference (TypeSpec a) + { + if (a.IsInOut) { + return a.NonReferenceCloneOf (); + } + var namedType = a as NamedTypeSpec; + if (namedType != null && namedType.GenericParameters.Count == 1) { + if (namedType.Name == "Swift.UnsafePointer" || namedType.Name == "Swift.UnsafeMutablePointer") + return namedType.GenericParameters [0]; + } + return a; + } + + + public override int GetHashCode () + { + return ToString ().GetHashCode (); + } + + protected static bool ListEqual (List one, List two, bool partialNameMatch) + { + if (one.Count != two.Count) + return false; + for (int i = 0; i < one.Count; i++) { + if (partialNameMatch) { + if (!one [i].EqualsPartialMatch (two [i])) + return false; + } else { + if (!one [i].Equals (two [i])) + return false; + } + } + return true; + } + + public static bool IsNullOrEmptyTuple (TypeSpec spec) + { + return spec == null || spec.IsEmptyTuple; + } + + public static bool BothNullOrEqual (TypeSpec one, TypeSpec two) + { + if (one == null && two == null) + return true; + if (one == null || two == null) + return false; + return one.Equals (two); + } + + public bool ContainsBoundGenericClosure () + { + return ContainsBoundGenericClosure (0); + } + + bool ContainsBoundGenericClosure (int depth) + { + if (this is NamedTypeSpec namedTypeSpec) { + foreach (var subSpec in namedTypeSpec.GenericParameters) { + if (subSpec.ContainsBoundGenericClosure (depth + 1)) + return true; + } + } else if (this is TupleTypeSpec tupleSpec) { + foreach (var subSpec in tupleSpec.Elements) { + if (subSpec.ContainsBoundGenericClosure (depth + 1)) + return true; + } + } else if (this is ClosureTypeSpec closureSpec) { + return depth > 0; + } + return false; + } + + public override string ToString () + { + return ToString (true); + } + + public string ToString (bool useFullNames) + { + StringBuilder builder = new StringBuilder (); + + foreach (var attr in Attributes) { + builder.Append (attr.ToString ()); + builder.Append (' '); + } + if (IsInOut) + builder.Append ("inout "); + + if (IsAny) + builder.Append ("any "); + + if (TypeLabel != null) { + builder.Append (TypeLabel).Append (": "); + } + builder.Append (LLToString (useFullNames)); + + if (ContainsGenericParameters) { + builder.Append ('<'); + for (int i = 0; i < GenericParameters.Count; i++) { + if (i > 0) + builder.Append (", "); + builder.Append (GenericParameters [i].ToString (useFullNames)); + } + builder.Append ('>'); + } + builder.Append (LLFinalStringParts ()); + + return builder.ToString (); + } + + static string [] intNames = { + "Swift.Int", "Swift.UInt", "Swift.Int8", "Swift.UInt8", + "Swift.Int16", "Swift.UInt16", "Swift.Int32", "Swift.UInt32", + "Swift.Int64", "Swift.UInt64", "Swift.Char" + }; + + public static bool IsIntegral (TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return Array.IndexOf (intNames, named.Name) >= 0; + } + + public static bool IsFloatingPoint (TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return named.Name == "Swift.Float" || named.Name == "Swift.Double" || named.Name == "CoreGraphics.CGFloat"; + } + + public static bool IsBoolean (TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return named.Name == "Swift.Bool"; + } + + public static bool IsBuiltInValueType (TypeSpec ts) + { + return IsIntegral (ts) || IsFloatingPoint (ts) || IsBoolean (ts); + } + + public TypeSpec WithInOutSet () + { + var theSpec = TypeSpecParser.Parse (this.ToString ()); + theSpec.IsInOut = true; + return theSpec; + } + + public bool IsDynamicSelf { + get { + return this is NamedTypeSpec ns && ns.Name == "Self"; + } + } + + public abstract bool HasDynamicSelf { + get; + } + + public static bool AnyHasDynamicSelf (List types) + { + return types.Any (t => t.HasDynamicSelf); + } + + public TypeSpec ReplaceName (string toFind, string replacement) + { + var result = this; + if (!String.IsNullOrEmpty (replacement)) + ReplaceName (this, toFind, replacement, ref result); + return result; + } + + static bool ReplaceName (TypeSpec original, string toFind, string replacement, ref TypeSpec result) + { + result = original; + var changed = false; + switch (original.Kind) { + case TypeSpecKind.Named: + changed = ReplaceName (original as NamedTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.ProtocolList: + changed = ReplaceName (original as ProtocolListTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.Closure: + changed = ReplaceName (original as ClosureTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.Tuple: + changed = ReplaceName (original as TupleTypeSpec, toFind, replacement, ref result); + break; + default: + throw new ArgumentOutOfRangeException ($"Unknown TypeSpec kind {original.Kind}"); + } + if (changed) { + result.Attributes.AddRange (original.Attributes); + result.TypeLabel = original.TypeLabel; + result.IsInOut = original.IsInOut; + result.IsAny = original.IsAny; + } + return changed; + } + + static bool ReplaceName (NamedTypeSpec named, string toFind, string replacement, ref TypeSpec result) + { + result = named; + var changed = false; + if (named.Name == toFind) { + changed = true; + result = new NamedTypeSpec (replacement); + } + var resultGenerics = new List (named.GenericParameters.Count); + var changedGenerics = ReplaceName (named.GenericParameters, toFind, replacement, resultGenerics); + + if (changedGenerics) { + if (!changed) { + result = new NamedTypeSpec (named.Name); + } + result.GenericParameters.AddRange (resultGenerics); + } else { + if (changed) + result.GenericParameters.AddRange (named.GenericParameters); + } + return changed || changedGenerics; + } + + static bool ReplaceName (List originalTypes, string toFind, string replacement, List resultTypes) + { + var changed = false; + foreach (var type in originalTypes) { + var result = type; + changed = ReplaceName (type, toFind, replacement, ref result) || changed; + resultTypes.Add (result); + } + return changed; + } + + static bool ReplaceName (TupleTypeSpec tuple, string toFind, string replacement, ref TypeSpec result) + { + List resultTypes = new List (tuple.Elements.Count); + if (ReplaceName (tuple.Elements, toFind, replacement, resultTypes)) { + result = new TupleTypeSpec (resultTypes); + return true; + } + result = tuple; + return false; + } + + static bool ReplaceName (ProtocolListTypeSpec protolist, string toFind, string replacement, ref TypeSpec result) + { + var originalProtos = new List (protolist.Protocols.Count); + var resultProtos = new List (protolist.Protocols.Count); + originalProtos.AddRange (protolist.Protocols.Keys); + if (ReplaceName (originalProtos, toFind, replacement, resultProtos)) { + result = new ProtocolListTypeSpec (resultProtos.OfType ()); + return true; + } + return false; + } + + static bool ReplaceName (ClosureTypeSpec closure, string toFind, string replacement, ref TypeSpec result) + { + var resultArgs = closure.Arguments; + var resultReturn = closure.ReturnType; + + var argsChanged = ReplaceName (closure.Arguments, toFind, replacement, ref resultArgs); + var returnChanged = ReplaceName (closure.ReturnType, toFind, replacement, ref resultReturn); + if (argsChanged || returnChanged) { + result = new ClosureTypeSpec (resultArgs, resultReturn); + return true; + } + return false; + } + } + + + public class NamedTypeSpec : TypeSpec { + public NamedTypeSpec (string name) + : base (TypeSpecKind.Named) + { + name = SwiftInterfaceReflector.SwiftInterfaceReflector.UnTick (name); + // Hack filter. + // For whatever reason, Any and AnyObject are not + // strictly in the Swift module. But they are. + // But they're not. + // What do I mean by this? + // Apple's demangler will print these as Swift.Any or + // Swift.AnyObject if the options are set to print + // fully qualified names, so I feel no remorse for doing + // this. + if (name == "Any") + name = "Swift.Any"; + else if (name == "AnyObject") + name = "Swift.AnyObject"; + Name = name; + } + + public NamedTypeSpec (string name, params TypeSpec[] genericSpecialization) + : this (name) + { + GenericParameters.AddRange (genericSpecialization); + } + + public NamedTypeSpec InnerType { get; set; } + + public bool IsProtocolList { get { return Name == "protocol"; } } + public string Name { get; private set; } + + protected override string LLToString (bool useFullName) + { + return useFullName ? Name : NameWithoutModule; + } + + protected override string LLFinalStringParts() + { + if (InnerType == null) + return ""; + return "." + InnerType; + } + + protected override bool LLEquals (TypeSpec other, bool partialNameMatch) + { + NamedTypeSpec spec = other as NamedTypeSpec; + if (spec == null) + return false; + var innersMatch = (InnerType == null && spec.InnerType == null) || (InnerType != null && InnerType.LLEquals (spec.InnerType, partialNameMatch)); + if (partialNameMatch) { + return NameWithoutModule == spec.NameWithoutModule && innersMatch; + } else { + return Name == spec.Name && innersMatch; + } + } + + public bool HasModule (BaseDeclaration context, TypeMapper typeMapper) + { + if (Name.Contains (".")) { + return !context.IsProtocolWithAssociatedTypesFullPath (new NamedTypeSpec (Name), typeMapper); + } else { + return false; + } + } + public string Module { + get { + return Name.Substring (0, Name.IndexOf ('.')); + } + } + public string NameWithoutModule { + get { + return Name.IndexOf ('.') >= 0 ? Name.Substring (Name.IndexOf ('.') + 1) : Name; + } + } + + public override bool HasDynamicSelf { + get { + if (Name == "Self") + return true; + return TypeSpec.AnyHasDynamicSelf (GenericParameters); + } + } + } + + + public class TupleTypeSpec : TypeSpec { + public TupleTypeSpec () + : base (TypeSpecKind.Tuple) + { + Elements = new List (); + } + + public TupleTypeSpec (TupleTypeSpec other) + : base (TypeSpecKind.Tuple) + { + Elements = new List (); + Elements.AddRange (other.Elements); + if (other.HasAttributes) + Attributes.AddRange (other.Attributes); + if (other.ContainsGenericParameters) + GenericParameters.AddRange (other.GenericParameters); + IsInOut = other.IsInOut; + } + + public TupleTypeSpec (IEnumerable elements) + : this () + { + Elements.AddRange (elements); + } + + public TupleTypeSpec (TypeSpec single) + : this () + { + Elements.Add (single); + } + + public List Elements { get; private set; } + + protected override string LLToString (bool useFullName) + { + StringBuilder builder = new StringBuilder (); + builder.Append ('('); + for (int i = 0; i < Elements.Count; i++) { + if (i > 0) + builder.Append (", "); + builder.Append (Elements [i].ToString (useFullName)); + } + builder.Append (')'); + return builder.ToString (); + } + + protected override bool LLEquals (TypeSpec other, bool partialNameMatch) + { + TupleTypeSpec spec = other as TupleTypeSpec; + if (spec == null) + return false; + return ListEqual (Elements, spec.Elements, partialNameMatch); + } + + public override bool IsEmptyTuple { + get { + return Elements.Count == 0; + } + } + + public override bool HasDynamicSelf => TypeSpec.AnyHasDynamicSelf (Elements); + + static TupleTypeSpec empty = new TupleTypeSpec (); + public static TupleTypeSpec Empty { get { return empty; } } + } + + public class ClosureTypeSpec : TypeSpec { + public ClosureTypeSpec () + : base (TypeSpecKind.Closure) + { + } + + public ClosureTypeSpec (TypeSpec arguments, TypeSpec returnType) + : this () + { + Arguments = arguments; + ReturnType = returnType; + } + + static ClosureTypeSpec voidVoid = new ClosureTypeSpec (TupleTypeSpec.Empty, TupleTypeSpec.Empty); + + public static ClosureTypeSpec VoidVoid { get { return voidVoid; } } + + public TypeSpec Arguments { get; set; } + public TypeSpec ReturnType { get; set; } + public bool Throws { get; set; } + public bool IsAsync { get; set; } + + public bool HasReturn () + { + return ReturnType != null && !ReturnType.IsEmptyTuple; + } + + public bool HasArguments () + { + return Arguments != null && !Arguments.IsEmptyTuple; + } + + public TupleTypeSpec ArgumentsAsTuple { + get { + if (Arguments is TupleTypeSpec tuple) + return tuple; + return new TupleTypeSpec (Arguments); + } + } + + public int ArgumentCount () + { + if (!HasArguments ()) + return 0; + if (Arguments is TupleTypeSpec tupe) { + return tupe.Elements.Count; + } + return 1; + } + + public IEnumerable EachArgument () + { + if (!HasArguments ()) + yield break; + TupleTypeSpec argList = Arguments as TupleTypeSpec; + if (argList != null) { + foreach (TypeSpec arg in argList.Elements) + yield return arg; + } else { + yield return Arguments; + } + } + + public TypeSpec GetArgument (int index) + { + if (index < 0 || index >= ArgumentCount ()) + throw new ArgumentOutOfRangeException (nameof (index)); + if (Arguments is TupleTypeSpec tuple) + return tuple.Elements [index]; + return Arguments; + } + + public bool IsEscaping { + get { + return HasAttributes && Attributes.Exists (attr => attr.Name == "escaping"); + } + } + + public bool IsAutoClosure { + get { + return HasAttributes && Attributes.Exists (attr => attr.Name == "autoclosure"); + } + } + + protected override string LLToString (bool useFullName) + { + StringBuilder builder = new StringBuilder (); + builder.Append (Arguments.ToString (useFullName)); + if (Throws) + builder.Append (" throws -> "); + else + builder.Append (" -> "); + builder.Append (ReturnType.ToString (useFullName)); + return builder.ToString (); + } + + protected override bool LLEquals (TypeSpec obj, bool partialNameMatch) + { + ClosureTypeSpec spec = obj as ClosureTypeSpec; + if (spec == null) + return false; + + if (partialNameMatch) { + if (Arguments == null && spec.Arguments == null && + ReturnType == null && spec.ReturnType == null) { + return true; + } + if (Arguments == null || spec.Arguments == null) + return false; + if (ReturnType == null || spec.ReturnType == null) + return false; + return Arguments.EqualsPartialMatch (spec.Arguments) && + ReturnType.EqualsPartialMatch (spec.ReturnType); + + } else { + var specArgs = spec.Arguments is TupleTypeSpec ? spec.Arguments : new TupleTypeSpec (spec.Arguments); + var thisArgs = Arguments is TupleTypeSpec ? Arguments : new TupleTypeSpec (Arguments); + return BothNullOrEqual (thisArgs, specArgs) && + BothNullOrEqual (ReturnType, spec.ReturnType); + } + } + + public override bool HasDynamicSelf { + get { + if (Arguments.HasDynamicSelf) + return true; + if (!IsNullOrEmptyTuple (ReturnType) && ReturnType.HasDynamicSelf) + return true; + return false; + } + } + } + + public class ProtocolListTypeSpec : TypeSpec { + + class SpecComparer : IComparer { + public int Compare (TypeSpec x, TypeSpec y) + { + if (x == null) + throw new ArgumentNullException (nameof (x)); + if (y == null) + throw new ArgumentNullException (nameof (y)); + + return StringComparer.Ordinal.Compare (x.ToString (), y.ToString ()); + } + } + + class SpecEqComparer : IEqualityComparer { + bool partialNameMatch; + public SpecEqComparer (bool partialNameMatch) + { + this.partialNameMatch = partialNameMatch; + } + + public bool Equals (TypeSpec x, TypeSpec y) + { + if (partialNameMatch) + return x.EqualsPartialMatch (y); + return x.Equals (y); + } + + public int GetHashCode (TypeSpec obj) + { + throw new NotImplementedException (); + } + } + + public ProtocolListTypeSpec () + : base (TypeSpecKind.ProtocolList) + { + Protocols = new SortedList (new SpecComparer ()); + } + + public ProtocolListTypeSpec (IEnumerable protos) + : this () + { + foreach (var proto in protos) + Protocols.Add (proto, false); + } + + public SortedList Protocols { get; private set; } + + protected override bool LLEquals (TypeSpec other, bool partialNameMatch) + { + var otherProtos = other as ProtocolListTypeSpec; + if (otherProtos == null) + return false; + if (otherProtos.Protocols.Count != Protocols.Count) + return false; + var eqComparer = new SpecEqComparer (partialNameMatch); + + return Protocols.Keys.SequenceEqual (otherProtos.Protocols.Keys, eqComparer); + } + + protected override string LLToString (bool useFullName) + { + return Protocols.Keys.Select (proto => proto.ToString ()).InterleaveStrings (" & "); + } + + public override bool HasDynamicSelf => false; + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs new file mode 100644 index 000000000000..b4431af3e7a1 --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Collections.Generic; +using SwiftReflector.ExceptionTools; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeSpecParser { + TextReader reader; + TypeSpecTokenizer tokenizer; + + TypeSpecParser (TextReader reader) + { + this.reader = reader; + tokenizer = new TypeSpecTokenizer (reader); + } + + TypeSpec Parse () + { + TypeSpecToken token = tokenizer.Peek (); + TypeSpec type = null; + List attrs = null; + var inout = false; + var isAny = false; + string typeLabel = null; + var throwsClosure = false; + var asyncClosure = false; + var expectClosure = false; + + // Prefix + + // parse any attributes + if (token.Kind == TypeTokenKind.At) { + attrs = ParseAttributes (); + token = tokenizer.Peek (); + } + + // looks like it's inout + if (token.Kind == TypeTokenKind.TypeName && token.Value == "inout") { + inout = true; + tokenizer.Next (); + token = tokenizer.Peek (); + } + + if (token.Kind == TypeTokenKind.TypeName && token.Value == "any") { + isAny = true; + tokenizer.Next (); + token = tokenizer.Peek (); + } + + if (token.Kind == TypeTokenKind.TypeLabel) { + typeLabel = token.Value; + tokenizer.Next (); + token = tokenizer.Peek (); + } + + + // meat + + + if (token.Kind == TypeTokenKind.LeftParenthesis) { // tuple + tokenizer.Next (); + TupleTypeSpec tuple = ParseTuple (); + type = tuple.Elements.Count == 1 ? tuple.Elements [0] : tuple; + typeLabel = type.TypeLabel; + type.TypeLabel = null; + } else if (token.Kind == TypeTokenKind.TypeName) { // name + tokenizer.Next (); + var tokenValue = token.Value.StartsWith ("ObjectiveC.", StringComparison.Ordinal) ? + "Foundation" + token.Value.Substring ("ObjectiveC".Length) : token.Value; + if (tokenValue == "Swift.Void") + type = TupleTypeSpec.Empty; + else + type = new NamedTypeSpec (tokenValue); + } else if (token.Kind == TypeTokenKind.LeftBracket) { // array + tokenizer.Next (); + type = ParseArray (); + } else { // illegal + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 0, $"Unexpected token {token.Value}."); + } + + if (tokenizer.NextIs ("async")) { + tokenizer.Next (); + asyncClosure = true; + expectClosure = true; + } + + if (tokenizer.NextIs ("throws")) { + tokenizer.Next (); + throwsClosure = true; + expectClosure = true; + } + + if (tokenizer.Peek ().Kind == TypeTokenKind.Arrow) { + tokenizer.Next (); + type = ParseClosure (type, throwsClosure, asyncClosure); + expectClosure = false; + throwsClosure = false; + asyncClosure = false; + } else if (expectClosure) { + var errorCase = asyncClosure && throwsClosure ? "'async throws'" : asyncClosure ? "'async'" : "'throws'"; + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 1, $"Unexpected token {tokenizer.Peek ().Value} after {errorCase} in a closure."); + } else if (tokenizer.Peek ().Kind == TypeTokenKind.LeftAngle) { + tokenizer.Next (); + type = Genericize (type); + } + + if (tokenizer.Peek().Kind == TypeTokenKind.Period) { + tokenizer.Next (); + var currType = type as NamedTypeSpec; + if (currType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 2, $"In parsing an inner type (type.type), first element is a {type.Kind} instead of a NamedTypeSpec."); + var nextType = Parse () as NamedTypeSpec; + if (nextType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 3, $"In parsing an inner type (type.type), the second element is a {nextType.Kind} instead of a NamedTypeSpec"); + currType.InnerType = nextType; + } + + // Postfix + + if (tokenizer.Peek ().Kind == TypeTokenKind.Ampersand) { + type = ParseProtocolList (type as NamedTypeSpec); + } + + while (tokenizer.Peek ().Kind == TypeTokenKind.QuestionMark) { + tokenizer.Next (); + type = WrapAsBoundGeneric (type, "Swift.Optional"); + } + + if (tokenizer.Peek ().Kind == TypeTokenKind.ExclamationPoint) { + tokenizer.Next (); + type = WrapAsBoundGeneric (type, "Swift.ImplicitlyUnwrappedOptional"); + } + + type.IsInOut = inout; + type.IsAny = isAny; + type.TypeLabel = typeLabel; + + if (type != null && attrs != null) { + type.Attributes.AddRange (attrs); + } + + return type; + } + + List ParseAttributes () + { + // An attribute is + // @name + // or + // @name [ parameters ] + // The spec says that it could be ( parameters ), [ parameters ], or { parameters } + // but the reflection code should make certain that it's [ parameters ]. + List attrs = new List (); + while (true) { + if (tokenizer.Peek ().Kind != TypeTokenKind.At) { + return attrs; + } + tokenizer.Next (); + if (tokenizer.Peek ().Kind != TypeTokenKind.TypeName) { + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 5, $"Unexpected token {tokenizer.Peek ().Value}, expected a name while parsing an attribute."); + } + string name = tokenizer.Next ().Value; + TypeSpecAttribute attr = new TypeSpecAttribute (name); + if (tokenizer.Peek ().Kind == TypeTokenKind.LeftBracket) { + tokenizer.Next (); + ParseAttributeParameters (attr.Parameters); + } + attrs.Add (attr); + } + } + + void ParseAttributeParameters (List parameters) + { + // Attribute parameters are funny + // The contents between the brackets vary. + // They may be comma separated. They may not. + // Therefore this code is likely to break, but since I'm responsible for + // generating the text of the attributes parsed here, I can try to ensure + // that it will always fit the pattern. + while (true) { + if (tokenizer.Peek ().Kind == TypeTokenKind.RightBracket) { + tokenizer.Next (); + return; + } + TypeSpecToken value = tokenizer.Next (); + if (value.Kind != TypeTokenKind.TypeName) { + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 6, $"Unexpected token {value.Value} while parsing attribute parameter."); + } + parameters.Add (value.Value); + if (tokenizer.Peek ().Kind == TypeTokenKind.Comma) { + tokenizer.Next (); + } + } + } + + TypeSpec ParseProtocolList (NamedTypeSpec first) + { + Exceptions.ThrowOnNull (first, nameof (first)); + var protocols = new List (); + protocols.Add (first); + while (true) { + if (tokenizer.Peek ().Kind != TypeTokenKind.Ampersand) + break; + tokenizer.Next (); + var nextName = tokenizer.Next (); + if (nextName.Kind != TypeTokenKind.TypeName) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 13, $"Unexpected token '{nextName.Value}' with kind {nextName.Kind} while parsing a protocol list"); + protocols.Add (new NamedTypeSpec (nextName.Value)); + } + return new ProtocolListTypeSpec (protocols); + } + + void ConsumeList (List elements, TypeTokenKind terminator, string typeImParsing) + { + while (true) { + if (tokenizer.Peek ().Kind == terminator) { + tokenizer.Next (); + return; + } + TypeSpec next = Parse (); + if (next == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 8, $"Unexpected end while parsing a {typeImParsing}"); + elements.Add (next); + if (tokenizer.Peek ().Kind == TypeTokenKind.Comma) { + tokenizer.Next (); + } + } + } + + TypeSpec Genericize (TypeSpec type) + { + ConsumeList (type.GenericParameters, TypeTokenKind.RightAngle, "generic parameter list"); + return type; + } + + TypeSpec WrapAsBoundGeneric(TypeSpec type, string name) + { + var result = new NamedTypeSpec (name); + result.GenericParameters.Add (type); + return result; + } + + TupleTypeSpec ParseTuple () + { + TupleTypeSpec tuple = new TupleTypeSpec (); + ConsumeList (tuple.Elements, TypeTokenKind.RightParenthesis, "tuple"); + return tuple; + } + + NamedTypeSpec ParseArray() + { + var keyType = Parse (); + TypeSpec valueType = null; + if (keyType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 9, "Unexpected end while parsing an array or dictionary."); + if (tokenizer.Peek ().Kind == TypeTokenKind.Colon) { + tokenizer.Next (); + valueType = Parse (); + if (valueType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 10, "Unexpected end while parsing a dictionary value type."); + } else if (tokenizer.Peek ().Kind != TypeTokenKind.RightBracket) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 11, "Expected a right bracket after an array or dictionary."); + + tokenizer.Next (); + + if (valueType == null) { + var array = new NamedTypeSpec ("Swift.Array"); + array.GenericParameters.Add (keyType); + return array; + } else { + var dictionary = new NamedTypeSpec ("Swift.Dictionary"); + dictionary.GenericParameters.Add (keyType); + dictionary.GenericParameters.Add (valueType); + return dictionary; + } + } + + ClosureTypeSpec ParseClosure (TypeSpec arg, bool throws, bool isAsync) + { + TypeSpec returnType = Parse (); + if (returnType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 12, "Unexpected end while parsing a closure."); + ClosureTypeSpec closure = new ClosureTypeSpec (); + closure.Arguments = arg; + closure.ReturnType = returnType; + closure.Throws = throws; + closure.IsAsync = isAsync; + return closure; + } + + public static TypeSpec Parse (string typeName) + { + TypeSpecParser parser = new TypeSpecParser (new StringReader (typeName)); + return parser.Parse (); + } + } +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs new file mode 100644 index 000000000000..742401a1717a --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using SwiftRuntimeLibrary; + +namespace SwiftReflector.SwiftXmlReflection { + public class TypeSpecToken { + TypeSpecToken (TypeTokenKind kind, string value) + { + Kind = kind; + Value = value; + } + public TypeTokenKind Kind { get; private set; } + public string Value { get; private set; } + public static TypeSpecToken LabelFromString (string value) + { + return new TypeSpecToken (TypeTokenKind.TypeLabel, Exceptions.ThrowOnNull (value, "value")); + } + public static TypeSpecToken FromString (string value) + { + return new TypeSpecToken (TypeTokenKind.TypeName, Exceptions.ThrowOnNull (value, "value")); + } + static TypeSpecToken leftparenthesis = new TypeSpecToken (TypeTokenKind.LeftParenthesis, "("); + static TypeSpecToken rightparenthesis = new TypeSpecToken (TypeTokenKind.RightParenthesis, ")"); + static TypeSpecToken leftangle = new TypeSpecToken (TypeTokenKind.LeftAngle, "<"); + static TypeSpecToken rightangle = new TypeSpecToken (TypeTokenKind.RightAngle, ">"); + static TypeSpecToken comma = new TypeSpecToken (TypeTokenKind.Comma, ","); + static TypeSpecToken arrow = new TypeSpecToken (TypeTokenKind.Arrow, "->"); + static TypeSpecToken at = new TypeSpecToken (TypeTokenKind.At, "@"); + static TypeSpecToken questionmark = new TypeSpecToken (TypeTokenKind.QuestionMark, "?"); + static TypeSpecToken exclamationpoint = new TypeSpecToken (TypeTokenKind.ExclamationPoint, "!"); + static TypeSpecToken done = new TypeSpecToken (TypeTokenKind.Done, ""); + static TypeSpecToken leftbracket = new TypeSpecToken (TypeTokenKind.LeftBracket, "["); + static TypeSpecToken rightbracket = new TypeSpecToken (TypeTokenKind.RightBracket, "]"); + static TypeSpecToken colon = new TypeSpecToken (TypeTokenKind.Colon, ":"); + static TypeSpecToken period = new TypeSpecToken (TypeTokenKind.Period, ".'"); + static TypeSpecToken ampersand = new TypeSpecToken (TypeTokenKind.Ampersand, "&"); + + public static TypeSpecToken LeftParenthesis { get { return leftparenthesis; } } + public static TypeSpecToken RightParenthesis { get { return rightparenthesis; } } + public static TypeSpecToken LeftAngle { get { return leftangle; } } + public static TypeSpecToken RightAngle { get { return rightangle; } } + public static TypeSpecToken Comma { get { return comma; } } + public static TypeSpecToken Arrow { get { return arrow; } } + public static TypeSpecToken At { get { return at; } } + public static TypeSpecToken QuestionMark { get { return questionmark; } } + public static TypeSpecToken ExclamationPoint { get { return exclamationpoint; }} + public static TypeSpecToken Done { get { return done; } } + public static TypeSpecToken LeftBracket { get { return leftbracket; } } + public static TypeSpecToken RightBracket { get { return rightbracket; } } + public static TypeSpecToken Colon { get { return colon; } } + public static TypeSpecToken Period { get { return period; } } + public static TypeSpecToken Ampersand { get { return ampersand; } } + public override string ToString () + { + return Value; + } + } + +} + diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs new file mode 100644 index 000000000000..bfea78bfd64e --- /dev/null +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Text; +using System.IO; +using SwiftReflector.ExceptionTools; + +namespace SwiftReflector.SwiftXmlReflection { + + public class TypeSpecTokenizer { + enum State { + Start, + InName, + InArrow, + }; + + State state; + StringBuilder buffer; + TextReader reader; + static string invalidNameChars; + + static TypeSpecTokenizer () + { + // OK - thanks Apple. Since identifiers in Swift can be any messed up unicode, including emoji, we + // can't just ask "IsLetterOrNumber". Instead, I build the set of characters that are specifically + // forbidden. Guh. + StringBuilder sb = new StringBuilder (); + for (char c = (char)0; c < '.'; c++) { + sb.Append (c); + } + sb.Append ('/'); + for (char c = ':'; c < 'A'; c++) { + sb.Append (c); + } + for (char c = '['; c < '_'; c++) { + sb.Append (c); + } + sb.Append ('`'); + for (char c = '{'; c <= (char)127; c++) { + sb.Append (c); + } + invalidNameChars = sb.ToString (); + } + + public TypeSpecTokenizer (TextReader reader) + { + this.reader = reader; + buffer = new StringBuilder (); + state = State.Start; + } + + TypeSpecToken curr = null; + + public TypeSpecToken Peek () + { + if (curr == null) { + curr = Next (); + } + return curr; + } + + public TypeSpecToken Next () + { + if (curr != null) { + TypeSpecToken retval = curr; + curr = null; + return retval; + } + TypeSpecToken token = null; + do { + switch (state) { + case State.InName: + token = DoName (); + break; + case State.InArrow: + token = DoArrow (); + break; + case State.Start: + token = DoStart (); + break; + } + } while (token == null); + return token; + } + + public bool NextIs (string name) + { + return Peek ().Kind == TypeTokenKind.TypeName && Peek ().Value == name; + } + + TypeSpecToken DoName () + { + int curr = reader.Peek (); + if (curr < 0 || InvalidNameCharacter ((char)curr)) { + if (curr == ':') { + reader.Read (); // drop the colon + state = State.Start; + TypeSpecToken token = TypeSpecToken.LabelFromString (buffer.ToString ()); + buffer.Clear (); + return token; + } else { + state = State.Start; + TypeSpecToken token = TypeSpecToken.FromString (buffer.ToString ()); + buffer.Clear (); + return token; + } + } else { + buffer.Append ((char)reader.Read ()); + return null; + } + } + + TypeSpecToken DoArrow () + { + if (buffer.Length == 0) { + if (reader.Peek () == (int)'-') { + buffer.Append ((char)reader.Read ()); + return null; + } + } else { + if (reader.Peek () == (int)'>') { + reader.Read (); + buffer.Clear (); + state = State.Start; + return TypeSpecToken.Arrow; + } + } + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 4, $"Unexpected character {(char)reader.Peek ()} while parsing '->'."); + } + + TypeSpecToken DoStart () + { + int currentChar = reader.Peek (); + if (currentChar < 0) + return TypeSpecToken.Done; + char c = (char)currentChar; + switch (c) { + case '(': + reader.Read (); + return TypeSpecToken.LeftParenthesis; + case ')': + reader.Read (); + return TypeSpecToken.RightParenthesis; + case '<': + reader.Read (); + return TypeSpecToken.LeftAngle; + case '>': + reader.Read (); + return TypeSpecToken.RightAngle; + case ',': + reader.Read (); + return TypeSpecToken.Comma; + case '@': + reader.Read (); + return TypeSpecToken.At; + case '?': + reader.Read (); + return TypeSpecToken.QuestionMark; + case '!': + reader.Read (); + return TypeSpecToken.ExclamationPoint; + case '-': + state = State.InArrow; + return null; + case '[': + reader.Read (); + return TypeSpecToken.LeftBracket; + case ']': + reader.Read (); + return TypeSpecToken.RightBracket; + case ':': + reader.Read (); + return TypeSpecToken.Colon; + case '.': + reader.Read (); + return TypeSpecToken.Period; + case '&': + reader.Read (); + return TypeSpecToken.Ampersand; + default: + if (Char.IsWhiteSpace (c)) { + reader.Read (); + return null; + } + if (InvalidNameCharacter (c)) { + throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 7, $"Unexpected/illegal char {c}"); + } + state = State.InName; + return null; + } + } + + static bool InvalidNameCharacter (char c) + { + return invalidNameChars.IndexOf (c) >= 0; + } + } +} + diff --git a/src/SwiftReflector/TopLevelFunctionCompiler.cs b/src/SwiftReflector/TopLevelFunctionCompiler.cs new file mode 100644 index 000000000000..1a22c991008b --- /dev/null +++ b/src/SwiftReflector/TopLevelFunctionCompiler.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using SyntaxDynamo; +using SyntaxDynamo.CSLang; +using SwiftReflector.ExceptionTools; +using SwiftReflector.TypeMapping; +using SwiftReflector.SwiftXmlReflection; +using SwiftRuntimeLibrary; +using SwiftReflector.Demangling; + +namespace SwiftReflector { + public class TopLevelFunctionCompiler { + TypeMapper typeMap; + Dictionary mangledToCSharp = new Dictionary (); + + public TopLevelFunctionCompiler (TypeMapper typeMap) + { + this.typeMap = typeMap; + } + + public CSProperty CompileProperty (string propertyName, CSUsingPackages packs, SwiftType swiftPropertyType, bool hasGetter, bool hasSetter, + CSMethodKind methodKind) + { + propertyName = typeMap.SanitizeIdentifier (propertyName); + NetTypeBundle propertyType = typeMap.MapType (swiftPropertyType, false); + + if (!(swiftPropertyType is SwiftGenericArgReferenceType)) + AddUsingBlock (packs, propertyType); + ICodeElement [] uselessLine = new ICodeElement [] { CSReturn.ReturnLine (new CSIdentifier ("useless")) }; + + CSCodeBlock getterBlock = null; + if (hasGetter) + getterBlock = new CSCodeBlock (uselessLine); + CSCodeBlock setterBlock = null; + if (hasSetter) + setterBlock = new CSCodeBlock (uselessLine); + + CSProperty theProp = new CSProperty (propertyType.ToCSType (packs), methodKind, + new CSIdentifier (propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); + if (getterBlock != null) + getterBlock.Clear (); + if (setterBlock != null) + setterBlock.Clear (); + + return theProp; + } + + public CSProperty CompileProperty (CSUsingPackages packs, string propertyName, + FunctionDeclaration getter, FunctionDeclaration setter, CSMethodKind methodKind = CSMethodKind.None) + { + var swiftPropertyType = GetPropertyType (getter, setter); + NetTypeBundle propertyType = null; + if (TypeMapper.IsCompoundProtocolListType (swiftPropertyType)) { + propertyType = new NetTypeBundle ("System", "object", false, false, EntityType.ProtocolList); + } else { + propertyType = typeMap.MapType (getter, swiftPropertyType, false, true); + } + propertyName = propertyName ?? typeMap.SanitizeIdentifier (getter != null ? getter.PropertyName : setter.PropertyName); + bool isSubscript = getter != null ? getter.IsSubscript : + setter.IsSubscript; + + if (!getter.IsTypeSpecGeneric (swiftPropertyType)) + AddUsingBlock (packs, propertyType); + + var uselessLine = new ICodeElement [] { CSReturn.ReturnLine (new CSIdentifier ("useless")) }; + + CSCodeBlock getterBlock = null; + if (getter != null) + getterBlock = new CSCodeBlock (uselessLine); + CSCodeBlock setterBlock = null; + if (setter != null) + setterBlock = new CSCodeBlock (uselessLine); + + CSProperty theProp = null; + var csPropType = propertyType.ToCSType (packs); + if (isSubscript) { + List swiftParms = null; + if (getter != null) { + swiftParms = getter.ParameterLists [1]; + } else { + swiftParms = setter.ParameterLists [1].Skip (1).ToList (); + } + var args = typeMap.MapParameterList (getter, swiftParms, false, false, null, null, packs); + args.ForEach (a => AddUsingBlock (packs, a.Type)); + + var csParams = + new CSParameterList ( + args.Select (a => + new CSParameter (a.Type.ToCSType (packs), + new CSIdentifier (a.Name), a.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null))); + theProp = new CSProperty (csPropType, methodKind, CSVisibility.Public, getterBlock, + CSVisibility.Public, setterBlock, csParams); + + + } else { + theProp = new CSProperty (csPropType, methodKind, + new CSIdentifier (propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); + } + // if (propertyType.Throws) + // DecoratePropWithThrows (theProp, packs); + if (getterBlock != null) + getterBlock.Clear (); + if (setterBlock != null) + setterBlock.Clear (); + + return theProp; + } + + SwiftType GetPropertyType (SwiftPropertyType getter, SwiftPropertyType setter) + { + if (getter != null) { + return getter.ReturnType; + } + if (setter != null) { + if (setter.IsSubscript) { + return ((SwiftTupleType)setter.Parameters).Contents [0]; + } else { + return setter.Parameters; + } + } + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 0, "neither getter nor setter provided"); + } + + TypeSpec GetPropertyType (FunctionDeclaration getter, FunctionDeclaration setter) + { + if (getter != null) { + return getter.ReturnTypeSpec; + } + if (setter != null) { + // same for subscript and prop + return setter.ParameterLists [1] [0].TypeSpec; + } + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 1, "neither getter nor setter provided"); + } + + public CSMethod CompileMethod (FunctionDeclaration func, CSUsingPackages packs, string libraryPath, + string mangledName, string functionName, bool isPinvoke, bool isFinal, bool isStatic) + { + isStatic = isStatic || func.IsExtension; + var extraProtoArgs = new CSGenericTypeDeclarationCollection (); + var extraProtoConstraints = new CSGenericConstraintCollection (); + var args = typeMap.MapParameterList (func, func.ParameterLists.Last (), isPinvoke, false, extraProtoArgs, extraProtoConstraints, packs); + if (isPinvoke && func.ParameterLists.Count > 1) { + var metaTypeBundle = new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, false, EntityType.None); + NetParam p = new NetParam ("metaClass", metaTypeBundle); + args.Add (p); + } + + NetTypeBundle returnType = null; + if (func.ReturnTypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) { + returnType = new NetTypeBundle ("System", "object", false, false, EntityType.ProtocolList); + } else { + returnType = typeMap.MapType (func, func.ReturnTypeSpec, isPinvoke, true); + } + + string funcName = functionName ?? typeMap.SanitizeIdentifier (func.Name); + + if (isPinvoke && !mangledToCSharp.ContainsKey (mangledName)) + mangledToCSharp.Add (mangledName, funcName); + + args.ForEach (a => AddUsingBlock (packs, a.Type)); + + if (returnType != null && !(func.IsTypeSpecGeneric (func.ReturnTypeSpec))) + AddUsingBlock (packs, returnType); + + CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType (packs); + + var csParams = new CSParameterList (); + foreach (var arg in args) { + var csType = arg.Type.ToCSType (packs); + // if (arg.Type.Throws) + // csType = DecorateTypeWithThrows (csType, packs); + csParams.Add (new CSParameter (csType, new CSIdentifier (arg.Name), + arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)); + + } + + if (isPinvoke) { + // AddExtraGenericArguments (func, csParams, packs); + var pinvoke = CSMethod.InternalPInvoke (csReturnType, funcName, libraryPath, + mangledName.Substring (1), csParams); + if (csReturnType is CSSimpleType simple && simple.Name == "bool") { + CSAttribute.ReturnMarshalAsI1.AttachBefore (pinvoke); + } + return pinvoke; + } else { + CSMethod retval = null; + if (func.IsConstructor) { + retval = CSMethod.PublicConstructor (funcName, csParams, new CSCodeBlock ()); + } else { + if (isFinal) + retval = new CSMethod (CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.None, csReturnType, new CSIdentifier (funcName), + csParams, new CSCodeBlock ()); + else + retval = new CSMethod (CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.Virtual, csReturnType, new CSIdentifier (funcName), + csParams, new CSCodeBlock ()); + } + if (extraProtoArgs.Count > 0) { + retval.GenericParameters.AddRange (extraProtoArgs); + retval.GenericConstraints.AddRange (extraProtoConstraints); + } + return retval; + } + } + + public static bool GenericArgumentIsReferencedByGenericClassInParameterList (SwiftBaseFunctionType func, GenericArgument arg) + { + foreach (SwiftType st in func.EachParameter) { + if (st is SwiftUnboundGenericType) { + var sut = (SwiftUnboundGenericType)st; + if (!sut.DependentType.IsClass) + continue; + // there appears to be a bug in the swift compiler that doesn't accept certain + // generic patterns that will ensure that sut.Arguments won't ever have more than 1 + // element in it in cases that we care about, but what the heck - do the general case. + foreach (GenericArgument gen in sut.Arguments) { + if (gen.Depth == arg.Depth && gen.Index == arg.Index) + return true; + } + } + } + return false; + } + + public static bool GenericDeclarationIsReferencedByGenericClassInParameterList (FunctionDeclaration func, GenericDeclaration genDecl, TypeMapper mapper) + { + foreach (ParameterItem pi in func.ParameterLists.Last ()) { + if (pi.TypeSpec is NamedTypeSpec) { + // this inner section should probably be recursive, but I was unable to + // even test if SomeClass> is valid because the swift compiler + // wouldn't take it. + var ns = (NamedTypeSpec)pi.TypeSpec; + if (ns.ContainsGenericParameters) { + Entity en = mapper.GetEntityForTypeSpec (ns); + if (en != null && en.EntityType == EntityType.Class) { + foreach (TypeSpec genTS in ns.GenericParameters) { + var nsGen = genTS as NamedTypeSpec; + if (nsGen != null) { + if (genDecl.Name == nsGen.Name) + return true; + } + } + } + } + } + } + return false; + } + + public string CSMethodForMangledName (string mangledName) + { + return mangledToCSharp [SwiftRuntimeLibrary.Exceptions.ThrowOnNull (mangledName, "mangledName")]; + } + + static void AddUsingBlock (CSUsingPackages packs, NetTypeBundle type) + { + if (type.IsVoid || String.IsNullOrEmpty (type.NameSpace)) + return; + packs.AddIfNotPresent (type.NameSpace); + } + + + int TotalProtocolConstraints (GenericArgument gen) + { + int count = 0; + foreach (var constraint in gen.Constraints) { + var ct = constraint as SwiftClassType; + if (ct == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 11, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); + if (ct.EntityKind == MemberNesting.Protocol) + count++; + } + return count; + } + int TotalProtocolConstraints (GenericDeclaration gen) + { + int count = 0; + foreach (BaseConstraint constraint in gen.Constraints) { + var inh = constraint as InheritanceConstraint; + if (inh == null) + continue; + // throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 12, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); + var en = typeMap.GetEntityForTypeSpec (inh.InheritsTypeSpec); + if (en.EntityType == EntityType.Protocol) + count++; + } + return count; + } + + bool IsObjCStruct (NetParam ntb, SwiftType parmType) + { + if (ntb.Type.Entity != EntityType.Struct) + return false; + + // if the Entity is EntityType.Struct, it's guaranteed to be a SwiftClassType + var structType = parmType as SwiftClassType; + var entity = typeMap.GetEntityForSwiftClassName (structType.ClassName.ToFullyQualifiedName (true)); + if (entity == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 5, $"Unable to get the entity for struct type {structType.ClassName.ToFullyQualifiedName (true)}"); + return entity.Type.IsObjC; + } + + bool IsObjCStruct (TypeSpec typeSpec) + { + if (!(typeSpec is NamedTypeSpec)) + return false; + var entity = typeMap.GetEntityForTypeSpec (typeSpec); + if (entity == null) + throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 6, $"Unable to get the entity for type {typeSpec.ToString ()}"); + return entity.IsObjCStruct; + } + + void RemapSwiftClosureRepresensation (List args) + { + for (int i = 0; i < args.Count; i++) { + if (args[i].Type.FullName == "SwiftRuntimeLibrary.SwiftClosureRepresentation") { + var bundle = new NetTypeBundle ("SwiftRuntimeLibrary", "BlindSwiftClosureRepresentation", false, args [i].Type.IsReference, EntityType.Closure); + args [i] = new NetParam (args [i].Name, bundle); + } + } + } + + public static bool TypeSpecCanThrow (TypeSpec t, bool isPinvoke) + { + if (t == null) + return false; + return !isPinvoke && t is ClosureTypeSpec cl && cl.Throws; + } + } +} + diff --git a/src/SwiftReflector/TypeMapping/Entity.cs b/src/SwiftReflector/TypeMapping/Entity.cs new file mode 100644 index 000000000000..8b0db5fa074b --- /dev/null +++ b/src/SwiftReflector/TypeMapping/Entity.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.IOUtils; +using System.Xml.Linq; + +namespace SwiftReflector.TypeMapping { + public class Entity : IXElementConvertible { + public Entity () + { + } + + public string SharpNamespace { get; set; } + public string SharpTypeName { get; set; } + public EntityType EntityType { get; set; } + public string ProtocolProxyModule { get; set; } + public bool IsDiscretionaryConstraint { get; set; } + + public TypeDeclaration Type { get; set; } + + public DotNetName GetFullType () + { + return new DotNetName (SharpNamespace, SharpTypeName); + } + + public bool IsStructOrEnum { + get { + return EntityType == EntityType.Struct || EntityType == EntityType.Enum || + EntityType == EntityType.TrivialEnum; + } + } + + public bool IsStructClassOrEnum { + get { + return IsStructOrEnum || EntityType == EntityType.Class; + } + } + + public bool IsObjCClass { + get { + return EntityType == EntityType.Class && (Type != null && Type.IsObjC); + } + } + + public bool IsObjCStruct { + get { + return EntityType == EntityType.Struct && (Type != null && Type.IsObjC); + } + } + + public bool IsObjCEnum { + get { + return EntityType == EntityType.Enum && (Type != null && Type.IsObjC); + } + } + + public bool IsObjCProtocol { + get { + return EntityType == EntityType.Protocol && (Type != null && Type.IsObjC); + } + } + + #region IXElementConvertible implementation + + public XElement ToXElement () + { + return new XElement ("entity", + new XAttribute ("sharpNameSpace", SharpNamespace), + new XAttribute ("sharpTypeName", SharpTypeName), + new XAttribute ("entityType", EntityType), + new XAttribute ("protocolProxyModule", ProtocolProxyModule ?? ""), + new XAttribute ("discretionaryConstraint", IsDiscretionaryConstraint ? "true" : "false"), + Type.ToXElement ()); + } + + #endregion + } +} + diff --git a/src/SwiftReflector/TypeMapping/ModuleDatabase.cs b/src/SwiftReflector/TypeMapping/ModuleDatabase.cs new file mode 100644 index 000000000000..bf16577c26e9 --- /dev/null +++ b/src/SwiftReflector/TypeMapping/ModuleDatabase.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using SwiftReflector.SwiftXmlReflection; + +namespace SwiftReflector.TypeMapping { + public class ModuleDatabase : Dictionary{ + public ModuleDatabase () + { + Operators = new List (); + TypeAliases = new List (); + } + + public List Operators { get; private set; } + public List TypeAliases { get; private set; } + } +} diff --git a/src/SwiftReflector/TypeMapping/NetParam.cs b/src/SwiftReflector/TypeMapping/NetParam.cs new file mode 100644 index 000000000000..7b3dc2e3285b --- /dev/null +++ b/src/SwiftReflector/TypeMapping/NetParam.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using SwiftRuntimeLibrary; + +namespace SwiftReflector.TypeMapping { + public class NetParam { + public NetParam (string name, NetTypeBundle bundle) + { + Name = Exceptions.ThrowOnNull (name, "name"); + Type = bundle; + } + public string Name { get; private set; } + public NetTypeBundle Type { get; private set; } + } + +} + diff --git a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs new file mode 100644 index 000000000000..5578639f45b3 --- /dev/null +++ b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SyntaxDynamo.CSLang; +using SwiftReflector.SwiftXmlReflection; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.TypeMapping { + public class NetTypeBundle { + const string kNoType = "!!NO_TYPE!!"; + List genericTypes = new List (); + + public NetTypeBundle (string nameSpace, string entityName, bool isScalar, bool isReference, EntityType entity, + bool swiftThrows = false) + { + GenericIndex = -1; + IsVoid = entityName == kNoType; + Type = entityName; + NameSpace = nameSpace; + + FullName = String.IsNullOrEmpty (nameSpace) ? entityName : nameSpace + "." + entityName; + IsScalar = isScalar; + IsReference = isReference; + Entity = entity; + Throws = swiftThrows; + } + + public NetTypeBundle (List tupleElements, bool isReference) + { + GenericIndex = -1; + string netTypeName = ToTupleName (tupleElements); + FullName = "System." + netTypeName; + Type = netTypeName; + NameSpace = "System"; + + IsScalar = false; + IsReference = isReference; + Entity = EntityType.Tuple; + TupleTypes.AddRange (Exceptions.ThrowOnNull (tupleElements, "tupleElements")); + } + + public NetTypeBundle (string nameSpace, string entityName, EntityType entity, bool isReference, IEnumerable genericTypes, + bool swiftThrows = false) + : this (nameSpace, entityName, false, isReference, entity) + { + GenericIndex = -1; + this.genericTypes.AddRange (genericTypes); + if (this.genericTypes.Count == 0) + throw new ArgumentOutOfRangeException (nameof (genericTypes), "Generic NetBundle constructor needs actual generic types."); + Throws = swiftThrows; + } + + public NetTypeBundle (int depth, int index) + { + if (depth < 0) + throw new ArgumentOutOfRangeException (nameof (depth)); + if (index < 0) + throw new ArgumentOutOfRangeException (nameof (index)); + GenericDepth = depth; + GenericIndex = index; + } + + public NetTypeBundle (ProtocolDeclaration proto, AssociatedTypeDeclaration assoc, bool isReference) + { + GenericIndex = -1; + AssociatedTypeProtocol = proto; + AssociatedType = assoc; + // Type = OverrideBuilder.GenericAssociatedTypeName (assoc); + FullName = Type; + NameSpace = String.Empty; + IsReference = isReference; + } + + public NetTypeBundle (string selfRepresentation, bool isReference) + { + GenericIndex = -1; + Type = FullName = Exceptions.ThrowOnNull (selfRepresentation, nameof (selfRepresentation)); + NameSpace = String.Empty; + IsReference = isReference; + IsSelf = true; + } + + static NetTypeBundle ntbVoid = new NetTypeBundle ("", kNoType, false, false, EntityType.None); + + public static NetTypeBundle Void { get { return ntbVoid; } } + + static NetTypeBundle ntbIntPtr = new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + public static NetTypeBundle IntPtr { + get { + return ntbIntPtr; + } + } + + public bool IsSelf { get; private set; } + public bool IsVoid { get; private set; } + public string Type { get; private set; } + public string NameSpace { get; private set; } + public string FullName { get; private set; } + public bool IsScalar { get; private set; } + public bool IsReference { get; private set; } + public EntityType Entity { get; private set; } + public List TupleTypes { get { return genericTypes; } } + public NetTypeBundle OptionalType { get { return genericTypes [0]; } } + public List GenericTypes { get { return genericTypes; } } + public int GenericDepth { get; private set; } + public int GenericIndex { get; private set; } + public bool IsGenericReference { get { return GenericIndex >= 0; } } + public ProtocolDeclaration AssociatedTypeProtocol { get; private set; } + public AssociatedTypeDeclaration AssociatedType { get; private set; } + public bool IsAssociatedType { get { return AssociatedTypeProtocol != null; } } + public bool Throws { get; private set; } + public bool ContainsGenericParts { + get { + return genericTypes.Count > 0; + } + } + public List GenericConstraints { + get { + return IsGenericReference ? GenericTypes : null; + } + } + + public override string ToString () + { + return FullName; + } + + public override bool Equals (object obj) + { + NetTypeBundle other = obj as NetTypeBundle; + if (other == null) + return false; + return FullName == other.FullName; + } + + public override int GetHashCode () + { + return FullName.GetHashCode (); + } + + static string ToTupleName (IEnumerable types) + { + StringBuilder sb = new StringBuilder (); + bool first = true; + sb.Append ("Tuple<"); + foreach (NetTypeBundle t in types) { + if (!first) { + sb.Append (", "); + } + first = false; + sb.Append (t.FullName); + } + return sb.Append (">").ToString (); + } + + static string ToOptionalName (NetTypeBundle optType) + { + StringBuilder sb = new StringBuilder (); + sb.Append ("SwiftOptional<").Append (optType.FullName).Append (">"); + return sb.ToString (); + } + + + static IEnumerable ToCSSimpleType (IEnumerable ntbs, CSUsingPackages use) + { + return ntbs.Select (ntb => ToCSSimpleType (ntb, use)); + } + + public static CSType ToCSSimpleType(NetTypeBundle ntb, CSUsingPackages use) + { + if (!String.IsNullOrEmpty (ntb.NameSpace)) + use.AddIfNotPresent (ntb.NameSpace); + return ntb.Entity == EntityType.Tuple ? ToCSTuple (ntb.TupleTypes, use) : ntb.ToCSType (use); + } + + public static CSSimpleType ToCSOptional (NetTypeBundle optType, CSUsingPackages use) + { + // use.AddIfNotPresent (typeof (SwiftOptional<>)); + // return new CSSimpleType ("SwiftOptional", false, optType.ToCSType (use)); + throw new Exception(); + } + + public static CSSimpleType ToCSTuple (IList innerTypes, CSUsingPackages use) + { + if (innerTypes.Count <= 7) { + return new CSSimpleType ("Tuple", false, ToCSSimpleType (innerTypes, use).ToArray ()); + } else { + IEnumerable head = ToCSSimpleType (innerTypes.Take (7), use); + CSType tail = ToCSTuple (innerTypes.Skip (7).ToList (), use); + return new CSSimpleType ("Tuple", false, Enumerable.Concat (head, Enumerable.Repeat (tail, 1)).ToArray ()); + } + } + + public CSType ToCSType (CSUsingPackages use) + { + if (!String.IsNullOrEmpty (NameSpace)) + use.AddIfNotPresent (NameSpace); + if (IsGenericReference) { + CSGenericReferenceType genref = new CSGenericReferenceType (GenericDepth, GenericIndex); + if (this.GenericConstraints.Count > 0) { + genref.InterfaceConstraints.AddRange (this.GenericConstraints.Select (ntb => ntb.ToCSType (use))); + } + return genref; + } else if (IsAssociatedType || IsSelf) { + return new CSSimpleType (Type, false); + } + + return Entity == EntityType.Tuple ? ToCSTuple (TupleTypes, use) : + new CSSimpleType (Type, false, GenericTypes.Select (ntb => ntb.ToCSType (use)).ToArray ()); + } + + + } +} + diff --git a/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs b/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs new file mode 100644 index 000000000000..46b11243e918 --- /dev/null +++ b/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo.SwiftLang; +using SwiftReflector.ExceptionTools; +using System.Collections.Generic; +using System.Linq; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.TypeMapping { + public class SwiftTypeToSLType { + TypeMapper typeMapper; + bool IncludeModule { get; } + public SwiftTypeToSLType (TypeMapper typeMapper, bool includeModule = false) + { + this.typeMapper = Exceptions.ThrowOnNull (typeMapper, "typeMapper"); + IncludeModule = includeModule; + } + + + public SLType MapType (SLImportModules modules, SwiftType st) + { + switch (st.Type) { + case CoreCompoundType.Scalar: + return ToScalar ((SwiftBuiltInType)st); + case CoreCompoundType.Tuple: + return ToTuple (modules, (SwiftTupleType)st); + case CoreCompoundType.MetaClass: + // Steve sez: + // Today, type objects are never explicit arguments to functions + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 3, "Asked to map an internal type object to an SLType - this should never happen"); + case CoreCompoundType.Class: + return ToClass (modules, (SwiftClassType)st); + case CoreCompoundType.BoundGeneric: + return ToClass (modules, (SwiftBoundGenericType)st); + case CoreCompoundType.ProtocolList: + return ToProtocol (modules, (SwiftProtocolListType)st); + case CoreCompoundType.GenericReference: + return ToGenericArgReference (modules, (SwiftGenericArgReferenceType)st); + case CoreCompoundType.Function: + return ToClosure (modules, (SwiftFunctionType)st); + default: + throw new NotImplementedException (); + } + } + + public SLType MapType (SLImportModules modules, SwiftClassName cl) + { + return ToClass (modules, cl); + } + + + static SLType ToScalar (SwiftBuiltInType st) + { + switch (st.BuiltInType) { + case CoreBuiltInType.Bool: + return SLSimpleType.Bool; + case CoreBuiltInType.Double: + return SLSimpleType.Double; + case CoreBuiltInType.Float: + return SLSimpleType.Float; + case CoreBuiltInType.Int: + return SLSimpleType.Int; + case CoreBuiltInType.UInt: + return SLSimpleType.UInt; + default: + throw new ArgumentOutOfRangeException (nameof (st)); + } + } + + public void MapParams (SLImportModules modules, List output, SwiftType parameters) + { + if (parameters is SwiftTupleType) { + SLTupleType sltuple = typeMapper.SwiftTypeMapper.ToParameters (modules, (SwiftTupleType)parameters); + output.AddRange (sltuple.Elements); + } else { + output.Add (new SLNameTypePair (parameters.IsReference || MustBeInOut (parameters) ? SLParameterKind.InOut : SLParameterKind.None, new SLIdentifier ("noName"), MapType (modules, parameters))); + } + } + + bool MustBeInOut (SwiftType st) + { + SwiftProtocolListType protList = st as SwiftProtocolListType; + if (protList != null) { + if (protList.Protocols.Count > 1) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 14, "Protocol lists of size > 1 aren't supported. Yet."); + return MustBeInOut (protList.Protocols [0]); + } + if (st.IsClass) + return false; + return typeMapper.MustForcePassByReference (st); + } + + public SLTupleType ToParameters (SLImportModules modules, SwiftTupleType st) + { + List contents = st.Contents.Select ( + (swiftType, i) => new SLNameTypePair ( + swiftType.IsReference || MustBeInOut (swiftType) ? SLParameterKind.InOut : SLParameterKind.None, + ConjureIdentifier (swiftType.Name, i), + MapType (modules, swiftType))).ToList (); + return new SLTupleType (contents); + } + + + SLTupleType ToTuple (SLImportModules modules, SwiftTupleType st) + { + List contents = st.Contents.Select ( + (swiftType, i) => new SLNameTypePair ( + (swiftType.Name == null ? SLIdentifier.Anonymous : new SLIdentifier (swiftType.Name.Name)), + MapType (modules, swiftType))).ToList (); + return new SLTupleType (contents); + } + + SLSimpleType ToClass (SLImportModules modules, SwiftClassType st) + { + return ToClass (modules, st.ClassName, IncludeModule); + } + + SLType ToClass (SLImportModules modules, SwiftBoundGenericType gt) + { + SLType slType = MapType (modules, gt.BaseType); + SLSimpleType baseType = slType as SLSimpleType; + if (baseType == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 15, $"Mapping SwiftType to SLType, expected a simple type, but got {baseType.GetType ().Name}."); + IEnumerable boundTypes = gt.BoundTypes.Select (st => MapType (modules, st)); + return new SLBoundGenericType (baseType.Name, boundTypes); + } + + static SLSimpleType ToClass (SLImportModules modules, SwiftClassName className, bool includeModule = false) + { + modules.AddIfNotPresent (className.Module.Name); + return new SLSimpleType (className.ToFullyQualifiedName (includeModule)); + } + + SLSimpleType ToProtocol (SLImportModules modules, SwiftProtocolListType protocol) + { + if (protocol.Protocols.Count > 1) + throw new NotSupportedException ("Protocol lists > 1 not supported (yet)."); + SwiftClassType cl = protocol.Protocols [0]; + return ToClass (modules, cl); + } + + SLType ToGenericArgReference (SLImportModules modules, SwiftGenericArgReferenceType arg) + { + return new SLGenericReferenceType (arg.Depth, arg.Index, associatedTypePath: arg.AssociatedTypePath); + } + + SLType ToClosure (SLImportModules modules, SwiftFunctionType func) + { + var args = func.EachParameter.Select (p => new SLUnnamedParameter (MapType (modules, p), ToParameterKind (p))); + var returnType = MapType (modules, func.ReturnType); + var closureResult = new SLFuncType (returnType, args); + return closureResult; + } + + static SLIdentifier ConjureIdentifier (SwiftName name, int index) + { + return new SLIdentifier (name != null ? name.Name : String.Format ("noName{0}", index)); + } + + static SLParameterKind ToParameterKind (SwiftType p) + { + if (p.IsReference) + return SLParameterKind.InOut; + return SLParameterKind.None; + } + } +} diff --git a/src/SwiftReflector/TypeMapping/TypeDatabase.cs b/src/SwiftReflector/TypeMapping/TypeDatabase.cs new file mode 100644 index 000000000000..4f4bc24e021d --- /dev/null +++ b/src/SwiftReflector/TypeMapping/TypeDatabase.cs @@ -0,0 +1,471 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.ExceptionTools; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.TypeMapping { + public class DotNetName + { + public readonly string Namespace; + public readonly string TypeName; + + public DotNetName (string @namespace, string typeName) + { + Namespace = @namespace; + TypeName = typeName; + } + + public override string ToString () + { + return $"{Namespace}.{TypeName}"; + } + + public override bool Equals (object obj) + { + var other = obj as DotNetName; + return other != null && Namespace == other.Namespace && TypeName == other.TypeName; + } + + public override int GetHashCode () + { + return Namespace.GetHashCode () ^ TypeName.GetHashCode (); + } + } + + public class TypeDatabase { + const double kCurrentVersion = 1.0; + const double kMinVersion = 1.0; + Dictionary netNamesToSwiftNames = new Dictionary (); + Dictionary swiftNamesToNetNames = new Dictionary (); + + Dictionary modules = new Dictionary (); + + public TypeDatabase () + { + } + + + public DotNetName DotNetNameForSwiftName (string swiftName) + { + DotNetName netName = null; + swiftNamesToNetNames.TryGetValue (Exceptions.ThrowOnNull (swiftName, "swiftName"), out netName); + return netName; // may be null + } + + public DotNetName DotNetNameForSwiftName (SwiftClassName swiftName) + { + return DotNetNameForSwiftName (Exceptions.ThrowOnNull (swiftName, "swiftName").ToFullyQualifiedName (true)); + } + + public string SwiftNameForDotNetName (DotNetName netName) + { + string swiftName = null; + netNamesToSwiftNames.TryGetValue (Exceptions.ThrowOnNull (netName, "netName"), out swiftName); + return swiftName; + } + + public Entity EntityForDotNetName (DotNetName netClassName) + { + return EntityForSwiftName (netNamesToSwiftNames [netClassName]); + } + + public Entity EntityForSwiftName (SwiftClassName swiftName) + { + return EntityForSwiftName (swiftName.ToFullyQualifiedName (true)); + } + + public Entity EntityForSwiftName (string swiftName) + { + var modName = swiftName.ModuleFromName (); + if (modName == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 1, $"Swift name '{swiftName}' needs to have a module."); + + var module = EntityCollection (modName); + if (module == null) + return null; + + Entity e = null; + module.TryGetValue (swiftName, out e); + return e; + } + + public Entity TryGetEntityForSwiftName (string swiftName) + { + try { + return EntityForSwiftName (swiftName); + } + catch { + return null; + } + } + + public int Count { + get { + return modules.Select (m => m.Value.Count).Sum (); + } + } + + public bool Contains (string swiftClassName) + { + return EntityForSwiftName (swiftClassName) != null; + } + + public bool Contains (SwiftClassName swiftClassName) + { + return Contains (swiftClassName.ToFullyQualifiedName (true)); + } + + public bool Contains (DotNetName name) + { + return netNamesToSwiftNames.ContainsKey (name); + } + + public IEnumerable ModuleNames { get { return modules.Keys; } } + + public void Update (Entity e) + { + var old = EntityForSwiftName (e.Type.ToFullyQualifiedName (true)); + if (old == null) { + Add (e); + } else { + old.EntityType = e.EntityType; + old.SharpNamespace = e.SharpNamespace; + old.SharpTypeName = e.SharpTypeName; + old.Type = e.Type; + } + } + + public void Add (Entity e) + { + if (e.Type != null && !e.Type.IsUnrooted) + throw new ArgumentException ("Entity.Type needs to be unrooted.", "e"); + var errors = new ErrorHandling (); + AddEntity (e, errors); + if (errors.AnyErrors) + throw new AggregateException (errors.Errors.Select ((v) => v.Exception)); + } + + ModuleDatabase EntityCollection (string moduleName) + { + ModuleDatabase module = null; + modules.TryGetValue (Exceptions.ThrowOnNull (moduleName, nameof(moduleName)), out module); + return module; + } + + public IEnumerable EntitiesForModule (string moduleName) + { + var module = EntityCollection (moduleName); + if (module != null) + return module.Values; + return Enumerable.Empty (); + } + + public IEnumerable OperatorsForModule (string moduleName) + { + var module = EntityCollection (moduleName); + if (module != null) + return module.Operators; + return Enumerable.Empty (); + } + + public IEnumerable TypeAliasesForModule (string moduleName) + { + var module = EntityCollection (moduleName); + if (module != null) + return module.TypeAliases; + return Enumerable.Empty (); + } + + public void Write (string file, IEnumerable modules) + { + using (FileStream stm = new FileStream (Exceptions.ThrowOnNull (file, nameof(file)), FileMode.Create)) { + Write (stm, modules); + } + } + + public void Write (Stream stm, IEnumerable modules) + { + Write (stm, modules.Select (s => EntitiesForModule (s)).SelectMany (x => x).Select (entity => entity.ToXElement ())); + } + + IEnumerable GatherXElements (IEnumerable modules) + { + foreach (var modName in modules) { + foreach (var entity in EntitiesForModule (modName)) { + yield return entity.ToXElement (); + } + foreach (var op in OperatorsForModule (modName)) { + yield return op.ToXElement (); + } + foreach (var alias in TypeAliasesForModule (modName)) { + yield return alias.ToXElement (); + } + } + } + + public void Write (string file, string module) + { + using (FileStream stm = new FileStream (Exceptions.ThrowOnNull (file, "file"), FileMode.Create)) { + Write (stm, module); + } + } + + public void Write (Stream stm, string module) + { + Write (stm, EntitiesForModule (module).Select (entity => entity.ToXElement ())); + } + + void Write (Stream stm, IEnumerable entities) + { + var entityList = new XElement ("entities", entities); + var db = new XElement ("xamtypedatabase", + new XAttribute ("version", 1.0), + entityList); + var doc = new XDocument ( + new XDeclaration ("1.0", "utf-8", "yes"), + db); + doc.Save (stm); + } + + public bool Merge (TypeDatabase other, ErrorHandling errors) + { + var initialErrorCount = errors.ErrorCount; + foreach (var mod in other.modules.Values) { + foreach (var entity in mod.Values) { + AddEntity (entity, errors); + } + foreach (var op in mod.Operators) { + AddOperator (op); + } + } + return initialErrorCount != errors.ErrorCount; + } + + + public ErrorHandling Read (List files) + { + var errors = new ErrorHandling(); + foreach (string file in files) { + errors.Add (Read (file)); + } + return errors; + } + + public ErrorHandling Read (string file) + { + var errors = new ErrorHandling (); + Stream stm = null; + try { + stm = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read); + errors.Add (Read (stm)); + } catch (Exception e) { + errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 59, e, "Failed opening file {0}: {1}", file, e.Message)); + } finally { + if (stm != null) + stm.Close (); + } + return errors; + } + + public ErrorHandling Read (Stream stm) + { + var errors = new ErrorHandling (); + try { + var doc = XDocument.Load (stm); + var xamtypedatabase = doc.Element ("xamtypedatabase"); + if (xamtypedatabase == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 2, "Type database is missing required key 'xamtypedatabase'"); + var version = xamtypedatabase.DoubleAttribute ("version", -1.0); + if (version < kMinVersion) + if (version > kCurrentVersion) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 3, $"Type database version, {version}, is greater than the current version, {kCurrentVersion}."); + ReadVersion1_0 (xamtypedatabase, errors); + } catch (Exception e) { + errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 60, e, "Failure reading type definition XML: " + e.Message)); + } + return errors; + } + + void ReadVersion1_0 (XElement typeDbRoot, ErrorHandling errors) + { + var localModules = new Dictionary (); + + var entityLists = typeDbRoot.Descendants ("entities"); + + foreach (var entityList in entityLists) { + var entities = from entity in entityList.Elements ("entity") + select EntityFromXElement (entity, localModules, errors); + + foreach (Entity e in entities) { + if (e == null) + continue; + AddEntity (e, errors); + } + + var ops = from op in entityList.Elements ("operator") + select OperatorDeclaration.FromXElement (op, null); + + foreach (var op in ops) { + AddOperator (op); + } + + var aliases = from alias in entityList.Elements ("typealias") + select TypeAliasDeclaration.FromXElement (null, alias); + + foreach (var alias in aliases) { + AddTypeAlias (alias); + } + } + } + + public ModuleDatabase ModuleDatabaseForModuleName (string moduleName) + { + ModuleDatabase db; + if (!modules.TryGetValue (moduleName, out db)) { + db = new ModuleDatabase (); + modules.Add (moduleName, db); + } + return db; + } + + public void AddOperator (OperatorDeclaration op, string moduleName = null) + { + moduleName = moduleName ?? op.ModuleName; + ModuleDatabase db = ModuleDatabaseForModuleName (moduleName); + db.Operators.Add (op); + } + + public IEnumerable FindOperators (IEnumerable moduleNames) + { + foreach (var moduleName in moduleNames) { + ModuleDatabase db = null; + if (!modules.TryGetValue (moduleName, out db)) + continue; + foreach (var op in db.Operators) + yield return op; + } + yield break; + } + + public void AddTypeAlias (TypeAliasDeclaration alias, string moduleName = null) + { + moduleName = moduleName ?? alias.ModuleName; + ModuleDatabase db = ModuleDatabaseForModuleName (moduleName); + db.TypeAliases.Add (alias); + } + + void AddEntity (Entity e, ErrorHandling errors) + { + var swiftName = e.Type.ToFullyQualifiedName (true); + var sharpName = e.GetFullType (); + if (netNamesToSwiftNames.ContainsKey (sharpName)) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 4, $"Already have a C# definition for {e.EntityType} {sharpName}"))); + return; + } + if (swiftNamesToNetNames.ContainsKey (swiftName)) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 5, $"Already have a Swift definition for {e.EntityType} {swiftName}"))); + return; + } + + netNamesToSwiftNames.Add (sharpName, swiftName); + swiftNamesToNetNames.Add (swiftName, sharpName); + + var moduleName = e.Type.Module.Name; + AddEntityToModuleCollection (moduleName, e); + } + + void AddEntityToModuleCollection (string moduleName, Entity e) + { + ModuleDatabase entities = null; + if (!modules.TryGetValue (moduleName, out entities)) { + entities = new ModuleDatabase (); + modules.Add (moduleName, entities); + } + entities.Add (e.Type.ToFullyQualifiedName (true), e); + } + + Entity EntityFromXElement (XElement entityElem, Dictionary theModules, ErrorHandling errors) + { + var typeDeclElement = entityElem.Element ("typedeclaration"); + if (typeDeclElement == null) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 6, "Entity elements must contain a child element."))); + return null; + } + var moduleName = (string)typeDeclElement.Attribute ("module"); + if (string.IsNullOrEmpty (moduleName)) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 7, "Entity elements must contain a module name."))); + return null; + } + var module = MakeModuleForName (moduleName, theModules); + var folder = new TypeAliasFolder (module.TypeAliases); + var decl = TypeDeclaration.FromXElement (folder, typeDeclElement, module, null) as TypeDeclaration; + if (decl == null) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 8, "Incorrect type declaration in entity."))); + return null; + } + var e = new Entity { + SharpNamespace = (string)entityElem.Attribute ("sharpNameSpace"), + SharpTypeName = (string)entityElem.Attribute ("sharpTypeName"), + EntityType = ToEntityType ((string)entityElem.Attribute ("entityType")), + ProtocolProxyModule = (string)entityElem.Attribute ("protocolProxyModule"), + IsDiscretionaryConstraint = IsDiscetionaryConstraint (entityElem), + Type = decl + }; + if (e.SharpNamespace == null) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 12, "Missing sharpNameSpace in entity."))); + return null; + } + if (e.SharpTypeName == null) { + errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 13, "Missing sharpTypeName in entity."))); + return null; + } + return e; + } + + static EntityType ToEntityType (string s) + { + switch (Exceptions.ThrowOnNull (s, "s").ToLower ()) { + case "scalar": + return EntityType.Scalar; + case "class": + return EntityType.Class; + case "struct": + return EntityType.Struct; + case "enum": + return EntityType.Enum; + case "trivialenum": + return EntityType.TrivialEnum; + case "protocol": + return EntityType.Protocol; + default: + case "none": + return EntityType.None; + } + } + + static bool IsDiscetionaryConstraint (XElement entityElem) + { + var discretionary = (string)entityElem.Attribute ("discretionaryConstraint") ?? "false"; + return discretionary.ToLower () == "true"; + } + + ModuleDeclaration MakeModuleForName (string name, Dictionary modules) + { + ModuleDeclaration module = null; + if (!modules.TryGetValue (name, out module)) { + module = new ModuleDeclaration (); + module.Name = name; + modules.Add (name, module); + } + return module; + } + } +} + diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/TypeMapping/TypeMapper.cs new file mode 100644 index 000000000000..6305deeaef0e --- /dev/null +++ b/src/SwiftReflector/TypeMapping/TypeMapper.cs @@ -0,0 +1,1135 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using SwiftReflector.ExceptionTools; +using SwiftReflector.Inventory; +using SwiftReflector.SwiftXmlReflection; +using System.IO; +using SyntaxDynamo.CSLang; +using SwiftRuntimeLibrary; + +namespace SwiftReflector.TypeMapping { + public class TypeMapper { + public TypeDatabase TypeDatabase { get; private set; } + TypeSpecToSLType specMapper, overrideSpecMapper; + SwiftTypeToSLType swiftTypeMapper; + UnicodeMapper unicodeMapper; + HashSet loadedFiles = new HashSet (); + + public TypeMapper (List typeDatabasePaths, UnicodeMapper unicodeMapper) + { + TypeDatabase = new TypeDatabase (); + this.unicodeMapper = unicodeMapper; + + // We check 'SwiftyOptions' for errors so each 'typeDatabasePath' at this point should be a valid directory. + // foreach (var typeDatabasePath in typeDatabasePaths) { + // if (Directory.Exists (typeDatabasePath)) { + // foreach (string fileName in Directory.GetFiles (typeDatabasePath)) + // AddTypeDatabase (fileName); + // } else if (File.Exists (typeDatabasePath)) { + // AddTypeDatabase (typeDatabasePath); + // } + // } + + specMapper = new TypeSpecToSLType (this, false); + overrideSpecMapper = new TypeSpecToSLType (this, true); + swiftTypeMapper = new SwiftTypeToSLType (this); + } + + public void AddTypeDatabase (string fileName) + { + if (loadedFiles.Contains (fileName)) + return; + loadedFiles.Add (fileName); + var errors = TypeDatabase.Read (fileName); + if (errors.AnyErrors) + throw new AggregateException (errors.Errors.Select ((v) => v.Exception)); + } + + DotNetName PreRegisterEntityName (string swiftClassName, EntityType entityKind) + { + + var en = TypeDatabase.EntityForSwiftName (swiftClassName); + if (en != null) + return en.GetFullType (); + + + var netClassName = MakeDotNetClassName (swiftClassName, entityKind == EntityType.Protocol); + + en = new Entity { + SharpNamespace = netClassName.Namespace, + SharpTypeName = netClassName.TypeName, + Type = new ShamDeclaration (swiftClassName, entityKind), + EntityType = entityKind + }; + TypeDatabase.Add (en); + return netClassName; + } + + public bool IsRegistered (SwiftClassName cl) + { + return TypeDatabase.Contains (cl); + } + + public bool IsRegistered (string fullyQualifiedName) + { + return TypeDatabase.Contains (fullyQualifiedName); + } + + public DotNetName PreRegisterEntityName (SwiftClassName cl) + { + var swiftClassName = cl.ToFullyQualifiedName (); + var entity = EntityType.None; + // FIXME + if (cl.IsClass) + entity = EntityType.Class; + else if (cl.IsStruct) + entity = EntityType.Struct; + else if (cl.IsEnum) + entity = EntityType.Enum; + else { + throw new NotImplementedException (); + } + return PreRegisterEntityName (swiftClassName, entity); + } + + public DotNetName GetDotNetNameForSwiftClassName (SwiftClassName cl) + { + return TypeDatabase.EntityForSwiftName (cl).GetFullType (); + } + + public DotNetName GetDotNetNameForTypeSpec (TypeSpec spec) + { + var named = spec as NamedTypeSpec; + if (named == null) + return null; + return GetDotNetNameForSwiftClassName (named.Name); + } + + public DotNetName GetDotNetNameForSwiftClassName (string fullyQualifiedName) + { + var entity = TypeDatabase.EntityForSwiftName (fullyQualifiedName); + if (entity == null) + return null; + return entity.GetFullType (); + } + + public EntityType GetEntityTypeForSwiftClassName (string fullyQualifiedName) + { + var ent = TypeDatabase.EntityForSwiftName (fullyQualifiedName); + return ent != null ? ent.EntityType : EntityType.None; + } + + public EntityType GetEntityTypeForDotNetName (DotNetName netClassName) + { + var ent = TypeDatabase.EntityForDotNetName (netClassName); + return ent != null ? ent.EntityType : EntityType.None; + } + + public Entity GetEntityForSwiftClassName (string fullyQualifiedName) + { + return TypeDatabase.EntityForSwiftName (fullyQualifiedName); + } + + public Entity TryGetEntityForSwiftClassName (string fullyQualifiedName) + { + return TypeDatabase.TryGetEntityForSwiftName (fullyQualifiedName); + } + + public Entity GetEntityForTypeSpec (TypeSpec spec) + { + if (spec == null) + return null; + var ns = spec as NamedTypeSpec; + if (ns == null || spec.IsDynamicSelf) + return null; + return GetEntityForSwiftClassName (ns.Name); + } + + public EntityType GetEntityTypeForTypeSpec (TypeSpec spec) + { + if (spec == null) + return EntityType.None; + + if (spec is NamedTypeSpec) { + if (spec.IsDynamicSelf) + return EntityType.DynamicSelf; + var ent = GetEntityForTypeSpec (spec); + return ent != null ? ent.EntityType : EntityType.None; + } + if (spec is TupleTypeSpec) { + return EntityType.Tuple; + } + if (spec is ClosureTypeSpec) { + return EntityType.Closure; + } + if (spec is ProtocolListTypeSpec) { + return EntityType.ProtocolList; + } + throw new ArgumentOutOfRangeException (spec.GetType ().Name); + } + + public Entity GetEntityForDotNetName (DotNetName netName) + { + return TypeDatabase.EntityForDotNetName (netName); + } + + public DotNetName RegisterClass (TypeDeclaration t) + { + t = t.MakeUnrooted (); + var isProtocol = false; + // FIXME + var entity = EntityType.None; + // don't reorder - until I change this, ProtocolDeclaration extends from ClassDeclaration + if (t is ProtocolDeclaration) { + entity = EntityType.Protocol; + isProtocol = true; + } else if (t is ClassDeclaration) { + entity = EntityType.Class; + } else if (t is StructDeclaration) { + entity = EntityType.Struct; + } else { + EnumDeclaration eDecl = t as EnumDeclaration; + entity = (eDecl.IsTrivial || (eDecl.IsIntegral && eDecl.IsHomogenous && eDecl.Inheritance.Count == 0)) ? EntityType.TrivialEnum : EntityType.Enum; + } + var sharpName = MakeDotNetClassName (t.ToFullyQualifiedName (true), isProtocol); + + var en = new Entity { + SharpNamespace = sharpName.Namespace, + SharpTypeName = sharpName.TypeName, + Type = t, + EntityType = entity + }; + + TypeDatabase.Update (en); + return sharpName; + } + + public IEnumerable RegisterClasses (IEnumerable decl) + { + var allReg = new List (); + foreach (TypeDeclaration cl in decl) { + DotNetName reg = RegisterClass (cl); + allReg.Add (reg); + } + return allReg; + } + + DotNetName MakeDotNetClassName (string fullyQualifiedName, bool isProtocol) + { + var parts = fullyQualifiedName.Split ('.'); + var sb = new StringBuilder (); + var namesp = MapModuleToNamespace (parts [0]); + for (int i = 1; i < parts.Length; i++) { + if (i > 1) + sb.Append ('.'); + if (isProtocol && i == parts.Length - 1) + sb.Append ('I'); + sb.Append (SanitizeIdentifier (parts [i])); + } + return new DotNetName (namesp, sb.ToString ()); + } + + string MakeDotNetClassName (SwiftClassName name) + { + var sb = new StringBuilder (); + var namesp = MapModuleToNamespace (name.Module); + sb.Append (namesp); + foreach (SwiftName sn in name.NestingNames) { + sb.Append ('.'); + sb.Append (SanitizeIdentifier (sn.Name)); + } + return sb.ToString (); + } + + public string MapModuleToNamespace (SwiftName name) + { + string finalName = null; + finalName = UserModuleMap (name); + if (finalName == null) { + finalName = SanitizeIdentifier (name.Name); + } + return finalName; + } + + public string MapModuleToNamespace (string name) + { + string finalName = null; + finalName = UserModuleMap (name); + if (finalName == null) { + finalName = SanitizeIdentifier (name); + } + return finalName; + } + + + string UserModuleMap (SwiftName name) + { + return null; + } + + string UserModuleMap (string name) + { + return null; + } + + static UnicodeCategory [] validStarts = { + UnicodeCategory.UppercaseLetter, + UnicodeCategory.LowercaseLetter, + UnicodeCategory.TitlecaseLetter, + UnicodeCategory.ModifierLetter, + UnicodeCategory.OtherLetter, + UnicodeCategory.LetterNumber + }; + + static bool ValidIdentifierStart (UnicodeCategory cat) + { + return validStarts.Contains (cat); + } + + static UnicodeCategory [] validContent = { + UnicodeCategory.DecimalDigitNumber, + UnicodeCategory.ConnectorPunctuation, + UnicodeCategory.Format + }; + + static bool ValidIdentifierContent (UnicodeCategory cat) + { + return ValidIdentifierStart (cat) || validContent.Contains (cat); + } + + static bool IsValidIdentifier (int position, UnicodeCategory cat) + { + if (position == 0) + return ValidIdentifierStart (cat); + else + return ValidIdentifierContent (cat); + } + + static bool IsHighUnicode (string s) + { + // Steve says: this is arbitrary, but it solves an issue + // with mcs and csc not liking certain Ll and Lu class + // unicode characters (for now). + // Open issue: https://github.com/dotnet/roslyn/issues/27986 + var encoding = Encoding.UTF32; + var bytes = encoding.GetBytes (s); + var utf32Value = BitConverter.ToUInt32 (bytes, 0); + return utf32Value > 0xffff; + } + + public string SanitizeIdentifier (string name) + { + var sb = new StringBuilder (); + + var characterEnum = StringInfo.GetTextElementEnumerator (name); + while (characterEnum.MoveNext ()) { + string c = characterEnum.GetTextElement (); + int i = characterEnum.ElementIndex; + + var cat = CharUnicodeInfo.GetUnicodeCategory (name, i); + + if (IsValidIdentifier (i, cat) && !IsHighUnicode(c)) + sb.Append (i == 0 && cat == UnicodeCategory.LowercaseLetter ? c.ToUpper() : c); + else + sb.Append (unicodeMapper.MapToUnicodeName (c)); + } + + if (CSKeywords.IsKeyword (sb.ToString ())) + sb.Append ('_'); + return sb.ToString (); + } + + static string ComeUpWithAName (string given, string typeName, int index) + { + if (String.IsNullOrEmpty (given)) { + return String.Format ("{0}{1}", Char.ToLower (typeName [0]), index); + } else { + return given; + } + } + + static NetParam ToNamedParam (ParameterItem st, NetTypeBundle bundle, int index) + { + string targetName = ComeUpWithAName (st.NameIsRequired ? st.PublicName : st.PrivateName, bundle.Type, index); + return new NetParam (targetName, bundle); + } + + static bool IsUnique (NetParam p, List pl, int startPoint) + { + for (int i = startPoint; i < pl.Count; i++) { + if (p.Name == pl [i].Name) + return false; + } + return true; + } + + static NetParam Uniquify (NetParam p, List pl, int startPoint) + { + while (!IsUnique (p, pl, startPoint) || CSKeywords.IsKeyword (p.Name)) { + p = new NetParam (p.Name + '0', p.Type); + } + return p; + } + + static List SanitizeParamNames (List parms) + { + List outlist = new List (); + bool changed = false; + do { + changed = false; + outlist = new List (); + for (int i = 0; i < parms.Count; i++) { + NetParam q = Uniquify (parms [i], parms, i + 1); + changed = q.Name != parms [i].Name; + outlist.Add (q); + } + if (changed) + parms = outlist; + } while (changed); + return outlist; + } + + public List GetLineage (SwiftUncurriedFunctionType uft) + { + var lineage = new List (); + if (uft != null) { + var theClass = uft.UncurriedParameter as SwiftClassType; + if (theClass == null) { + var meta = uft.UncurriedParameter as SwiftMetaClassType; + if (meta == null) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 17, $"Expected a SwiftClassType or a SwiftMetaClassType as the uncurried parameter in a function, but got {uft.UncurriedParameter.GetType ().Name}."); + theClass = meta.Class; + } + var sb = new StringBuilder ().Append (theClass.ClassName.Module.Name); + foreach (SwiftName name in theClass.ClassName.NestingNames) { + sb.Append ('.').Append (name.Name); + lineage.Add (sb.ToString ()); + } + } + return lineage; + } + + internal object GetEntityForTypeSpec (object inheritsTypeSpec) + { + throw new NotImplementedException (); + } + + + NetTypeBundle RecastToReference (BaseDeclaration typeContext, NetTypeBundle netBundle, TypeSpec theElem, bool structsAndEnumsAreAlwaysRefs) + { + if (typeContext.IsTypeSpecGenericReference (theElem) || typeContext.IsProtocolWithAssociatedTypesFullPath (theElem as NamedTypeSpec, this)) + return netBundle; + if (theElem is ClosureTypeSpec) + return netBundle; + if (theElem is ProtocolListTypeSpec) + return new NetTypeBundle (netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); + var entity = GetEntityForTypeSpec (theElem); + if (entity != null && (entity.IsObjCStruct || entity.IsObjCEnum) && netBundle.IsReference) + return netBundle; + if (theElem.IsInOut && netBundle.Entity != EntityType.Struct) + return netBundle; + + var objcStructType = ObjCStructOrEnumReferenceType (typeContext, theElem as NamedTypeSpec); + if (objcStructType != null) { + return MapType (typeContext, objcStructType, true); + } + var isStructOrEnum = netBundle.Entity == EntityType.Struct || netBundle.Entity == EntityType.Enum; + if (isStructOrEnum) { + if (MustForcePassByReference (typeContext, theElem) || netBundle.Entity == EntityType.Enum || structsAndEnumsAreAlwaysRefs) { + return new NetTypeBundle ("System", "IntPtr", netBundle.IsScalar, false, netBundle.Entity); + } + } else if (entity != null && entity.EntityType == EntityType.Protocol && !entity.IsObjCProtocol) { + return new NetTypeBundle (netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); + } + return netBundle; + } + + + NetParam MapParameterItem (BaseDeclaration context, ParameterItem parameter, int index, bool isPinvoke, bool structsAndEnumsAreAlwaysRefs) + { + var theType = parameter.TypeSpec; //parameter.IsInOut && !parameter.TypeSpec.IsInOut ? parameter.TypeSpec.WithInOutSet () : parameter.TypeSpec; + var t = MapType (context, theType, isPinvoke); + if (isPinvoke) { + t = RecastToReference (context, t, theType, structsAndEnumsAreAlwaysRefs); + } + return ToNamedParam (parameter, t, index); + } + + public List MapParameterList (BaseDeclaration context, List st, bool isPinvoke, + bool structsAndEnumsAreAlwaysRefs, CSGenericTypeDeclarationCollection extraProtocolTypes, + CSGenericConstraintCollection extraProtocolContstraints, CSUsingPackages use) + { + var parms = new List (); + for (int i=0; i < st.Count; i++) { + if (st[i].TypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) { + var genprotoName = new CSIdentifier ($"TProto{i}"); + extraProtocolTypes.Add (new CSGenericTypeDeclaration (genprotoName)); + extraProtocolContstraints.Add (new CSGenericConstraint (genprotoName, ToConstraintIDs (context, plitem.Protocols.Keys, isPinvoke))); + var netBundle = new NetTypeBundle ("", genprotoName.Name, false, st [i].IsInOut, EntityType.ProtocolList); + + parms.Add (ToNamedParam (st [i], netBundle, i)); + } else { + var entity = !context.IsTypeSpecGeneric (st [i].TypeSpec) ? GetEntityForTypeSpec (st [i].TypeSpec) : null; + if (entity != null && entity.EntityType == EntityType.Protocol && !isPinvoke) { + var proto = entity.Type as ProtocolDeclaration; + // if (proto.HasDynamicSelf) { + // extraProtocolTypes.Add (new CSGenericTypeDeclaration (BindingsCompiler.kGenericSelf)); + // var csProtoBundle = MapType (context, st [i].TypeSpec, isPinvoke); + // var csType = csProtoBundle.ToCSType (use); + // extraProtocolContstraints.Add (new CSGenericConstraint (BindingsCompiler.kGenericSelf, new CSIdentifier (csType.ToString ()))); + // } + } + + parms.Add (MapParameterItem (context, st [i], i, isPinvoke, structsAndEnumsAreAlwaysRefs)); + } + } + return SanitizeParamNames (parms); + } + + public IEnumerable ToConstraintIDs(BaseDeclaration context, IEnumerable types, bool isPinvoke) + { + foreach (var ns in types) { + var cstype = MapType (context, ns, isPinvoke); + yield return new CSIdentifier (cstype.ToString ()); + } + } + + public static bool IsCompoundProtocolListType (SwiftType st) + { + return st is SwiftProtocolListType pt && pt.Protocols.Count > 1; + } + + public static bool IsCompoundProtocolListType (TypeSpec sp) + { + return sp is ProtocolListTypeSpec pl && pl.Protocols.Count > 1; + } + + public NetTypeBundle MapType (SwiftType st, bool isPinvoke, bool isReturnValue = false) + { + if (IsCompoundProtocolListType (st) && !isPinvoke) + throw new NotImplementedException ("Check for a protocol list type first because you need to promote the method to a generic"); + switch (st.Type) { + case CoreCompoundType.Scalar: + return ToScalar ((SwiftBuiltInType)st); + case CoreCompoundType.Tuple: + return ToTuple ((SwiftTupleType)st, isPinvoke); + case CoreCompoundType.MetaClass: + return ToMetaClass ((SwiftMetaClassType)st); + case CoreCompoundType.Class: + if (st.IsStruct) + return ToStruct ((SwiftClassType)st, isPinvoke); + else if (st.IsClass) + return ToClass ((SwiftClassType)st, isPinvoke); + else if (st.IsEnum) + return ToEnum ((SwiftClassType)st, isPinvoke, isReturnValue); + else if (st.IsProtocol) + return ToProtocol ((SwiftClassType)st, isPinvoke); + else + throw new NotImplementedException (); + case CoreCompoundType.ProtocolList: + return ToProtocol ((SwiftProtocolListType)st, isPinvoke); + case CoreCompoundType.BoundGeneric: + return ToBoundGeneric ((SwiftBoundGenericType)st, isPinvoke); + case CoreCompoundType.GenericReference: + return ToGenericReference ((SwiftGenericArgReferenceType)st, isPinvoke); + case CoreCompoundType.Function: + return ToClosure ((SwiftBaseFunctionType)st, isPinvoke, isReturnValue); + default: + throw new NotImplementedException (); + } + } + + public NetTypeBundle MapType (BaseDeclaration context, TypeSpec spec, bool isPinvoke, bool isReturnValue = false, + Tuple selfDepthIndex = null) + { + if (IsCompoundProtocolListType (spec) && !isPinvoke) + throw new NotImplementedException ("Check for a protocol list type first because you need to promote the method to a generic"); + switch (spec.Kind) { + case TypeSpecKind.Named: + var named = (NamedTypeSpec)spec; + if (IsScalar (named.Name)) { + return ToScalar (named.Name, spec.IsInOut); + } + if (context.IsProtocolWithAssociatedTypesFullPath (named, this)) { + if (isPinvoke) { + return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + } else { + var assocType = context.AssociatedTypeDeclarationFromGenericWithFullPath (named, this); + var owningProtocol = context.OwningProtocolFromGenericWithFullPath (named, this); + return new NetTypeBundle (owningProtocol, assocType, false); + } + } else if (context.IsEqualityConstrainedByAssociatedType (named, this)) { + if (isPinvoke) { + return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + } else { + var assocType = context.AssociatedTypeDeclarationFromConstrainedGeneric (named, this); + var owningProtocol = context.OwningProtocolFromConstrainedGeneric (named, this); + return new NetTypeBundle (owningProtocol, assocType, false); + } + } else if (context.IsTypeSpecGeneric (spec) && (!spec.ContainsGenericParameters || isPinvoke)) { + if (context.IsTypeSpecGenericMetatypeReference (spec)) { + return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, spec.IsInOut, EntityType.None); + } else { + if (isPinvoke) { + var isPAT = context.GetConstrainedProtocolWithAssociatedType (named, this) != null; + var isInOut = isPAT ? false : named.IsInOut; + return new NetTypeBundle ("System", "IntPtr", false, isInOut, EntityType.None); + } else { + var depthIndex = context.GetGenericDepthAndIndex (spec); + return new NetTypeBundle (depthIndex.Item1, depthIndex.Item2); + } + } + } else if (context.IsTypeSpecAssociatedType (named)) { + if (isPinvoke) { + return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); + } else { + if (named.ContainsGenericParameters) { + var en = TypeDatabase.EntityForSwiftName (named.Name); + var retval = new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + foreach (var gen in named.GenericParameters) { + var genNtb = MapType (context, gen, isPinvoke, isReturnValue); + retval.GenericTypes.Add (genNtb); + } + return retval; + } else { + var assocType = context.AssociatedTypeDeclarationFromNamedTypeSpec (named); + return new NetTypeBundle (context.AsProtocolOrParentAsProtocol (), assocType, named.IsInOut); + } + } + } + // else if (named.Name == "Self") { + // if (isPinvoke) { + // return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); + // } else { + // return new NetTypeBundle (BindingsCompiler.kGenericSelfName, named.IsInOut); + // } + // } + else { + Entity en = TypeDatabase.EntityForSwiftName (named.Name); + if (en != null) { + if (isPinvoke) { + switch (en.EntityType) { + case EntityType.Class: + case EntityType.Enum: + case EntityType.Tuple: + if (en.IsObjCEnum) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); + case EntityType.TrivialEnum: + return ToTrivialEnumType (en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, spec.IsInOut); + case EntityType.Protocol: + if (en.IsObjCProtocol) { + return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); + } else { + if (spec is ProtocolListTypeSpec protocolList) { + var container = $"SwiftExistentialContainer{protocolList.Protocols.Count}"; + return new NetTypeBundle ("SwiftRuntimeLibrary", container, false, true, EntityType.None); + } else { + return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, true, + EntityType.None); + } + } + case EntityType.Struct: + var protocolListRef = GetBoundProtocolListType (named); + if (protocolListRef != null) { + var container = $"SwiftExistentialContainer{protocolListRef.Protocols.Count}"; + return new NetTypeBundle ("SwiftRuntimeLibrary", container, false, true, EntityType.None); + + } + en = MapToObjCStructOrEnumReference (context, named) ?? en; + if (en.IsObjCStruct || en.IsObjCEnum) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + en = MapToScalarReference (context, named) ?? en; + if (en.EntityType == EntityType.Scalar) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } else { + return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); + } + case EntityType.Scalar: + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + default: + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 21, "Can't happen - shouldn't ever get to this case in type mapping."); + } + } else { + var retval = new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + if (en.EntityType == EntityType.Protocol && en.Type is ProtocolDeclaration proto) { + // if (proto.HasDynamicSelf) { + // if (selfDepthIndex != null) { + // retval.GenericTypes.Add (new NetTypeBundle (selfDepthIndex.Item1, selfDepthIndex.Item2)); + // } else { + // retval.GenericTypes.Add (new NetTypeBundle (BindingsCompiler.kGenericSelfName, spec.IsInOut)); + // } + // } + foreach (var assoc in proto.AssociatedTypes) { + var genMap = new NetTypeBundle (proto, assoc, spec.IsInOut); + retval.GenericTypes.Add (genMap); + } + } else { + foreach (var gen in spec.GenericParameters) { + retval.GenericTypes.Add (MapType (context, gen, isPinvoke)); + } + } + return retval; + } + } else { + if (isPinvoke) { + var namedSpec = spec as NamedTypeSpec; + if (namedSpec != null) { + if (TypeMapper.IsSwiftPointerType (namedSpec.Name)) { + return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + } + } + } + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 0, $"Unable to find C# reference for swift class '{spec.ToString ()}'."); + } + } + case TypeSpecKind.Tuple: + var tuple = (TupleTypeSpec)spec; + if (tuple.Elements.Count == 0) + return NetTypeBundle.Void; + var tupTypes = tuple.Elements.Select (ts => MapType (context, ts, isPinvoke)).ToList (); + return new NetTypeBundle (tupTypes, tuple.IsInOut); + case TypeSpecKind.Closure: + if (isPinvoke) { + return new NetTypeBundle ("SwiftRuntimeLibrary", isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", false, false, EntityType.Closure); + } else { + ClosureTypeSpec ft = spec as ClosureTypeSpec; + var throws = !isPinvoke && ft.Throws; + var arguments = ft.EachArgument().Select (parm => MapType (context, parm, false)).ToList (); + + string delegateName = "Action"; + if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) { + var returnBundle = MapType (context, ft.ReturnType, false, true); + arguments.Add (returnBundle); + delegateName = "Func"; + } + + if (arguments.Count == 0) + return new NetTypeBundle ("System", delegateName, false, false, EntityType.Closure, swiftThrows: throws); + else + return new NetTypeBundle ("System", delegateName, EntityType.Closure, false, arguments, swiftThrows: throws); + } + case TypeSpecKind.ProtocolList: + var pl = (ProtocolListTypeSpec)spec; + return new NetTypeBundle ("SwiftRuntimeLibrary", $"SwiftExistentialContainer{pl.Protocols.Count}", + false, true, EntityType.None); + + default: + throw new NotImplementedException (); + } + } + + bool IsProtocolListTypeReference (BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundProtocolListType (spec); + + return boundType != null; + } + + Entity MapToScalarReference (BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType (spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference (boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName (boundType.Name); + return entity.EntityType == EntityType.Scalar || SwiftType.IsStructScalar (boundType.Name) ? entity : null; + } + + Entity MapToObjCStructOrEnumReference (BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType (spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference (boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName (boundType.Name); + return entity.IsObjCStruct || entity.IsObjCEnum ? entity : null; + } + + TypeSpec ObjCStructOrEnumReferenceType (BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType (spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference (boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName (boundType.Name); + return entity.IsObjCStruct || entity.IsObjCEnum ? boundType : null; + } + + static NamedTypeSpec GetBoundPointerType (NamedTypeSpec spec) + { + if (spec == null) + return null; + if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") + return null; + var boundType = spec.GenericParameters [0] as NamedTypeSpec; + return boundType; + } + + static ProtocolListTypeSpec GetBoundProtocolListType (NamedTypeSpec spec) + { + if (spec == null) + return null; + if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") + return null; + return spec.GenericParameters [0] as ProtocolListTypeSpec; + } + + NetTypeBundle ToTuple (SwiftTupleType tt, bool isPinvoke) + { + if (tt.IsEmpty) + return NetTypeBundle.Void; + if (tt.Contents.Count == 1) { + return MapType (tt.Contents [0], isPinvoke); + } + var lt = tt.Contents.Select (t => MapType (t, isPinvoke)).ToList (); + return new NetTypeBundle (lt, tt.IsReference); + } + + NetTypeBundle ToScalar (SwiftBuiltInType bit) + { + switch (bit.BuiltInType) { + case CoreBuiltInType.Bool: + return ToScalar ("Swift.Bool", bit.IsReference); + case CoreBuiltInType.Double: + return ToScalar ("Swift.Double", bit.IsReference); + case CoreBuiltInType.Float: + return ToScalar ("Swift.Float", bit.IsReference); + case CoreBuiltInType.Int: + return new NetTypeBundle ("System", "nint", true, bit.IsReference, EntityType.Scalar); + case CoreBuiltInType.UInt: + return new NetTypeBundle ("System", "nuint", true, bit.IsReference, EntityType.Scalar); + default: + throw new ArgumentOutOfRangeException (nameof(bit)); + } + } + + static string [] scalarNames = new string [] { + "Swift.Bool", + "Swift.Double", + "Swift.Float", + "Swift.Int", + "Swift.UInt", + "Swift.Int8", + "Swift.UInt8", + "Swift.Int16", + "Swift.UInt16", + "Swift.Int32", + "Swift.UInt32", + "Swift.Int64", + "Swift.UInt64" + }; + + static int ScalarIndex (string builtIn) + { + return Array.IndexOf (scalarNames, builtIn); + } + + public static bool IsScalar (string builtIn) + { + return ScalarIndex (Exceptions.ThrowOnNull (builtIn, "builtIn")) >= 0; + } + + public static bool IsScalar (TypeSpec spec) + { + var ns = spec as NamedTypeSpec; + if (ns == null) + return false; + return ScalarIndex (ns.Name) >= 0; + } + + NetTypeBundle ToScalar (string builtIn, bool isReference) + { + int index = ScalarIndex (builtIn); + if (index >= 0) { + var en = TypeDatabase.EntityForSwiftName (builtIn); + if (en != null) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } + throw new ArgumentOutOfRangeException (nameof(builtIn)); + } + + NetTypeBundle ToMetaClass (SwiftMetaClassType mt) + { + return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, mt.IsReference, EntityType.None); + } + + NetTypeBundle ToClass (SwiftClassType ct, bool isPinvoke) + { + if (isPinvoke) { + return new NetTypeBundle ("System", "IntPtr", false, ct.IsReference, EntityType.None); + } else { + var en = TypeDatabase.EntityForSwiftName (ct.ClassName); + if (en != null) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, ct.IsReference, en.EntityType); + } else { + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 9, $"Unable to find swift class '{ct.ClassName.ToFullyQualifiedName ()}'."); + } + } + } + + NetTypeBundle ToProtocol (SwiftProtocolListType lt, bool isPinvoke) + { + if (lt.Protocols.Count > 1) { + return ToProtocols (lt, isPinvoke); + } + return ToProtocol (lt.Protocols [0], isPinvoke); + } + + NetTypeBundle ToProtocols (SwiftProtocolListType lt, bool isPinvoke) + { + if (!isPinvoke) + throw new NotImplementedException ("If you're not doing a PInvoke, this has to be handled specially"); + return new NetTypeBundle ("SwiftRuntimeLibrary", $"SwiftExistentialContainer{lt.Protocols.Count}", false, true, EntityType.ProtocolList); + } + + NetTypeBundle ToProtocol (SwiftClassType proto, bool isPinvoke) + { + var en = GetEntityForSwiftClassName (proto.ClassName.ToFullyQualifiedName (true)); + if (!en.Type.IsObjC) { + if (isPinvoke) { + return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, isPinvoke || proto.IsReference, + EntityType.None); + } + return ToClass (proto, false); + } else { + return ToClass (proto, isPinvoke); + } + } + + NetTypeBundle ToGenericReference (SwiftGenericArgReferenceType st, bool isPinvoke) + { + if (isPinvoke) { + return NetTypeBundle.IntPtr; + } else { + return new NetTypeBundle (st.Depth, st.Index); + } + } + + NetTypeBundle ToClosure (SwiftBaseFunctionType ft, bool isPinvoke, bool isReturnValue) + { + if (isPinvoke) { + return new NetTypeBundle ("SwiftRuntimeLibrary", + isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", + false, false, EntityType.Closure); + } else { + var arguments = ft.EachParameter.Select (parm => MapType (parm, false)).ToList (); + + string delegateName = "Action"; + if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) { + var returnBundle = MapType (ft.ReturnType, false, true); + arguments.Add (returnBundle); + delegateName = "Func"; + } + + if (arguments.Count == 0) + return new NetTypeBundle ("System", delegateName, false, false, EntityType.Closure); + else + return new NetTypeBundle ("System", delegateName, EntityType.Closure, false, arguments); + } + } + + NetTypeBundle ToBoundGeneric (SwiftBoundGenericType gt, bool isPinvoke) + { + var ct = gt.BaseType as SwiftClassType; + if (ct != null && IsSwiftPointerType (ct.ClassName.ToFullyQualifiedName (true))) { + if (gt.BoundTypes [0] is SwiftClassType boundType) { + var entity = GetEntityForSwiftClassName (boundType.ClassName.ToFullyQualifiedName (true)); + if (entity != null && entity.IsObjCStruct) + return MapType (boundType, isPinvoke); + } + return new NetTypeBundle ("System", "IntPtr", false, gt.IsReference, EntityType.None); + } + + if (isPinvoke) { + return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + } + + var baseType = MapType (ct, false); + var genericTypes = gt.BoundTypes.Select (bt => MapType (bt, false)); + return new NetTypeBundle (baseType.NameSpace, baseType.Type, baseType.Entity, baseType.IsReference, genericTypes); + } + + NetTypeBundle ToStruct (SwiftClassType st, bool isPinvoke) + { + var en = TypeDatabase.EntityForSwiftName (st.ClassName); + if (en != null) { + if (isPinvoke && !SwiftType.IsStructScalar (st)) { + if (en.Type.IsObjC) { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } else { + return NetTypeBundle.IntPtr; + } + } else { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); + } + } else { + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 10, $"Unable to find swift struct '{st.ClassName.ToFullyQualifiedName ()}'."); + } + } + + NetTypeBundle ToEnum (SwiftClassType st, bool isPinvoke, bool isReturnValue) + { + var en = TypeDatabase.EntityForSwiftName (st.ClassName); + if (en == null) { + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 11, $"Unable to find swift enum '{st.ClassName.ToFullyQualifiedName ()}'"); + } + if (en.EntityType == EntityType.TrivialEnum) { + return ToTrivialEnumType (en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, st.IsReference); + } else { + if (isPinvoke) { + return NetTypeBundle.IntPtr; + } else { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); + } + } + } + + public bool TargetPlatformIs64Bit { get; private set; } + + public int MachinePointerSize { get { return TargetPlatformIs64Bit ? 8 : 4; } } + + + bool MustForcePassByReference (Entity en) + { + if (en == null) + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 4, "Null entity."); + // can't big structs, non-blitable structs, or plain enums + if (en.EntityType == EntityType.Scalar) + return false; + return en.IsStructOrEnum || (en.EntityType == EntityType.Protocol && !en.IsObjCProtocol); + } + + public bool MustForcePassByReference (TypeDeclaration decl) + { + var en = TypeDatabase.EntityForSwiftName (decl.ToFullyQualifiedName ()); + if (en == null) + return false; + return MustForcePassByReference (en); + } + + public bool MustForcePassByReference (SwiftType st) + { + if (st is SwiftUnboundGenericType) + return true; + if (st is SwiftGenericArgReferenceType) + return true; + if (st is SwiftBaseFunctionType) + return false; + var protList = st as SwiftProtocolListType; + if (protList != null) { + if (protList.Protocols.Count > 1) + return true; + return MustForcePassByReference (protList.Protocols [0]); + } + var classType = st as SwiftClassType; + if (classType == null) { + SwiftTupleType tuple = st as SwiftTupleType; + if (tuple != null) { + return tuple.Contents.Count > 0; + } + SwiftBuiltInType bit = st as SwiftBuiltInType; + if (bit != null) { + return false; + } + SwiftBoundGenericType bgt = st as SwiftBoundGenericType; + if (bgt == null) + throw new NotImplementedException (); + classType = bgt.BaseType as SwiftClassType; + } + + var en = TypeDatabase.EntityForSwiftName (classType.ClassName); + if (en == null) { + if (!classType.IsClass) { + var module = classType.ClassName.Module.Name; + return !(classType.IsEnum && (module == "__C" || module == "__ObjC")); + } + return false; + } + return MustForcePassByReference (en); + } + + public bool MustForcePassByReference (BaseDeclaration context, TypeSpec sp) + { + if (sp.IsEmptyTuple) + return false; + if (sp is TupleTypeSpec tuple) + return tuple.Elements.Count > 1; + if (sp is ClosureTypeSpec) + return false; + if (sp is ProtocolListTypeSpec protolist) { + if (protolist.Protocols.Count > 1) + return true; + return MustForcePassByReference (context, protolist.Protocols.ElementAt (0).Key); + } + if (context.IsTypeSpecGeneric (sp) && context.IsTypeSpecGenericReference (sp)) + return true; + if (context.IsProtocolWithAssociatedTypesFullPath (sp as NamedTypeSpec, this)) + return true; + if (sp.IsDynamicSelf) + return true; + var en = GetEntityForTypeSpec (sp); + if (en == null) + return false; + if (sp.IsUnboundGeneric (context, this)) + return en.EntityType != EntityType.Class; + return MustForcePassByReference (en); + } + + public TypeSpecToSLType TypeSpecMapper { get { return specMapper; } } + public TypeSpecToSLType OverrideTypeSpecMapper { get { return overrideSpecMapper; } } + public SwiftTypeToSLType SwiftTypeMapper { get { return swiftTypeMapper; } } + + public static bool IsSwiftPointerType (string fullTypeName) + { + return fullTypeName == "Swift.UnsafePointer" || fullTypeName == "Swift.UnsafeMutablePointer" + || fullTypeName == "Swift.UnsafeRawPointer" || fullTypeName == "Swift.UnsafeMutableRawPointer"; + } + + static NetTypeBundle ToTrivialEnumType (Entity en, EnumDeclaration decl, bool isPinvoke, bool isReturnValue, bool isReference) + { + if (decl.HasRawType) { + if (decl.RawTypeName == "Swift.Int" || decl.RawTypeName == "Swift.UInt") { + return new NetTypeBundle ("System", decl.RawTypeName == "Swift.Int" ? "nint" : "nuint", false, false, EntityType.None); + } else { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } else { + if (isPinvoke) { + if (isReturnValue) { + var enType = en.Type as EnumDeclaration; + if (enType.IsTrivial && !enType.HasRawType) { + if (enType.Elements.Count < 256) + return new NetTypeBundle ("System", "byte", false, false, EntityType.None); + else if (enType.Elements.Count < 65536) { + return new NetTypeBundle ("System", "ushort", false, false, EntityType.None); + } + } + } + return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); + } else { + return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } + } + } +} + diff --git a/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs b/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs new file mode 100644 index 000000000000..8ea5691ce834 --- /dev/null +++ b/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo.SwiftLang; +using System.Collections.Generic; +using SwiftReflector.SwiftXmlReflection; +using System.Linq; +using SwiftReflector.ExceptionTools; +using SyntaxDynamo; + +namespace SwiftReflector.TypeMapping { + public class TypeSpecToSLType { + TypeMapper parent; + bool isForOverride; + public TypeSpecToSLType (TypeMapper parent, bool forOverride) + { + this.parent = Exceptions.ThrowOnNull (parent, nameof (parent)); + isForOverride = forOverride; + } + + public SLType MapTypeSimplified (SLImportModules modules, TypeSpec spec) + { + switch (spec.Kind) { + case TypeSpecKind.Named: + var named = (NamedTypeSpec)spec; + if (TypeSpec.IsBuiltInValueType (spec)) { + return new SLSimpleType (named.Name); + } else { + return new SLSimpleType ("UnsafeRawPointer"); + } + case TypeSpecKind.Closure: + case TypeSpecKind.Tuple: + case TypeSpecKind.ProtocolList: + return new SLSimpleType ("UnsafeRawPointer"); + default: + throw new ArgumentOutOfRangeException ("spec"); + } + } + + public SLType MapType (BaseDeclaration declContext, SLImportModules modules, TypeSpec spec, bool isForReturn) + { + switch (spec.Kind) { + case TypeSpecKind.Named: + return MapType (declContext, modules, (NamedTypeSpec)spec); + case TypeSpecKind.Closure: + return MapType (declContext, modules, (ClosureTypeSpec)spec, isForReturn); + case TypeSpecKind.Tuple: + return MapType (declContext, modules, (TupleTypeSpec)spec); + case TypeSpecKind.ProtocolList: + return MapType (declContext, modules, (ProtocolListTypeSpec)spec); + default: + throw new ArgumentOutOfRangeException ("spec"); + } + } + + SLType MapType (BaseDeclaration declContext, SLImportModules modules, NamedTypeSpec spec) + { + SLType retval = null; + if (spec.HasModule (declContext, this.parent)) + modules.AddIfNotPresent (spec.Module); + if (declContext.IsTypeSpecGeneric (spec) && !spec.ContainsGenericParameters) { + Tuple depthIndex = declContext.GetGenericDepthAndIndex (spec); + retval = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); + } else if (spec.ContainsGenericParameters) { + retval = new SLBoundGenericType (spec.NameWithoutModule, spec.GenericParameters.Select (p => MapType (declContext, modules, p, false))); + } else { + if (declContext.IsProtocolWithAssociatedTypesFullPath (spec, parent)) { + // for T.AssocType + var genPart = spec.Module; + var depthIndex = declContext.GetGenericDepthAndIndex (genPart); + var newGenPart = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); + retval = new SLSimpleType ($"{newGenPart}.{spec.NameWithoutModule}"); + } else { + retval = new SLSimpleType (spec.NameWithoutModule); + } + } + + if (spec.InnerType == null) + return retval; + else + return new SLCompoundType (retval, MapType (declContext, modules, spec.InnerType)); + } + + SLType MapType (BaseDeclaration declContext, SLImportModules modules, ClosureTypeSpec spec, bool isForReturn) + { + var argumentTypes = new List (); + if (spec.Arguments is TupleTypeSpec) { + argumentTypes.AddRange (((TupleTypeSpec)spec.Arguments).Elements.Select (arg => MapType (declContext, modules, arg, false))); + } else { + argumentTypes.Add (MapType (declContext, modules, spec.Arguments, false)); + } + + + SLFuncType funcType = null; + if (isForOverride) { + var arguments = new SLTupleType (argumentTypes.Select (at => new SLNameTypePair ((string)null, at)).ToList ()); + if (spec.ReturnType.IsEmptyTuple) { + // Action -> + funcType = new SLFuncType (arguments ?? new SLTupleType (), new SLTupleType (), hasThrows: spec.Throws); + } else { + // Func + SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); + funcType = new SLFuncType (arguments ?? new SLTupleType (), slRetType, hasThrows: spec.Throws); + } + if (spec.IsEscaping) { + SLAttribute.Escaping ().AttachBefore (funcType); + } + } else if (isForReturn) { + var arguments = argumentTypes.Select (at => new SLNameTypePair ("_", at)).ToList (); + + if (spec.ReturnType.IsEmptyTuple) { + // Action -> + // (UnsafeMutablePointer<(argumentTypes)>) -> () + var pointerToArgTuple = arguments.Count != 0 ? + new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) + : null; + if (pointerToArgTuple != null) { + funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", pointerToArgTuple)), + new SLTupleType ()); + } else { // should never happen? + funcType = new SLFuncType (new SLTupleType (), new SLTupleType ()); + } + } else { + // Func + // (UnsafeMutablePointer,UnsafeMutablePointer<(argumentTypes)>) -> () + SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); + var pointerToArgTuple = arguments.Count != 0 ? + new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) + : null; + SLType returnSLType = null; + if (spec.Throws && !spec.IsAsync) { + var returnTuple = new SLTupleType (new SLNameTypePair ((string)null, slRetType), + new SLNameTypePair ((string)null, new SLSimpleType ("Swift.Error")), + new SLNameTypePair ((string)null, SLSimpleType.Bool)); + returnSLType = new SLBoundGenericType ("UnsafeMutablePointer", returnTuple); + } else if (spec.IsAsync) { + throw new NotImplementedException ("Not handling async return closure mapping (yet)"); + } else { + returnSLType = new SLBoundGenericType ("UnsafeMutablePointer", slRetType); + } + + if (pointerToArgTuple != null) { + funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", returnSLType), + new SLNameTypePair ("_", pointerToArgTuple)), new SLTupleType ()); + } else { + funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", returnSLType)), + new SLTupleType ()); + } + } + } else { + var arguments = argumentTypes.Select (at => new SLNameTypePair ("_", at)).ToList (); + var opaquePointerArg = new SLNameTypePair ("_", SLSimpleType.OpaquePointer); + + if (spec.ReturnType.IsEmptyTuple) { + // Action -> + // (UnsafeMutablePointer<(argumentTypes)>, OpaquePointer) -> () + var pointerToArgTuple = arguments.Count != 0 ? + new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) + : null; + if (pointerToArgTuple != null) { + funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", pointerToArgTuple), opaquePointerArg), + new SLTupleType ()); + } else { // should never happen? + funcType = new SLFuncType (new SLTupleType (opaquePointerArg), new SLTupleType ()); + } + + } else { + // Func + // (UnsafeMutablePointer,UnsafeMutablePointer<(argumentTypes)>) -> () + // SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); + // var pointerToArgTuple = arguments.Count != 0 ? + // new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) + // : null; + // var slReturnTypePtr = MethodWrapping.ClosureReturnType (slRetType, spec); + // if (pointerToArgTuple != null) { + // funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", slReturnTypePtr), + // new SLNameTypePair ("_", pointerToArgTuple), + // opaquePointerArg), + // new SLTupleType ()); + // } else { + // funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", slReturnTypePtr), + // opaquePointerArg), + // new SLTupleType ()); + // } + } + + if (!isForReturn) { + funcType.Attributes.Add (new SLAttribute ("escaping", null)); + } + } + + + return funcType; + } + + SLType MapType (BaseDeclaration declContext, SLImportModules modules, TupleTypeSpec spec) + { + return new SLTupleType (spec.Elements.Select (p => new SLNameTypePair ((string)null, MapType (declContext, modules, p, false))).ToList ()); + } + + SLType MapType (BaseDeclaration declContext, SLImportModules modules, ProtocolListTypeSpec spec) + { + return new SLProtocolListType (spec.Protocols.Keys.Select (proto => MapType (declContext, modules, proto))); + } + + public void MapParams (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, List output, List parameters, + bool dontChangeInOut, SLGenericTypeDeclarationCollection genericDeclaration = null, bool remapSelf = false, string selfReplacement = "") + { + output.AddRange (parameters.Select ((p, i) => ToParameter (typeMapper, func, modules, p, i, dontChangeInOut, genericDeclaration, remapSelf, selfReplacement))); + } + + public void MapParamsToCSharpTypes (SLImportModules modules, List output, List parameters) + { + output.AddRange (parameters.Select ((p, i) => ToParameterToCSharpTypes (modules, p, i))); + } + + SLParameter ToParameterToCSharpTypes (SLImportModules modules, ParameterItem p, int index) + { + return new SLParameter (p.PublicName, p.PrivateName, MapTypeSimplified (modules, p.TypeSpec), + p.IsInOut && TypeSpec.IsBuiltInValueType (p.TypeSpec) ? SLParameterKind.InOut : SLParameterKind.None); + } + + public SLParameter ToParameter (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, ParameterItem p, int index, + bool dontChangeInOut, SLGenericTypeDeclarationCollection genericDecl = null, bool remapSelf = false, string remappedSelfName = "") + { + var pIsGeneric = func.IsTypeSpecGeneric (p) && p.TypeSpec is NamedTypeSpec; + var parmTypeEntity = !pIsGeneric ? typeMapper.GetEntityForTypeSpec (p.TypeSpec) : null; + if (parmTypeEntity == null && !pIsGeneric && p.IsInOut) + throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 45, $"In function {func.ToFullyQualifiedName ()}, unknown type parameter type {p.PublicName}:{p.TypeName}."); + var parmKind = p.IsInOut && (pIsGeneric || !parmTypeEntity.IsStructOrEnum) ? SLParameterKind.InOut : SLParameterKind.None; + SLType parmType = null; + + var pTypeSpec = remapSelf ? p.TypeSpec.ReplaceName ("Self", remappedSelfName) : p.TypeSpec; + + if (genericDecl != null) { + GatherGenerics (typeMapper, func, modules, pTypeSpec, genericDecl); + } + if (pIsGeneric) { + if (pTypeSpec.ContainsGenericParameters) { + var ns = pTypeSpec as NamedTypeSpec; + var boundGen = new SLBoundGenericType (ns.Name, + pTypeSpec.GenericParameters.Select (genParm => { + return MapType (func, modules, genParm, true); + })); + if (parent.MustForcePassByReference (func, ns)) { + boundGen = new SLBoundGenericType ("UnsafeMutablePointer", boundGen); + } + parmType = boundGen; + } else { + var namedType = pTypeSpec as NamedTypeSpec; + if (namedType == null) + throw new NotImplementedException ("Can only have a named type spec here."); + var depthIndex = func.GetGenericDepthAndIndex (namedType.Name); + var gd = func.GetGeneric (depthIndex.Item1, depthIndex.Item2); + var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2, func.IsTypeSpecGenericMetatypeReference (namedType)); + parmType = genRef; + } + } else { + parmType = MapType (func, modules, pTypeSpec, false); + if (pIsGeneric) { + Tuple depthIndex = func.GetGenericDepthAndIndex (pTypeSpec); + parmType = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); + } else if (parent.MustForcePassByReference (func, pTypeSpec) && !dontChangeInOut) { + parmType = new SLBoundGenericType (p.IsInOut ? "UnsafeMutablePointer" : "UnsafePointer", parmType); + } + } + if (isForOverride && p.IsVariadic) { + // if we get here, then parmType is an SLSimpleType of SwiftArray + // we're going to turn it into "someType ..." + var oldParmType = parmType as SLBoundGenericType; + parmType = new SLVariadicType (oldParmType.BoundTypes [0]); + } + var publicName = !p.NameIsRequired ? null : ConjureIdentifier (p.PublicName, index); + var privateName = !String.IsNullOrEmpty (p.PrivateName) ? p.PrivateName : null; + return new SLParameter (publicName, ConjureIdentifier (privateName, index), parmType, parmKind); + } + + + void GatherGenerics (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type, + SLGenericTypeDeclarationCollection genericDeclations) + { + var redundantConstraints = new Dictionary> (); + GatherGenerics (typeMapper, func, modules, type, genericDeclations, redundantConstraints); + + // In the process of gathering generics, there may be generic types with + // constraints that are redundant. In the process of gathering the generics, I + // collect all the generic reference types that have constraints that would be + // considered redundant. + // After gathering, all constraints are looked up and if they're redundant, they get removed. + + foreach (var generic in genericDeclations) { + var genericName = generic.Name.Name; + List forbiddenList = null; + if (!redundantConstraints.TryGetValue (genericName, out forbiddenList)) + continue; + for (int i = generic.Constraints.Count - 1; i >= 0; i--) { + var candidateConstraint = generic.Constraints [i]; + foreach (var forbidden in forbiddenList) { + var forbiddenInherit = forbidden as InheritanceConstraint; + if (candidateConstraint.IsInheritance && forbidden != null) { + var candidateString = candidateConstraint.SecondType.ToString (); + var forbiddenNamedTypeSpec = forbiddenInherit.InheritsTypeSpec as NamedTypeSpec; + if (forbiddenNamedTypeSpec == null) + continue; + var verbottenString = forbiddenNamedTypeSpec.NameWithoutModule; + if (candidateString == verbottenString) { + generic.Constraints.RemoveAt (i); + break; + } + } + } + } + } + } + + void GatherGenerics (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type, + SLGenericTypeDeclarationCollection genericDecl, Dictionary> redundantConstraints) + { + if (!func.IsTypeSpecGeneric (type)) + return; + + if (type.ContainsGenericParameters) { + var entity = typeMapper.GetEntityForTypeSpec (type); + if (entity != null) { + for (int i = 0; i < entity.Type.Generics.Count; i++) { + var genDecl = entity.Type.Generics [i]; + var originalGenTypeSpec = type.GenericParameters [i]; + if (originalGenTypeSpec is NamedTypeSpec named) { + var depthIndex = func.GetGenericDepthAndIndex (originalGenTypeSpec); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + continue; + var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); + var genRefName = genRef.Name; + List constList = null; + if (!redundantConstraints.TryGetValue (genRefName, out constList)) { + constList = new List (); + redundantConstraints.Add (genRefName, constList); + } + constList.AddRange (genDecl.Constraints); + } else if (originalGenTypeSpec is ClosureTypeSpec closure) { + GatherGenerics (typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints); + GatherGenerics (typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints); + } else if (originalGenTypeSpec is TupleTypeSpec tuple) { + foreach (var tupleSpec in tuple.Elements) { + GatherGenerics (typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints); + } + } + } + } + foreach (var subType in type.GenericParameters) + GatherGenerics (typeMapper, func, modules, subType, genericDecl, redundantConstraints); + } else { +// if (type is NamedTypeSpec named) { +// var depthIndex = func.GetGenericDepthAndIndex (type); +// var gd = func.GetGeneric (depthIndex.Item1, depthIndex.Item2); +// var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); +// var sldecl = new SLGenericTypeDeclaration (new SLIdentifier (genRef.Name)); +// #if SWIFT4 +// if (depthIndex.Item1 >= func.GetMaxDepth ()) { +// sldecl.Constraints.AddRange (gd.Constraints.Select (baseConstraint => +// MethodWrapping.ToSLGenericConstraint (func, baseConstraint, genRef.ToString ()) +// )); +// } +// #else +// sldecl.Constraints.AddRange (gd.Constraints.Select (bc => { +// InheritanceConstraint inh = bc as InheritanceConstraint; +// if (inh == null) +// throw new CompilerException ("Equality constraints not supported (yet)"); +// return new SLGenericConstraint (true, new SLSimpleType (genRef.Name), parent.TypeSpecMapper.MapType (func, modules, inh.InheritsTypeSpec)); +// })); +// #endif +// genericDecl.Add (sldecl); +// } else if (type is ClosureTypeSpec closure) { +// GatherGenerics (typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints); +// GatherGenerics (typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints); +// } else if (type is TupleTypeSpec tuple) { +// foreach (var tupleSpec in tuple.Elements) { +// GatherGenerics (typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints); +// } +// } + } + } + + public static SLIdentifier ConjureIdentifier (string name, int index) + { + name = name ?? $"xamarin_anonymous_parameter{index}"; + + return new SLIdentifier (name); + } + } +} + diff --git a/src/SwiftReflector/UnicodeMapper.cs b/src/SwiftReflector/UnicodeMapper.cs new file mode 100644 index 000000000000..8e249ff34e6f --- /dev/null +++ b/src/SwiftReflector/UnicodeMapper.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Xml.Linq; + +namespace SwiftReflector { + public sealed class UnicodeMapper { + + static Dictionary DefaultMapping = new Dictionary { + { "\x03b1", "Alpha" }, + { "\x03b2", "Beta" }, + { "\x03b3", "Gamma" }, + { "\x03b4", "Delta" }, + { "\x03b5", "Epsilon" }, + { "𝑒", "LittleEpsilon"}, + { "Π", "BigPi"}, + { "\x03c0", "Pi" }, + { "𝝉", "Tau"}, + { "\x03c4", "Tau" }, + { "\x00ac", "Not" }, + { "\x2227", "And" }, + { "\x2228", "Or" }, + { "\x22bb", "Xor" }, + { "\x2295", "CirclePlus" }, + { "\x21ae", "NotLeftRightArrow" }, + { "\x2262", "NotIdentical" }, + { "\x22bc", "Nand" }, + { "\x2191", "UpArrow" }, + { "\x22bd", "Nor" }, + { "\x2193", "DownArrow" }, + { "\x22a6", "Assertion" }, + { "\x00f7", "Division" }, + { "\x00d7", "Multiplication" }, + { "\x221a", "SquareRoot" }, + { "\x221b", "CubeRoot" }, + { "\x00b1", "PlusOrMinus" }, + { "\x2213", "MinusOrPlus" }, + { "\x2224", "DoesNotDivide" }, + { "\x2208", "ElementOf" }, + { "\x220c", "NotElementOf" }, + { "\x2229", "Intersection" }, + { "\x222a", "Union" }, + { "\x2286", "Subset" }, + { "\x2282", "ProperSubset" }, + { "\x2284", "NotSubset" }, + { "\x2287", "Superset" }, + { "\x2283", "ProperSuperset" }, + { "\x2285", "NotSuperset" }, + { "\x2264", "LessThanOrEqualTo" }, + { "\x2265", "GreaterThanOrEqualTo" }, + { "\x226c", "Between" }, + { "\x2248", "Approximates" }, + { "\x2218", "Ring" }, + }; + + public static UnicodeMapper Default = new UnicodeMapper (); + + Dictionary mapping; + + public UnicodeMapper () + { + mapping = DefaultMapping; + } + + // While this takes a string, it should be one 'character', possibly made up of multiple + // parts, like 🍎 + public string MapToUnicodeName (string s) + { + if (new StringInfo (s).LengthInTextElements != 1) + throw new ArgumentOutOfRangeException (nameof (s)); + + if (mapping.TryGetValue (s, out var result)) + return result; + + StringBuilder stringBuilder = new StringBuilder ().Append ("U"); + + var encoding = Encoding.UTF32; + var bytes = encoding.GetBytes (s); + var utf32Value = BitConverter.ToUInt32 (bytes, 0); + if (utf32Value > 0xffff) + stringBuilder.Append ($"{utf32Value:X8}"); + else + stringBuilder.Append ($"{utf32Value:X4}"); + + return stringBuilder.ToString (); + } + + public void AddMappingsFromFile (string fileName) + { + AddMappingsFromXML (File.ReadAllText (fileName)); + } + + public void AddMappingsFromXML (string mappingXML) + { + if (mapping == DefaultMapping) { + // Clone the default mapping, since we don't want to modify it. + mapping = new Dictionary (mapping); + } + foreach (var m in ReadMappings (mappingXML)) + mapping [m.Item1] = m.Item2; + } + + static IEnumerable> ReadMappings (string mappingXML) + { + XDocument xmlDocument = XDocument.Parse (mappingXML); + foreach (var mapping in xmlDocument.Descendants ("map")) + { + string from = mapping.Attribute (XName.Get ("from"))?.Value; + string to = mapping.Attribute (XName.Get ("to"))?.Value; + + if (from != null && to != null) + yield return new Tuple (from, to); + } + } + } +} diff --git a/src/SwiftReflector/ValueWitnessTable.cs b/src/SwiftReflector/ValueWitnessTable.cs new file mode 100644 index 000000000000..217889d0c005 --- /dev/null +++ b/src/SwiftReflector/ValueWitnessTable.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using SwiftReflector.ExceptionTools; +using SwiftReflector.Demangling; + +namespace SwiftReflector { + public class ValueWitnessTable { + // #define FOR_ALL_FUNCTION_VALUE_WITNESSES(MACRO) \ + // MACRO(destroyBuffer) \ + // MACRO(initializeBufferWithCopyOfBuffer) \ + // MACRO(projectBuffer) \ + // MACRO(deallocateBuffer) \ + // MACRO(destroy) \ + // MACRO(initializeBufferWithCopy) \ + // MACRO(initializeWithCopy) \ + // MACRO(assignWithCopy) \ + // MACRO(initializeBufferWithTake) \ + // MACRO(initializeWithTake) \ + // MACRO(assignWithTake) \ + // MACRO(allocateBuffer) \ + // MACRO(initializeBufferWithTakeOfBuffer) \ + // MACRO(destroyArray) \ + // MACRO(initializeArrayWithCopy) \ + // MACRO(initializeArrayWithTakeFrontToBack) \ + // MACRO(initializeArrayWithTakeBackToFront) + public long DestroyBufferOffset { get; private set; } + public long InitializeBufferWithCopyOfBufferOffset { get; private set; } + public long ProjectBufferOffset { get; private set; } + public long DeallocateBufferOffset { get; private set; } + public long DestroyOffset { get; private set; } + public long InitializeBufferWithCopyOffset { get; private set; } + public long InitializeWithCopyOffset { get; private set; } + public long AssignWithCopyOffset { get; private set; } + public long InitializeBufferWithTakeOffset { get; private set; } + public long InitializeWithTakeOffset { get; private set; } + public long AssignWithTakeOffset { get; private set; } + public long AllocateBufferOffset { get; private set; } + public long InitializeBufferWithTakeOfBufferOffset { get; private set; } + public long DestroyArrayOffset { get; private set; } + public long InitializeArrayWithCopyOffset { get; private set; } + public long InitializeArrayWithTakeFrontToBackOffset { get; private set; } + public long InitializeArrayWithTakeBackToFrontOffset { get; private set; } + public long Size { get; private set; } + public ushort Flags { get; private set; } + public ushort Log2Stride { get; private set; } + public long Stride { get; private set; } + public string MangledName { get; private set; } + + ValueWitnessTable () + { + } + + public static ValueWitnessTable FromStream (Stream stm, TLFunction tlf, int sizeofMachinePointer) + { + if (sizeofMachinePointer != 4 && sizeofMachinePointer != 8) { + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 14, $"Expected a maching pointer size of either 4 or 8, but got {sizeofMachinePointer}"); + } + var wit = tlf.Signature as SwiftWitnessTableType; + if (wit == null || wit.WitnessType != WitnessType.Value) + throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 15, $"Expected a SwiftWitnessTable, but got {tlf.Signature.GetType ().Name}."); + var reader = new BinaryReader (stm); + reader.BaseStream.Seek ((long)tlf.Offset, SeekOrigin.Begin); + + var table = new ValueWitnessTable (); + table.MangledName = tlf.MangledName; + if (sizeofMachinePointer == 4) + table.Read32 (reader); + else + table.Read64 (reader); + return table; + } + + void Read32 (BinaryReader reader) + { + DestroyBufferOffset = reader.ReadInt32 (); + InitializeBufferWithCopyOfBufferOffset = reader.ReadInt32 (); + ProjectBufferOffset = reader.ReadInt32 (); + DeallocateBufferOffset = reader.ReadInt32 (); + DestroyOffset = reader.ReadInt32 (); + InitializeBufferWithCopyOffset = reader.ReadInt32 (); + InitializeWithCopyOffset = reader.ReadInt32 (); + AssignWithCopyOffset = reader.ReadInt32 (); + InitializeBufferWithTakeOffset = reader.ReadInt32 (); + InitializeWithTakeOffset = reader.ReadInt32 (); + AssignWithTakeOffset = reader.ReadInt32 (); + AllocateBufferOffset = reader.ReadInt32 (); + InitializeBufferWithTakeOfBufferOffset = reader.ReadInt32 (); + DestroyArrayOffset = reader.ReadInt32 (); + InitializeArrayWithCopyOffset = reader.ReadInt32 (); + InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt32 (); + InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt32 (); + Size = reader.ReadInt32 (); + Flags = reader.ReadUInt16 (); + Log2Stride = reader.ReadUInt16 (); + Stride = reader.ReadInt32 (); + } + + void Read64 (BinaryReader reader) + { + DestroyBufferOffset = reader.ReadInt64 (); + InitializeBufferWithCopyOfBufferOffset = reader.ReadInt64 (); + ProjectBufferOffset = reader.ReadInt64 (); + DeallocateBufferOffset = reader.ReadInt64 (); + DestroyOffset = reader.ReadInt64 (); + InitializeBufferWithCopyOffset = reader.ReadInt64 (); + InitializeWithCopyOffset = reader.ReadInt64 (); + AssignWithCopyOffset = reader.ReadInt64 (); + InitializeBufferWithTakeOffset = reader.ReadInt64 (); + InitializeWithTakeOffset = reader.ReadInt64 (); + AssignWithTakeOffset = reader.ReadInt64 (); + AllocateBufferOffset = reader.ReadInt64 (); + InitializeBufferWithTakeOfBufferOffset = reader.ReadInt64 (); + DestroyArrayOffset = reader.ReadInt64 (); + InitializeArrayWithCopyOffset = reader.ReadInt64 (); + InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt64 (); + InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt64 (); + Size = reader.ReadInt64 (); + reader.ReadInt32 (); + Flags = reader.ReadUInt16 (); + Log2Stride = reader.ReadUInt16 (); + Stride = reader.ReadInt64 (); + } + } +} + diff --git a/src/SwiftReflector/XmlToTLFunctionMapper.cs b/src/SwiftReflector/XmlToTLFunctionMapper.cs new file mode 100644 index 000000000000..38fbaa71ef1d --- /dev/null +++ b/src/SwiftReflector/XmlToTLFunctionMapper.cs @@ -0,0 +1,489 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.Inventory; +using System.Collections.Generic; +using System.Linq; +using SwiftReflector.Demangling; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector { + public class XmlToTLFunctionMapper { + public static TLFunction ToProtocolFactory (string swiftProxyFactoryName, ModuleDeclaration modDecl, ModuleContents contents, TypeMapper typeMap) + { + var swiftProxyFunctionDecl = modDecl.TopLevelFunctions.Where (fn => fn.Name == swiftProxyFactoryName).FirstOrDefault (); + if (swiftProxyFunctionDecl == null) + return null; + return ToTLFunction (swiftProxyFunctionDecl, contents, typeMap); + } + + public static TLFunction ToTLFunction (FunctionDeclaration decl, ModuleContents contents, TypeMapper typeMap) + { + string nameToSearch = GetNameToSearchOn (decl); + var funcs = FuncsToSearch (contents, decl, nameToSearch); + return MatchFunctionDecl (decl, funcs, typeMap); + } + + public static TLFunction ToTLFunction (FunctionDeclaration decl, ModuleInventory mi, TypeMapper typeMap) + { + var scn = ToSwiftClassName (decl); + var contents = mi.Values.FirstOrDefault (mc => mc.Name.Equals (scn.Module)); + if (contents == null) + return null; + return ToTLFunction (decl, contents, typeMap); + } + + public static TLFunction ToTLFunction (FunctionDeclaration decl, ClassContents classContents, TypeMapper typeMap) + { + string name = decl.IsProperty ? decl.PropertyName : decl.Name; + var funcsToSearch = FuncsToSearch (classContents, decl, name);//decl.ParameterLists.Count == 2 ? classContents.Methods.MethodsWithName (decl.Name) + //: classContents.StaticFunctions.MethodsWithName (decl.Name); + return MatchFunctionDecl (decl, funcsToSearch, typeMap); + } + + static List FuncsToSearch (ModuleContents contents, FunctionDeclaration decl, string name) + { + + List funcs = null; + if (decl.Parent == null) { // top level + if (decl.IsProperty) { + funcs = contents.Functions.MethodsWithName (name).Where (tlf => tlf.Signature is SwiftPropertyType).ToList (); + } else { + funcs = contents.Functions.MethodsWithName (name).Where (tlf => !(tlf.Signature is SwiftPropertyType)).ToList (); + } + } else { + var cn = ToSwiftClassName (decl); + var theClass = LocateClassContents (contents, cn); + funcs = FuncsToSearch (theClass, decl, name); + } + return funcs; + } + + static List FuncsToSearch (ClassContents theClass, FunctionDeclaration decl, string name) + { + List funcs = null; + + if (theClass == null) { + funcs = new List (); + } else { + if (decl.IsProperty) { + funcs = new List (); + if (decl.IsSubscript) { + funcs.AddRange (theClass.Subscripts); + } else { + foreach (var pc in theClass.AllPropertiesWithName(name)) { + var propType = pc.TLFGetter.Signature as SwiftPropertyType; + if (propType == null) // should never happen, but... + continue; + if (propType.IsStatic != decl.IsStatic) + continue; + if (decl.IsGetter) + funcs.Add (pc.TLFGetter); + else if (decl.IsSetter && pc.TLFSetter != null) + funcs.Add (pc.TLFSetter); + else if (decl.IsMaterializer && pc.TLFMaterializer != null) + funcs.Add (pc.TLFMaterializer); + } + } + } else if (decl.IsConstructor) { + funcs = theClass.Constructors.AllocatingConstructors (); + } else if (decl.IsDestructor) { + funcs = theClass.Destructors.DeallocatingDestructors (); + } else { + if (decl.IsStatic) + funcs = theClass.StaticFunctions.MethodsWithName (name); + else + funcs = theClass.Methods.MethodsWithName (name); + } + } + return funcs; + } + + static string GetNameToSearchOn (FunctionDeclaration decl) + { + if (!decl.IsProperty) + return decl.Name; + if (decl.IsGetter) + return decl.Name.Substring (FunctionDeclaration.kPropertyGetterPrefix.Length); + else if (decl.IsSetter) + return decl.Name.Substring (FunctionDeclaration.kPropertySetterPrefix.Length); + else if (decl.IsMaterializer) + return decl.Name.Substring (FunctionDeclaration.kPropertyMaterializerPrefix.Length); + else + throw new ArgumentOutOfRangeException ("decl", "Expected getter or setter but got something else?"); + } + + public static ClassContents LocateClassContents (ModuleContents contents, SwiftClassName cn) + { + return contents.Classes.Values.FirstOrDefault (cc => cc.Name.Equals (cn)); + } + + public static ClassContents LocateClassContents (ModuleInventory modInventory, SwiftClassName className) + { + var contents = modInventory.Values.FirstOrDefault (mod => mod.Name.Equals (className.Module)); + if (contents == null) + return null; + return LocateClassContents (contents, className); + } + + public static ProtocolContents LocateProtocolContents (ModuleContents contents, SwiftClassName cn) + { + return contents.Protocols.Values.FirstOrDefault (cc => cc.Name.Equals (cn)); + } + + public static ProtocolContents LocateProtocolContents (ModuleInventory modInventory, SwiftClassName className) + { + var contents = modInventory.Values.FirstOrDefault (mod => mod.Name.Equals (className.Module)); + if (contents == null) + return null; + return LocateProtocolContents (contents, className); + } + + + + public static SwiftClassName ToSwiftClassName (BaseDeclaration bdl, string suffix = null) + { + var nesting = new List (); + var names = new List (); + var walker = bdl; + do { + if (IsNestable (walker)) { + nesting.Insert (0, ToMemberNesting (walker)); + names.Insert (0, new SwiftName (walker.Name + (walker == bdl && suffix != null ? suffix : ""), false)); + } + walker = walker.Parent; + } while (walker != null); + return new SwiftClassName (new SwiftName (bdl.Module.Name, false), nesting, names); + } + + static bool IsNestable (BaseDeclaration bdl) + { + return bdl is ClassDeclaration || bdl is StructDeclaration + || bdl is EnumDeclaration + ; + } + + static MemberNesting ToMemberNesting (BaseDeclaration decl) + { + // Don't reorder - a ProtocolDeclaration is a ClassDeclaration (for now) + if (decl is ProtocolDeclaration) { + return MemberNesting.Protocol; + } + if (decl is ClassDeclaration) { + return MemberNesting.Class; + } + if (decl is StructDeclaration) { + return MemberNesting.Struct; + } + if (decl is EnumDeclaration) { + return MemberNesting.Enum; + } + throw new ArgumentOutOfRangeException ("decl", String.Format ("unknown class entity type {0}", decl.GetType ().Name)); + } + + static TLFunction MatchFunctionDecl (FunctionDeclaration decl, List funcs, TypeMapper typeMap) + { + if (decl.Parent == null) + funcs = funcs.Where (fn => fn.IsTopLevelFunction).ToList (); + else + funcs = funcs.Where (fn => !fn.IsTopLevelFunction).ToList (); + + foreach (var func in funcs) { + if (SignaturesMatch (decl, func, typeMap)) + return func; + } + return null; + } + + + static bool SignaturesMatch (FunctionDeclaration decl, TLFunction func, TypeMapper typeMap) + { + if (decl.IsConstructor && !(func.Signature is SwiftConstructorType) || + (!decl.IsConstructor && func.Signature is SwiftConstructorType)) + return false; + List significantParameterList = decl.ParameterLists.Last (); + if (decl.ParameterLists.Count > 1 && !decl.IsStatic) { + var ucf = func.Signature as SwiftUncurriedFunctionType; + if (ucf == null) + return false; + + var uncurriedParameter = ucf.UncurriedParameter; + var uncurriedTuple = uncurriedParameter as SwiftTupleType; + + // the !decl.IsConstructor is because the uncurried parameter in a constructor comes out + // "funny" in XmlReflection and won't match + if ((decl.Parent == null || !(decl.Parent is StructDeclaration)) && !decl.IsConstructor) { + if (decl.ParameterLists [0].Count == 1) { + if (!TypeMatches (decl, decl.ParameterLists [0] [0], uncurriedParameter, false, typeMap)) + return false; + } else if (decl.ParameterLists [0].Count == 0) { + if (uncurriedTuple == null || !uncurriedTuple.IsEmpty) + return false; + } else { + if (uncurriedTuple == null || !TypeMatches (decl, decl.ParameterLists [0], uncurriedTuple, typeMap)) + return false; + } + } + } + + // return is implied in constructor - we're good on that, thanks + bool dontMatchReturn = decl.IsConstructor; + + if (func.Signature.ParameterCount == significantParameterList.Count) { + if (func.Signature.ParameterCount == 0) + return dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); + if (func.Signature.ParameterCount == 1) { + var tuple = func.Signature.Parameters as SwiftTupleType; + var argsMatch = TypeMatches (decl, significantParameterList [0], tuple != null ? tuple.Contents [0] : func.Signature.Parameters, decl.IsSetter, typeMap); + var returnMatches = (dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); + return argsMatch && returnMatches; + } else { + var argsMatch = TypeMatches (decl, significantParameterList, func.Signature.Parameters as SwiftTupleType, typeMap); + var returnMatches = dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); + return argsMatch && returnMatches; + } + } else { + // oh, hooray. Swift does a reduction in the tuple-ness of arguments. + // if I declare a function, func a(a:(Bool, Bool)) { } + // This should get turned into: + // __TF6Module1aFTTSbSb__T_ + // Instead, swift turns it into: + // __TF6Module1aFTSbSb_T_ + // In other words, if the only argument to the function is a tuple, unwrap it. + if (significantParameterList.Count == 1 && significantParameterList [0].TypeSpec is TupleTypeSpec) { + return TypeMatches (decl, significantParameterList [0], func.Signature.Parameters, false, typeMap) + && (dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); + } + } + return false; + } + + + static bool TypeMatches (FunctionDeclaration decl, List parms, SwiftTupleType tuple, TypeMapper typeMap) + { + if (tuple == null || parms.Count != tuple.Contents.Count) + return false; + for (int i = 0; i < parms.Count; i++) { + if (!TypeMatches (decl, parms [i], tuple.Contents [i], decl.IsSubscript, typeMap)) + return false; + } + return true; + } + + static bool TypeMatches (FunctionDeclaration decl, ParameterItem pi, SwiftType st, bool ignoreName, TypeMapper typeMap) + { + // some SwiftType parameters have no names, such as operators + if (!ignoreName && pi.PublicName != "self" && st.Name != null && pi.PublicName != st.Name.Name) + return false; + if (pi.IsVariadic != st.IsVariadic) + return false; + return TypeMatches (decl, pi.TypeSpec, st, typeMap); + } + + static bool TypeMatches (FunctionDeclaration decl, TypeSpec ts, SwiftType st, TypeMapper typeMap) + { + switch (ts.Kind) { + case TypeSpecKind.Named: + return TypeMatches (decl, ts as NamedTypeSpec, st, typeMap); + case TypeSpecKind.Closure: + return TypeMatches (decl, ts as ClosureTypeSpec, st, typeMap); + case TypeSpecKind.Tuple: + return TypeMatches (decl, ts as TupleTypeSpec, st, typeMap); + case TypeSpecKind.ProtocolList: + return TypeMatches (decl, ts as ProtocolListTypeSpec, st, typeMap); + default: + throw new ArgumentOutOfRangeException (nameof (ts)); + } + } + + static bool TypeMatches (FunctionDeclaration decl, ClosureTypeSpec cs, SwiftType st, TypeMapper typeMap) + { + SwiftBaseFunctionType bft = st as SwiftBaseFunctionType; + return TypeMatches (decl, cs.Arguments, bft.Parameters, typeMap) && + TypeMatches (decl, cs.ReturnType, bft.ReturnType, typeMap); + } + + static bool TypeMatches (FunctionDeclaration decl, TupleTypeSpec ts, SwiftType st, TypeMapper typeMap) + { + var tuple = st as SwiftTupleType; + if (tuple == null || tuple.Contents.Count != ts.Elements.Count) + return false; + for (int i = 0; i < ts.Elements.Count; i++) { + if (!TypeMatches (decl, ts.Elements [i], tuple.Contents [i], typeMap)) + return false; + } + return true; + } + + static bool TypeMatches (FunctionDeclaration decl, ProtocolListTypeSpec ps, SwiftType st, TypeMapper typeMap) + { + var protoList = st as SwiftProtocolListType; + if (protoList == null || protoList.Protocols.Count != ps.Protocols.Count) + return false; + for (int i=0; i < ps.Protocols.Count; i++) { + if (!TypeMatches (decl, ps.Protocols.Keys [i], protoList.Protocols [i], typeMap)) + return false; + } + return true; + } + + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftType st, TypeMapper typeMap) + { + switch (st.Type) { + case CoreCompoundType.Scalar: + return TypeMatches (decl, ts, st as SwiftBuiltInType, typeMap); + case CoreCompoundType.Class: + return TypeMatches (decl, ts, st as SwiftClassType, typeMap); + case CoreCompoundType.MetaClass: + if (st is SwiftExistentialMetaType exist) + return TypeMatches (decl, ts, exist, typeMap); + else + return TypeMatches (decl, ts, st as SwiftMetaClassType, typeMap); + case CoreCompoundType.BoundGeneric: + return TypeMatches (decl, ts, st as SwiftBoundGenericType, typeMap); + case CoreCompoundType.ProtocolList: + return TypeMatches (decl, ts, st as SwiftProtocolListType, typeMap); + case CoreCompoundType.GenericReference: + return TypeMatches (decl, ts, st as SwiftGenericArgReferenceType, typeMap); + case CoreCompoundType.Struct: + default: + return false; + } + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftGenericArgReferenceType genArg, TypeMapper typeMap) + { + if (genArg.HasAssociatedTypePath) { + if (!decl.IsProtocolWithAssociatedTypesFullPath (ts, typeMap)) + return false; + var parts = ts.Name.Split ('.'); + // parts will have the generic part at 0, genArg will not + if (parts.Length != genArg.AssociatedTypePath.Count + 1) + return false; + var depthAndIndex = decl.GetGenericDepthAndIndex (parts [0]); + if (genArg.Depth != depthAndIndex.Item1 || genArg.Index != depthAndIndex.Item2) + return false; + for (int i = 0; i < genArg.AssociatedTypePath.Count; i++) { + if (genArg.AssociatedTypePath [i] != parts [i + 1]) + return false; + } + return true; + } else { + if (!decl.IsTypeSpecGeneric (ts)) + return false; + var depthAndIndex = decl.GetGenericDepthAndIndex (ts.Name); + return genArg.Depth == depthAndIndex.Item1 && genArg.Index == depthAndIndex.Item2; + } + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftProtocolListType protList, TypeMapper typeMap) + { + if (protList == null) + return false; + if (protList.Protocols.Count == 1 && !ts.IsProtocolList) { + return TypeMatches (decl, ts, protList.Protocols [0], typeMap); + } + + if (protList.Protocols.Count != ts.GenericParameters.Count || !ts.IsProtocolList) + return false; + for (int i = 0; i < ts.GenericParameters.Count; i++) { + if (!TypeMatches (decl, ts.GenericParameters [i], protList.Protocols [i], typeMap)) + return false; + } + return true; + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftClassType ct, TypeMapper typeMap) + { + if (ct == null) + return false; + return ts.Name == ct.ClassName.ToFullyQualifiedName (true) || + ts.NameWithoutModule == ct.ClassName.ToFullyQualifiedName (false); + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftBuiltInType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (ts.IsInOut != st.IsReference) + return false; + switch (st.BuiltInType) { + case CoreBuiltInType.Bool: + return ts.Name == "Swift.Bool"; + case CoreBuiltInType.Double: + return ts.Name == "Swift.Double"; + case CoreBuiltInType.Float: + return ts.Name == "Swift.Float"; + case CoreBuiltInType.Int: + return ts.Name == "Swift.Int"; + case CoreBuiltInType.UInt: + return ts.Name == "Swift.UInt"; + default: + throw new ArgumentOutOfRangeException ("st"); + } + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftExistentialMetaType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (st.Protocol.Protocols.Count != 1) + return false; + var protoClass = st.Protocol.Protocols [0]; + if (ts.Name == "Any.Type") { + return protoClass.ClassName.ToFullyQualifiedName () == "Swift.Any"; + } + if (ts.Name == protoClass.ClassName.ToFullyQualifiedName ()) + return true; + if (ts.Name.EndsWith (".Type", StringComparison.Ordinal)) { + var maybeClassName = ts.Name.Substring (0, ts.Name.Length - ".Type".Length); + return maybeClassName == protoClass.ClassName.ToFullyQualifiedName (); + } + return false; + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftMetaClassType st, TypeMapper typeMap) + { + if (st == null) + return false; + return ts.Name == st.Class.ClassName.ToFullyQualifiedName (true); + } + + static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftBoundGenericType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (!ts.ContainsGenericParameters) + return false; + return TypeMatches (decl, ts.GenericParameters, st.BoundTypes, typeMap); + } + + static bool TypeMatches (FunctionDeclaration decl, List ts, List st, TypeMapper typeMap) + { + if (ts == null || st == null) + return false; + if (ts.Count != st.Count) + return false; + if (ts.Count == 1) { + // Thanks swift, you're the best... + if (IsVoid (ts [0]) && st [0].IsEmptyTuple) + return true; + } + for (int i = 0; i < ts.Count; i++) { + if (!TypeMatches (decl, ts [i], st [i], typeMap)) + return false; + } + return true; + } + + static bool IsVoid (TypeSpec ts) + { + var ns = ts as NamedTypeSpec; + return ns != null && (ns.Name == "Void" || ns.Name == "Swift.Void"); + } + } +} + From 1876c1ab74f968baade4075c02f6be8bc898205d Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 16:33:01 +0100 Subject: [PATCH 04/37] Add SwiftBindings project A command-line interface that orchestrates the tooling workflow. --- src/SwiftBindings/src/MyClass.cs | 13 ---- src/SwiftBindings/src/Program.cs | 88 ++++++++++++++++++++++ src/SwiftBindings/src/SwiftBindings.csproj | 10 ++- 3 files changed, 96 insertions(+), 15 deletions(-) delete mode 100644 src/SwiftBindings/src/MyClass.cs create mode 100644 src/SwiftBindings/src/Program.cs diff --git a/src/SwiftBindings/src/MyClass.cs b/src/SwiftBindings/src/MyClass.cs deleted file mode 100644 index 907d856d3f57..000000000000 --- a/src/SwiftBindings/src/MyClass.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace SwiftBindings -{ - public class MyClass - { - public static bool ReturnTrue => true; - public static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - } - } -} diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs new file mode 100644 index 000000000000..fd41e1427ae9 --- /dev/null +++ b/src/SwiftBindings/src/Program.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using CommandLine; +using SwiftReflector; + +namespace SwiftBindings +{ + public class Options + { + [Option('d', "dylibs", Required = true, Separator = ',', HelpText = "Paths to the dynamic libraries (dylibs), separated by commas.")] + public IEnumerable DylibPaths { get; set; } + + [Option('s', "swiftinterfaces", Required = true, Separator = ',', HelpText = "Paths to the Swift interface files, separated by commas.")] + public IEnumerable SwiftInterfacePaths { get; set; } + + [Option('o', "output", Required = true, HelpText = "Output directory for generated bindings.")] + public string OutputDirectory { get; set; } + + [Option('h', "help", HelpText = "Display this help message.")] + public bool Help { get; set; } + } + + public class BindingsTool + { + public static void Main(string[] args) + { + Parser.Default.ParseArguments(args).WithParsed(options => + { + if (options.Help) + { + Console.WriteLine("Usage:"); + Console.WriteLine(" -d, --dylibs Paths to the dynamic libraries (dylibs), separated by commas."); + Console.WriteLine(" -s, --swiftinterfaces Paths to the Swift interface files, separated by commas."); + Console.WriteLine(" -o, --output Output directory for generated bindings."); + return; + } + + if (options.DylibPaths == null || options.SwiftInterfacePaths == null || options.OutputDirectory == null) + { + Console.WriteLine("Error: Missing required argument(s)."); + return; + } + + if (options.DylibPaths.Count() != options.SwiftInterfacePaths.Count()) + { + Console.WriteLine("Error: Number of dylibs, interface files, and modules must match."); + return; + } + + if (!Directory.Exists(options.OutputDirectory)) + { + Console.WriteLine($"Error: Directory '{options.OutputDirectory}' doesn't exist."); + return; + } + + for (int i = 0; i < options.DylibPaths.Count(); i++) + { + string dylibPath = options.DylibPaths.ElementAt(i); + string swiftInterfacePath = options.SwiftInterfacePaths.ElementAt(i); + + if (!File.Exists(dylibPath)) + { + Console.WriteLine($"Error: Dynamic library not found at path '{dylibPath}'."); + return; + } + + if (!File.Exists(swiftInterfacePath)) + { + Console.WriteLine($"Error: Swift interface file not found at path '{swiftInterfacePath}'."); + return; + } + + GenerateBindings(dylibPath, swiftInterfacePath, options.OutputDirectory); + } + }); + } + + public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory) + { + BindingsCompiler bindingsCompiler = new BindingsCompiler(); + var errors = new ErrorHandling (); + var moduleInventory = bindingsCompiler.GetModuleInventory(dylibPath, errors); + var moduleDeclarations = bindingsCompiler.GetModuleDeclarations(swiftInterfacePath); + bindingsCompiler.CompileModules(moduleDeclarations, moduleInventory, dylibPath, outputDirectory, errors); + } + } +} diff --git a/src/SwiftBindings/src/SwiftBindings.csproj b/src/SwiftBindings/src/SwiftBindings.csproj index 91b464afeacc..b7264f2a28f0 100644 --- a/src/SwiftBindings/src/SwiftBindings.csproj +++ b/src/SwiftBindings/src/SwiftBindings.csproj @@ -2,9 +2,15 @@ Exe - net8.0 + net7.0 enable - enable + disable + + + + + + From 1345f05877791044aca2d9234cc170e8595770ee Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 16:34:48 +0100 Subject: [PATCH 05/37] Add basic testing coverage --- Directory.Build.targets | 2 +- README.md | 15 ++++- eng/Versions.props | 2 +- global.json | 4 +- src/SwiftBindings/tests/CMakeLists.txt | 25 +++++++ src/SwiftBindings/tests/SmokeTests.cs | 29 ++++++++- src/SwiftBindings/tests/SmokeTests.swift | 7 ++ .../tests/SwiftBindings.Tests.csproj | 14 +++- src/SwiftBindings/tests/TestsHelper.cs | 65 +++++++++++++++++++ src/samples/HelloWorld/.gitignore | 6 ++ src/samples/HelloWorld/HelloLibrary.swift | 3 + src/samples/HelloWorld/HelloWorld.csproj | 8 +++ src/samples/HelloWorld/Program.cs | 16 +++++ .../TopLevelEntitiesHelloLibrary.cs | 18 +++++ src/samples/HelloWorld/build.sh | 14 ++++ 15 files changed, 215 insertions(+), 13 deletions(-) create mode 100644 src/SwiftBindings/tests/CMakeLists.txt create mode 100644 src/SwiftBindings/tests/SmokeTests.swift create mode 100644 src/SwiftBindings/tests/TestsHelper.cs create mode 100644 src/samples/HelloWorld/.gitignore create mode 100644 src/samples/HelloWorld/HelloLibrary.swift create mode 100644 src/samples/HelloWorld/HelloWorld.csproj create mode 100644 src/samples/HelloWorld/Program.cs create mode 100644 src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs create mode 100755 src/samples/HelloWorld/build.sh diff --git a/Directory.Build.targets b/Directory.Build.targets index 05db7dabfa1a..1d7fc8d541b2 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -8,7 +8,7 @@ TargetingPackVersion="$(MicrosoftNETCoreAppVersion)" /> - + diff --git a/README.md b/README.md index d865c64af7e3..f07814db03e4 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,18 @@ This is a collection of tools designed to consume a compiled Apple Swift library and generate bindings and wrappers that enable it to be used as a .NET library. -## Current Status - -The components are currently undergoing iterative reviews and will be moved from https://github.com/xamarin/binding-tools-for-swift. +## Installation and usage + +The tool will be available as a NuGet CLI package in the [`dotnet-experimental`](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet-experimental) feed. + +Options: +``` + -d, --dylibs Required. Paths to the dynamic libraries (dylibs), separated by commas. + -s, --swiftinterfaces Required. Paths to the Swift interface files, separated by commas. + -o, --output Required. Output directory for generated bindings. + -h, --help Display this help message. + --version Display version information. +``` ## .NET Foundation diff --git a/eng/Versions.props b/eng/Versions.props index 96ee7aa47cf3..c8b0dd0ce8ee 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -13,7 +13,7 @@ false 16.7.1 - 2.4.1 + 2.4.2 2.4.3 7.0.0-preview.7.22375.6 diff --git a/global.json b/global.json index ef7775d375fe..2e4a95fa688a 100644 --- a/global.json +++ b/global.json @@ -1,11 +1,11 @@ { "sdk": { - "version": "8.0.100", + "version": "7.0.100", "allowPrerelease": true, "rollForward": "major" }, "tools": { - "dotnet": "8.0.100" + "dotnet": "7.0.100" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.24102.4" diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt new file mode 100644 index 000000000000..ad95d4b52694 --- /dev/null +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.24) + +project(SmokeTests) + +set(SOURCE SmokeTests) + +if (NOT SWIFT_COMPILER_TARGET) + set(SWIFT_PLATFORM "macosx") + if (NOT DEFINED CMAKE_OSX_ARCHITECTURES OR CMAKE_OSX_ARCHITECTURES STREQUAL "") + set(CMAKE_OSX_ARCHITECTURES "arm64") + endif() + set(SWIFT_PLATFORM_SUFFIX "11") + set(SWIFT_DEPLOYMENT_TARGET ${CMAKE_OSX_DEPLOYMENT_TARGET}) + set(SWIFT_COMPILER_TARGET "${CMAKE_OSX_ARCHITECTURES}-apple-${SWIFT_PLATFORM}${SWIFT_DEPLOYMENT_TARGET}${SWIFT_PLATFORM_SUFFIX}") +endif() + +add_custom_target(${SOURCE} ALL + COMMAND xcrun swiftc -target ${SWIFT_COMPILER_TARGET} -emit-module -emit-library -enable-library-evolution -emit-module-interface ${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE}.swift -o ${CMAKE_CURRENT_BINARY_DIR}/lib${SOURCE}.dylib + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE}.swift + COMMENT "Generating ${SOURCE} library" +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/lib${SOURCE}.dylib + DESTINATION bin +) diff --git a/src/SwiftBindings/tests/SmokeTests.cs b/src/SwiftBindings/tests/SmokeTests.cs index db7c93457129..c90077403f81 100644 --- a/src/SwiftBindings/tests/SmokeTests.cs +++ b/src/SwiftBindings/tests/SmokeTests.cs @@ -1,14 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + using System; using Xunit; namespace SwiftBindings.Tests { - public class MyClassTests + public class SmokeTests { [Fact] - public void Test1() + public void DirectPInvokeVoidVoid() { - Assert.True(MyClass.ReturnTrue); + BindingsTool.GenerateBindings("libSmokeTests.dylib", "SmokeTests.swiftinterface", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using SmokeTests; + + namespace Hello { + class MainClass { + public static int Main(string[] args) + { + TopLevelEntities.SimplePinvokeVoidVoid(); + return 42; + } + } + } + """; + + int result = TestsHelper.CompileAndExecuteFromFileAndString("TopLevelEntitiesSmokeTests.cs", sourceCode); + Assert.Equal(42, result); } } } diff --git a/src/SwiftBindings/tests/SmokeTests.swift b/src/SwiftBindings/tests/SmokeTests.swift new file mode 100644 index 000000000000..eb556889f728 --- /dev/null +++ b/src/SwiftBindings/tests/SmokeTests.swift @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +public func SimplePinvokeVoidVoid() +{ + print("Hello world"); +} diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index b09cc9165c4c..e9bedd90a5dc 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,9 +1,17 @@ - net8.0 + net7.0 + cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make - + - + + + + + + + + diff --git a/src/SwiftBindings/tests/TestsHelper.cs b/src/SwiftBindings/tests/TestsHelper.cs new file mode 100644 index 000000000000..ad2fde361a82 --- /dev/null +++ b/src/SwiftBindings/tests/TestsHelper.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; + +namespace SwiftBindings.Tests +{ + public static class TestsHelper + { + public static int CompileAndExecuteFromFileAndString(string filePath, string sourceCode) + { + string fileSourceCode = File.ReadAllText(filePath); + var sourceCodes = new[] { fileSourceCode, sourceCode }; + return CompileAndExecute(sourceCodes); + } + + private static int CompileAndExecute(string[] sourceCodes) + { + var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication); + var syntaxTrees = sourceCodes.Select(code => CSharpSyntaxTree.ParseText(code)).ToArray(); + + var references = new[] + { + MetadataReference.CreateFromFile(typeof(object).Assembly.Location), + MetadataReference.CreateFromFile(typeof(Console).Assembly.Location), + }; + + + var compilation = CSharpCompilation.Create("CompiledAssembly", + syntaxTrees: syntaxTrees, + references: references, + options: options); + + string assemblyPath = Path.Combine(Path.GetTempPath(), "CompiledAssembly.dll"); + using (var stream = new FileStream(assemblyPath, FileMode.Create)) + { + EmitResult emitResult = compilation.Emit(stream); + + if (!emitResult.Success) + { + string errorMessage = "Compilation failed:"; + foreach (var diagnostic in emitResult.Diagnostics) + { + errorMessage += $"\n{diagnostic}"; + } + throw new InvalidOperationException(errorMessage); + } + } + + Assembly compiledAssembly = Assembly.LoadFile(assemblyPath); + + MethodInfo entryPoint = compiledAssembly.EntryPoint; + object[] args = entryPoint.GetParameters().Length == 0 ? null : new object[] { new string[0] }; + int result = (int)entryPoint.Invoke(null, args); + + return result; + } + } +} \ No newline at end of file diff --git a/src/samples/HelloWorld/.gitignore b/src/samples/HelloWorld/.gitignore new file mode 100644 index 000000000000..547b76a704d3 --- /dev/null +++ b/src/samples/HelloWorld/.gitignore @@ -0,0 +1,6 @@ +*.swiftinterface* +*.swiftdoc* +*.swiftmodule* +*.abi* +*.swiftsourceinfo* +*.dylib \ No newline at end of file diff --git a/src/samples/HelloWorld/HelloLibrary.swift b/src/samples/HelloWorld/HelloLibrary.swift new file mode 100644 index 000000000000..028ac3a79b38 --- /dev/null +++ b/src/samples/HelloWorld/HelloLibrary.swift @@ -0,0 +1,3 @@ +public func sayHello() { + print("Hello world") +} \ No newline at end of file diff --git a/src/samples/HelloWorld/HelloWorld.csproj b/src/samples/HelloWorld/HelloWorld.csproj new file mode 100644 index 000000000000..ec31b78f5c8b --- /dev/null +++ b/src/samples/HelloWorld/HelloWorld.csproj @@ -0,0 +1,8 @@ + + + Exe + net7.0 + enable + disable + + diff --git a/src/samples/HelloWorld/Program.cs b/src/samples/HelloWorld/Program.cs new file mode 100644 index 000000000000..3835b62a7c71 --- /dev/null +++ b/src/samples/HelloWorld/Program.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using HelloLibrary; + +namespace HelloWorld +{ + public class Progrma + { + public static void Main(string[] args) + { + TopLevelEntities.SayHello(); + } + } +} diff --git a/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs b/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs new file mode 100644 index 000000000000..a418e8be45ec --- /dev/null +++ b/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs @@ -0,0 +1,18 @@ + +using System; +using System.Runtime.InteropServices; +namespace HelloLibrary +{ + public class TopLevelEntities + { + public static void SayHello() + { + NativeMethodsForTopLevelEntities.PIfunc_SayHello(); + } + } + internal class NativeMethodsForTopLevelEntities + { + [DllImport("libHelloLibrary.dylib", EntryPoint = "$s12HelloLibrary03sayA0yyF")] + internal static extern void PIfunc_SayHello(); + } +} \ No newline at end of file diff --git a/src/samples/HelloWorld/build.sh b/src/samples/HelloWorld/build.sh new file mode 100755 index 000000000000..1b7ed46863bf --- /dev/null +++ b/src/samples/HelloWorld/build.sh @@ -0,0 +1,14 @@ +#!/bin/bash +xcrun swiftc -emit-module -emit-library -enable-library-evolution -emit-module-interface HelloLibrary.swift -o libHelloLibrary.dylib + +dotnet restore ../../SwiftBindings/src/SwiftBindings.csproj +dotnet build ../../SwiftBindings/src/SwiftBindings.csproj + +if [ $? -eq 0 ]; then + echo "Build successful. Running the BindingsTool..." + dotnet ../../../artifacts/bin/SwiftBindings/Debug/net7.0/SwiftBindings.dll -d "./libHelloLibrary.dylib" -s "./HelloLibrary.swiftinterface" -o "./" + dotnet run +else + echo "Build failed. Exiting..." + exit 1 +fi From 65dda6314e348639b84b8b485547f7526165b0d2 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 14 Feb 2024 17:09:00 +0100 Subject: [PATCH 06/37] Fix sample application --- src/samples/HelloWorld/Program.cs | 2 +- .../HelloWorld/TopLevelEntitiesHelloLibrary.cs | 18 ------------------ 2 files changed, 1 insertion(+), 19 deletions(-) delete mode 100644 src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs diff --git a/src/samples/HelloWorld/Program.cs b/src/samples/HelloWorld/Program.cs index 3835b62a7c71..21a0e34b01d4 100644 --- a/src/samples/HelloWorld/Program.cs +++ b/src/samples/HelloWorld/Program.cs @@ -6,7 +6,7 @@ namespace HelloWorld { - public class Progrma + public class Program { public static void Main(string[] args) { diff --git a/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs b/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs deleted file mode 100644 index a418e8be45ec..000000000000 --- a/src/samples/HelloWorld/TopLevelEntitiesHelloLibrary.cs +++ /dev/null @@ -1,18 +0,0 @@ - -using System; -using System.Runtime.InteropServices; -namespace HelloLibrary -{ - public class TopLevelEntities - { - public static void SayHello() - { - NativeMethodsForTopLevelEntities.PIfunc_SayHello(); - } - } - internal class NativeMethodsForTopLevelEntities - { - [DllImport("libHelloLibrary.dylib", EntryPoint = "$s12HelloLibrary03sayA0yyF")] - internal static extern void PIfunc_SayHello(); - } -} \ No newline at end of file From 56e96bc374adc1e15a23afda3277c184857de9fb Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 16:37:00 +0100 Subject: [PATCH 07/37] Remove Swift4 demangler --- .gitignore | 8 + src/SwiftReflector/Demangling/Decomposer.cs | 13 - .../Demangling/Swift4Demangler.cs | 1814 ---------------- .../Demangling/Swift4NodeToTLDefinition.cs | 1887 ----------------- .../Demangling/Swift5Demangler.cs | 6 +- src/samples/HelloWorld/.gitignore | 6 - 6 files changed, 9 insertions(+), 3725 deletions(-) delete mode 100644 src/SwiftReflector/Demangling/Swift4Demangler.cs delete mode 100644 src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs delete mode 100644 src/samples/HelloWorld/.gitignore diff --git a/.gitignore b/.gitignore index 39f459f0940a..0f6b076f2389 100644 --- a/.gitignore +++ b/.gitignore @@ -190,3 +190,11 @@ Session.vim # VS debug support files launchSettings.json + +# Swift output files +*.swiftinterface* +*.swiftdoc* +*.swiftmodule* +*.abi* +*.swiftsourceinfo* +*.dylib \ No newline at end of file diff --git a/src/SwiftReflector/Demangling/Decomposer.cs b/src/SwiftReflector/Demangling/Decomposer.cs index 8b60a3076c21..1106bee7e818 100644 --- a/src/SwiftReflector/Demangling/Decomposer.cs +++ b/src/SwiftReflector/Demangling/Decomposer.cs @@ -74,25 +74,12 @@ public static TLDefinition Decompose (string swiftIdentifier, bool isOldVersion, swiftIdentifier.StartsWith (kSwift5ID, StringComparison.Ordinal)) { var demangler5 = new Swift5Demangler (swiftIdentifier, offset); return demangler5.Run (); - } - if (swiftIdentifier.StartsWith (kSwift4ID, StringComparison.Ordinal)) { - var demangler = new Swift4Demangler (swiftIdentifier, offset); - return demangler.Run (); } else { Decomposer decomp = new Decomposer (swiftIdentifier, isOldVersion, offset); return decomp.Run (); } } - public static string ExplodedView (string swiftIdentifier) - { - if (swiftIdentifier.StartsWith (kSwift4ID, StringComparison.Ordinal)) { - var demangler = new Swift4Demangler (swiftIdentifier, 0); - return demangler.ExplodedView (); - } - return null; - } - public TLDefinition Run () { Initialize (); diff --git a/src/SwiftReflector/Demangling/Swift4Demangler.cs b/src/SwiftReflector/Demangling/Swift4Demangler.cs deleted file mode 100644 index cd5a071cb498..000000000000 --- a/src/SwiftReflector/Demangling/Swift4Demangler.cs +++ /dev/null @@ -1,1814 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Text; -using SwiftReflector.ExceptionTools; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Demangling { - public class Swift4Demangler { - public const int kMaxRepeatCount = 2048; - ulong offset; - string originalIdentifier; - Stack nodeStack = new Stack (); - List substitutions = new List (); - List pendingSubstitutions = new List (); - List words = new List (); - StringSlice slice; - - public Swift4Demangler (string swiftIdentifier, ulong offset = 0) - { - Exceptions.ThrowOnNull (swiftIdentifier, nameof (swiftIdentifier)); - if (!swiftIdentifier.StartsWith (Decomposer.kSwift4ID, StringComparison.Ordinal)) - throw new ArgumentOutOfRangeException (nameof (swiftIdentifier), $"Expecting '{swiftIdentifier}' to start with '{Decomposer.kSwift4ID}'"); - this.offset = offset; - originalIdentifier = swiftIdentifier; - slice = new StringSlice (originalIdentifier); - slice.Advance (Decomposer.kSwift4ID.Length); - } - - public TLDefinition Run() - { - Node topLevelNode = DemangleType (); - if (topLevelNode != null && topLevelNode.IsAttribute() && nodeStack.Count >= 1) { - var attribute = topLevelNode.ExtractAttribute (); - var tld = Run (); - if (tld != null && tld is TLFunction tlf) { - tlf.Signature.Attributes.Add (attribute); - } - return tld; - } else { - Swift4NodeToTLDefinition converter = new Swift4NodeToTLDefinition (originalIdentifier, offset); - return converter.Convert (topLevelNode); - } - } - - public string ExplodedView() - { - Node topLevelNode = DemangleType (); - return topLevelNode != null ? topLevelNode.ToString () : null; - } - - Node DemangleType() - { - if (!ParseAndPushNodes ()) - throw ErrorHelper.CreateError (ReflectorError.kDecomposeBase + 2, $"Error decomposing {slice.Original} at {slice.Position}"); - var node = PopNode (); - if (node != null) - return node; - return new Node (NodeKind.Suffix, slice.Original); - } - - bool ParseAndPushNodes() - { - while (!slice.IsAtEnd) { - var node = DemangleOperator (); - if (node == null) - return false; - PushNode (node); - } - return true; - } - - bool NextIf (string str) - { - if (slice.StartsWith (str)) { - slice.Advance (str.Length); - return true; - } - return false; - - } - - char PeekChar () - { - if (slice.IsAtEnd) - return (char)0; - return slice.Current; - } - - char NextChar () - { - return slice.Advance (); - } - - bool NextIf (char c) - { - return slice.AdvanceIfEquals (c); - } - - void PushBack () - { - slice.Rewind (); - } - - string ConsumeAll () - { - return slice.ConsumeRemaining (); - } - - void PushNode (Node node) - { - nodeStack.Push (node); - } - - Node PopNode () - { - if (nodeStack.Count == 0) - return null; - return nodeStack.Pop (); - } - - Node PopNode (NodeKind kind) - { - if (nodeStack.Count == 0) - return null; - if (kind != nodeStack.Peek ().Kind) - return null; - return PopNode (); - } - - Node PopNode (Predicate pred) - { - if (nodeStack.Count == 0) - return null; - if (!pred (nodeStack.Peek ().Kind)) - return null; - return PopNode (); - } - - void AddSubstitution (Node nd) - { - if (nd != null) - substitutions.Add (nd); - } - - Node AddChild (Node parent, Node child) - { - if (parent == null || child == null) - return null; - parent.Children.Add (child); - return parent; - } - - Node CreateWithChild (NodeKind kind, Node child) - { - if (child == null) - return null; - var node = new Node (kind); - node.Children.Add (child); - return node; - } - - Node CreateType (Node child) - { - return CreateWithChild (NodeKind.Type, child); - } - - Node CreateWithChildren (NodeKind kind, params Node [] children) - { - foreach (var nd in children) - if (nd == null) - throw new ArgumentOutOfRangeException (nameof (children)); - var node = new Node (kind); - node.Children.AddRange (children); - return node; - } - - Node CreateWithPoppedType(NodeKind kind) - { - return CreateWithChild (kind, PopNode (NodeKind.Type)); - } - - Node ChangeKind (Node node, NodeKind newKind) - { - Node newNode = null; - if (node.HasText) { - newNode = new Node (node.Kind, node.Text); - } else if (node.HasIndex) { - newNode = new Node (node.Kind, node.Index); - } else { - newNode = new Node (node.Kind); - } - newNode.Children.AddRange (node.Children); - return newNode; - } - - Node DemangleOperator () - { - var c = NextChar (); - switch (c) { - case 'A': return DemangleMultiSubstitutions (); - case 'B': return DemangleBuiltinType (); - case 'C': return DemangleAnyGenericType (NodeKind.Class); - case 'D': return CreateWithChild (NodeKind.TypeMangling, PopNode (NodeKind.Type)); - case 'E': return DemangleExtensionContext (); - case 'F': return DemanglePlainFunction (); - case 'G': return DemangleBoundGenericType (); - case 'I': return DemangleImplFunctionType (); - case 'K': return new Node (NodeKind.ThrowsAnnotation); - case 'L': return DemangleLocalIdentifier (); - case 'M': return DemangleMetatype (); - case 'N': return CreateWithChild (NodeKind.TypeMetadata, PopNode (NodeKind.Type)); - case 'O': return DemangleAnyGenericType (NodeKind.Enum); - case 'P': return DemangleAnyGenericType (NodeKind.Protocol); - case 'Q': return DemangleArchetype (); - case 'R': return DemangleGenericRequirement (); - case 'S': return DemangleStandardSubstitution (); - case 'T': return DemangleThunkOrSpecialization (); - case 'V': return DemangleAnyGenericType (NodeKind.Structure); - case 'W': return DemangleWitness (); - case 'X': return DemangleSpecialType (); - case 'Z': return CreateWithChild (NodeKind.Static, PopNode (Node.IsEntity)); - case 'a': return DemangleAnyGenericType (NodeKind.TypeAlias); - case 'c': return PopFunctionType (NodeKind.FunctionType); - case 'd': return new Node (NodeKind.VariadicMarker); - case 'f': return DemangleFunctionEntity (); - case 'i': return DemangleEntity (NodeKind.Subscript); - case 'l': return DemangleGenericSignature (false); - case 'm': return CreateType (CreateWithChild (NodeKind.Metatype, PopNode (NodeKind.Type))); - case 'o': return DemangleOperatorIdentifier (); - case 'p': return DemangleProtocolListType (); - case 'q': return CreateType (DemangleGenericParamIndex ()); - case 'r': return DemangleGenericSignature (true); - case 's': return new Node (NodeKind.Module, "Swift"); - case 't': return PopTuple (); - case 'u': return DemangleGenericType (); - case 'v': return DemangleEntity (NodeKind.Variable); - case 'w': return DemangleValueWitness (); - case 'x': return CreateType (GetDependentGenericParamType (0, 0)); - case 'y': return new Node (NodeKind.EmptyList); - case 'z': return CreateType (CreateWithChild (NodeKind.InOut, PopTypeAndGetChild ())); - case '_': return new Node (NodeKind.FirstElementMarker); - case '.': - PushBack (); - return new Node (NodeKind.Suffix, ConsumeAll ()); - default: - PushBack (); - return DemangleIdentifier (); - } - } - - Node DemangleLocalIdentifier() - { - if (NextIf('L')) { - var adiscriminator = PopNode (NodeKind.Identifier); - var aname = PopNode (Node.IsDeclName); - return CreateWithChildren (NodeKind.PrivateDeclName, adiscriminator, aname); - } - if (NextIf('l')) { - var adiscriminator = PopNode (NodeKind.Identifier); - return CreateWithChild (NodeKind.PrivateDeclName, adiscriminator); - } - var discriminator = DemangleIndexAsNode (); - var name = PopNode (Node.IsDeclName); - return CreateWithChildren (NodeKind.LocalDeclName, discriminator, name); - } - - Node PopModule() - { - var ident = PopNode (NodeKind.Identifier); - if (ident != null) - return ChangeKind (ident, NodeKind.Module); - return PopNode (NodeKind.Module); - } - - Node PopContext() - { - var mod = PopModule (); - if (mod != null) - return mod; - Node ty = PopNode (NodeKind.Type); - if (ty != null) { - if (ty.Children.Count != 1) - return null; - var child = ty.Children [0]; - if (!Node.IsContext (child.Kind)) - return null; - return child; - } - return PopNode (Node.IsContext); - } - - Node PopTypeAndGetChild () - { - Node ty = PopNode (NodeKind.Type); - if (ty == null || ty.Children.Count != 1) - return null; - return ty.Children [0]; - } - - Node PopTypeAndGetNominal() - { - var child = PopTypeAndGetChild (); - if (child != null && Node.IsNominal (child.Kind)) - return child; - return null; - } - - Node DemangleBuiltinType() - { - Node ty = null; - switch (NextChar ()) { - case 'b': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); - break; - case 'B': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); - break; - case 'f': { - int size = DemangleIndex () - 1; - if (size <= 0) - return null; - string name = $"Builtin.Float{size}"; - ty = new Node (NodeKind.BuiltinTypeName, name); - break; - } - case 'i': { - int size = DemangleIndex () - 1; - if (size <= 0) - return null; - string name = $"Builtin.Int{size}"; - ty = new Node (NodeKind.BuiltinTypeName, name); - break; - } - case 'v': { - int elts = DemangleIndex () - 1; - if (elts <= 0) - return null; - Node eltType = PopTypeAndGetChild (); - if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || - !eltType.Text.StartsWith ("Builtin.", StringComparison.Ordinal)) - return null; - string name = $"Builtin.Vec{elts}x{eltType.Text.Substring ("Builtin.".Length)}"; - ty = new Node (NodeKind.BuiltinTypeName, name); - break; - } - case 'O': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); - break; - case 'o': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.NativeObject"); - break; - case 'p': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.RawPointer"); - break; - case 'w': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.Word"); - break; - default: - return null; - } - return CreateType (ty); - } - - Node DemangleAnyGenericType(NodeKind kind) - { - var name = PopNode (Node.IsDeclName); - var ctx = PopContext (); - var nty = CreateType (CreateWithChildren (kind, ctx, name)); - AddSubstitution (nty); - return nty; - } - - Node DemangleExtensionContext() - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var module = PopModule (); - var type = PopTypeAndGetNominal (); - var ext = CreateWithChildren (NodeKind.Extension, module, type); - if (genSig != null) - ext = AddChild (ext, genSig); - return ext; - } - - Node DemanglePlainFunction() - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var type = PopFunctionType (NodeKind.FunctionType); - if (genSig != null) - type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); - var name = PopNode (Node.IsDeclName); - var ctx = PopContext (); - return CreateWithChildren (NodeKind.Function, ctx, name, type); - } - - Node PopFunctionType(NodeKind kind) - { - var funcType = new Node (kind); - AddChild (funcType, PopNode (NodeKind.ThrowsAnnotation)); - funcType = AddChild (funcType, PopFunctionParams (NodeKind.ArgumentTuple)); - funcType = AddChild (funcType, PopFunctionParams (NodeKind.ReturnType)); - return CreateType (funcType); - } - - Node PopFunctionParams(NodeKind kind) - { - Node parmsType = null; - if (PopNode(NodeKind.EmptyList) != null) { - parmsType = CreateType (new Node (NodeKind.Tuple)); - } else { - parmsType = PopNode (NodeKind.Type); - } - return CreateWithChild (kind, parmsType); - } - - Node PopTuple() - { - var root = new Node (NodeKind.Tuple); - - if (PopNode(NodeKind.EmptyList) == null) { - bool firstElem = false; - do { - firstElem = PopNode (NodeKind.FirstElementMarker) != null; - var tupleElmt = new Node (NodeKind.TupleElement); - AddChild (tupleElmt, PopNode (NodeKind.VariadicMarker)); - Node ident = null; - if ((ident = PopNode (NodeKind.Identifier)) != null) { - tupleElmt.Children.Add (new Node (NodeKind.TupleElementName, ident.Text)); - } - var ty = PopNode (NodeKind.Type); - if (ty == null) - return null; - tupleElmt.Children.Add (ty); - root.Children.Add (tupleElmt); - } while (!firstElem); - root.ReverseChildren (); - } - return CreateType (root); - } - - - Node DemangleMultiSubstitutions () - { - var repeatCount = -1; - while (true) { - var c = NextChar (); - if (c == 0) { - return null; - } - if (Char.IsLower (c)) { - Node nd = PushMultiSubstitutions (repeatCount, c - 'a'); - if (nd == null) - return null; - PushNode (nd); - repeatCount = -1; - continue; - } - if (Char.IsUpper (c)) { - return PushMultiSubstitutions (repeatCount, c - 'A'); - } - if (c == '_') { - var index = repeatCount + 27; - if (index >= substitutions.Count) - return null; - return substitutions [index]; - } - PushBack (); - repeatCount = DemangleNatural (); - if (repeatCount < 0) - return null; - } - } - - int DemangleNatural() - { - if (!Char.IsDigit (PeekChar ())) - return -1000; - int num = 0; - while (true) { - var c = PeekChar (); - if (!Char.IsDigit (c)) - return num; - int newNum = (10 * num) + (c - '0'); - if (newNum < num) - return -1000; - num = newNum; - NextChar (); - } - } - - int DemangleIndex() - { - if (NextIf ('_')) - return 0; - int num = DemangleNatural (); - if (num >= 0 && NextIf ('_')) - return num + 1; - return -1000; - } - - Node DemangleIndexAsNode() - { - int idx = DemangleIndex (); - if (idx >= 0) - return new Node (NodeKind.Number, idx); - return null; - } - - Node PushMultiSubstitutions(int repeatCount, int index) - { - if (index >= substitutions.Count) - return null; - if (repeatCount > kMaxRepeatCount) - return null; - Node nd = substitutions [index]; - while (repeatCount-- > 1) { - PushNode (nd); - } - return nd; - } - - Node CreateSwiftType(NodeKind typeKind, string name) { - return CreateType (CreateWithChildren (typeKind, - new Node (NodeKind.Module, "Swift"), - new Node (NodeKind.Identifier, name))); - } - - Node DemangleStandardSubstitution() - { - char c = NextChar (); - switch(c) { - case 'o': - return new Node (NodeKind.Module, "__ObjC"); - case 'C': - return new Node (NodeKind.Module, "__C"); - case 'g': { - var optionalTy = CreateType (CreateWithChildren (NodeKind.BoundGenericEnum, - CreateSwiftType (NodeKind.Enum, "Optional"), - CreateWithChild (NodeKind.TypeList, PopNode (NodeKind.Type)))); - AddSubstitution (optionalTy); - return optionalTy; - } - default: { - PushBack (); - var repeatCount = DemangleNatural (); - if (repeatCount > kMaxRepeatCount) - return null; - var nd = CreateStandardSubstitution (NextChar ()); - if (nd != null) { - while (repeatCount-- > 1) { - PushNode (nd); - } - return nd; - } - return null; - } - } - } - - Node CreateStandardSubstitution(char subst) - { - var kind = NodeKind.Structure; // most common - string name = null; - switch (subst) { - case 'a': name = "Array"; break; - case 'b': name = "Bool"; break; - case 'c': name = "UnicodeScalar"; break; - case 'd': name = "Double"; break; - case 'f': name = "Float"; break; - case 'i': name = "Int"; break; - case 'V': name = "UnsafeRawPointer"; break; - case 'v': name = "UnsafeMutableRawPointer"; break; - case 'P': name = "UnsafePointer"; break; - case 'p': name = "UnsafeMutablePointer"; break; - case 'R': name = "UnsafeBufferPointer"; break; - case 'r': name = "UnsafeMutableBufferPointer"; break; - case 'S': name = "String"; break; - case 'u': name = "UInt"; break; - case 'q': name = "Optional"; kind = NodeKind.Enum; break; - case 'Q': name = "ImplicitlyUnwrappedOptional"; kind = NodeKind.Enum; break; - default: return null; - } - return CreateSwiftType (kind, name); - } - - Node DemangleIdentifier() - { - var hasWordSubsts = false; - var isPunycoded = false; - var c = PeekChar (); - if (!Char.IsDigit (c)) - return null; - if (c == '0') { - NextChar (); - if (PeekChar() == '0') { - NextChar (); - isPunycoded = true; - } else { - hasWordSubsts = true; - } - } - var identifier = new StringBuilder (); - do { - while (hasWordSubsts && Char.IsLetter (PeekChar ())) { - var cc = NextChar (); - var wordIdx = 0; - if (Char.IsLower (cc)) { - wordIdx = cc - 'a'; - } else { - wordIdx = cc - 'A'; - hasWordSubsts = false; - } - if (wordIdx >= words.Count) - return null; - string piece0 = words [wordIdx]; - identifier.Append (piece0); - } - if (NextIf ('0')) - break; - var numChars = DemangleNatural (); - if (numChars <= 0) - return null; - if (isPunycoded) - NextIf ('_'); - if (numChars > slice.Length) - return null; - string piece = slice.Substring (slice.Position, numChars); - if (isPunycoded) { - PunyCode puny = new PunyCode (); - string punyCodedString = puny.Decode (piece); - identifier.Append (punyCodedString); - } else { - identifier.Append (piece); - var wordStartPos = -1; - for (int idx = 0; idx <= piece.Length; idx++) { - char ccc = idx < piece.Length ? piece [idx] : (char)0; - if (wordStartPos >= 0 && IsWordEnd (ccc, piece [idx - 1])) { - if (idx - wordStartPos >= 2 && words.Count < 26) { - var word = piece.Substring (wordStartPos, idx - wordStartPos); - words.Add (word); - } - wordStartPos = -1; - } - if (wordStartPos < 0 && IsWordStart(ccc)) { - wordStartPos = idx; - } - } - } - slice.Advance (numChars); - } while (hasWordSubsts); - if (identifier.Length == 0) - return null; - var ident = new Node (NodeKind.Identifier, identifier.ToString()); - AddSubstitution (ident); - return ident; - } - - bool IsWordStart(char ch) { - return !Char.IsDigit (ch) && ch != '_' && ch != (char)0; - } - - bool IsWordEnd(char ch, char prevCh) - { - if (ch == '_' || ch == (char)0) - return true; - if (!Char.IsUpper (prevCh) && Char.IsUpper (ch)) - return true; - return false; - } - Node DemangleOperatorIdentifier() - { - var ident = PopNode (NodeKind.Identifier); - if (ident == null) - return null; - var op_char_table = "& @/= > <*!|+?%-~ ^ ."; - StringBuilder opStr = new StringBuilder (); - foreach (var c in ident.Text) { - if (c > 0x7f) { - opStr.Append (c); - continue; - } - if (!Char.IsLower (c)) - return null; - char o = op_char_table [c - 'a']; - if (o == ' ') - return null; - opStr.Append (o); - } - switch (NextChar()) { - case 'i': return new Node (NodeKind.InfixOperator, opStr.ToString ()); - case 'p': return new Node (NodeKind.PrefixOperator, opStr.ToString ()); - case 'P': return new Node (NodeKind.PostfixOperator, opStr.ToString ()); - default: return null; - } - } - - Node PopTypeList() - { - var root = new Node (NodeKind.TypeList); - if (PopNode(NodeKind.EmptyList) == null) { - bool firstElem = false; - do { - firstElem = PopNode (NodeKind.FirstElementMarker) != null; - var ty = PopNode (NodeKind.Type); - if (ty == null) - return null; - root.Children.Add (ty); - } while (!firstElem); - root.ReverseChildren (); - } - return root; - } - - Node PopProtocol() - { - var name = PopNode (Node.IsDeclName); - var ctx = PopContext (); - var proto = CreateWithChildren (NodeKind.Protocol, ctx, name); - return CreateType (proto); - } - - Node DemangleBoundGenericType() - { - var typeListList = new List (4); - while (true) { - var tlist = new Node (NodeKind.TypeList); - typeListList.Add (tlist); - Node ty = null; - while ((ty = PopNode(NodeKind.Type)) != null) { - tlist.Children.Add (ty); - } - tlist.ReverseChildren (); - if (PopNode (NodeKind.EmptyList) != null) - break; - if (PopNode (NodeKind.FirstElementMarker) == null) - return null; - } - var nominal = PopTypeAndGetNominal (); - var nty = CreateType (DemangleBoundGenericArgs (nominal, typeListList, 0)); - AddSubstitution (nty); - return nty; - } - - Node DemangleBoundGenericArgs(Node nominal, List typeLists, int typeListIdx) - { - if (nominal == null || nominal.Children.Count < 2) - return null; - - if (typeListIdx >= typeLists.Count) - return null; - var args = typeLists [typeListIdx++]; - - var context = nominal.Children [0]; - - if (typeListIdx < typeLists.Count) { - Node boundParent = null; - if (context.Kind == NodeKind.Extension) { - boundParent = DemangleBoundGenericArgs (context.Children [1], typeLists, typeListIdx); - boundParent = CreateWithChildren (NodeKind.Extension, context.Children [0], boundParent); - - if (context.Children.Count == 3) { - AddChild (boundParent, context.Children [2]); - } - - } else { - boundParent = DemangleBoundGenericArgs (context, typeLists, typeListIdx); - } - nominal = CreateWithChildren (nominal.Kind, boundParent, nominal.Children [1]); - if (nominal == null) - return null; - } - - if (args.Children.Count == 0) - return nominal; - - NodeKind kind = NodeKind.Type; // arbitrary - switch (nominal.Kind) { - case NodeKind.Class: - kind = NodeKind.BoundGenericClass; - break; - case NodeKind.Structure: - kind = NodeKind.BoundGenericStructure; - break; - case NodeKind.Enum: - kind = NodeKind.BoundGenericEnum; - break; - default: - return null; - } - return CreateWithChildren (kind, CreateType (nominal), args); - } - - Node DemangleImplParamConvention() - { - string attr = null; - switch (NextChar ()) { - case 'i': attr = "@in"; break; - case 'c': attr = "@in_constant"; break; - case 'l': attr = "@inout"; break; - case 'b': attr = "@inout_aliasable"; break; - case 'n': attr = "@in_guaranteed"; break; - case 'x': attr = "@owned"; break; - case 'g': attr = "@guaranteed"; break; - case 'e': attr = "@deallocating"; break; - case 'y': attr = "@unowned"; break; - default: - PushBack (); - return null; - } - return CreateWithChild (NodeKind.ImplParameter, new Node (NodeKind.ImplConvention, attr)); - } - - Node DemangleImplResultConvention(NodeKind convKind) - { - string attr = null; - switch (NextChar ()) { - case 'r': attr = "@out"; break; - case 'o': attr = "@owned"; break; - case 'd': attr = "@unowned"; break; - case 'u': attr = "@unowned_inner_pointer"; break; - case 'a': attr = "@autoreleased"; break; - default: - PushBack (); - return null; - } - return CreateWithChild (convKind, new Node (NodeKind.ImplConvention, attr)); - } - - Node DemangleImplFunctionType() - { - var type = new Node (NodeKind.ImplFunctionType); - var genSig = PopNode (NodeKind.DependentGenericSignature); - if (genSig != null && NextIf ('P')) - genSig = ChangeKind (genSig, NodeKind.DependentPseudogenericSignature); - - string cAttr = null; - switch (NextChar()) { - case 'y': cAttr = "@callee_unowned"; break; - case 'g': cAttr = "@callee_guaranteed"; break; - case 'x': cAttr = "@callee_owned"; break; - case 't': cAttr = "@convention(thin)"; break; - default: - return null; - } - type.Children.Add (new Node (NodeKind.ImplConvention, cAttr)); - - string fAttr = null; - switch (NextChar ()) { - case 'B': fAttr = "@convention(block)"; break; - case 'C': fAttr = "@convention(c)"; break; - case 'M': fAttr = "@convention(method)"; break; - case 'O': fAttr = "@convention(objc_method)"; break; - case 'K': fAttr = "@convention(closure)"; break; - case 'W': fAttr = "@convention(witness_method)"; break; - default: - PushBack (); - break; - } - if (fAttr != null) - type.Children.Add (new Node (NodeKind.ImplFunctionAttribute, fAttr)); - - AddChild (type, genSig); - - int numTypesToAdd = 0; - Node parameter = null; - while ((parameter = DemangleImplParamConvention()) != null) { - type = AddChild (type, parameter); - numTypesToAdd++; - } - Node result = null; - while ((result = DemangleImplResultConvention(NodeKind.ImplResult)) != null) { - type = AddChild (type, result); - numTypesToAdd++; - } - if (NextIf('z')) { - var errorResult = DemangleImplResultConvention (NodeKind.ImplErrorResult); - if (errorResult == null) - return null; - type = AddChild (type, errorResult); - numTypesToAdd++; - } - if (!NextIf ('_')) - return null; - - for (int idx = 0; idx < numTypesToAdd; idx++) { - var convTy = PopNode (NodeKind.Type); - if (convTy == null) - return null; - type.Children [type.Children.Count - idx - 1].Children.Add (convTy); - } - return CreateType (type); - } - - Node DemangleMetatype() - { - switch (NextChar ()) { - case 'f': - return CreateWithPoppedType (NodeKind.FullTypeMetadata); - case 'P': - return CreateWithPoppedType (NodeKind.GenericTypeMetadataPattern); - case 'a': - return CreateWithPoppedType (NodeKind.TypeMetadataAccessFunction); - case 'L': - return CreateWithPoppedType (NodeKind.TypeMetadataLazyCache); - case 'm': - return CreateWithPoppedType (NodeKind.Metaclass); - case 'n': - return CreateWithPoppedType (NodeKind.NominalTypeDescriptor); - case 'p': - return CreateWithChild (NodeKind.ProtocolDescriptor, PopProtocol ()); - case 'B': - return CreateWithChild (NodeKind.ReflectionMetadataBuiltinDescriptor, PopNode (NodeKind.Type)); - case 'F': - return CreateWithChild (NodeKind.ReflectionMetadataFieldDescriptor, PopNode (NodeKind.Type)); - case 'A': - return CreateWithChild (NodeKind.ReflectionMetadataAssocTypeDescriptor, PopProtocolConformance ()); - case 'C': { - var ty = PopNode (NodeKind.Type); - if (ty == null || !Node.IsNominal (ty.Children [0].Kind)) - return null; - return CreateWithChild (NodeKind.ReflectionMetadataSuperclassDescriptor, ty.Children [0]); - } - default: - return null; - } - } - - Node DemangleArchetype() - { - switch (NextChar ()) { - case 'a': { - var ident = PopNode (NodeKind.Identifier); - var archeTy = PopTypeAndGetChild (); - var assocTy = CreateType (CreateWithChildren (NodeKind.AssociatedTypeRef, archeTy, ident)); - AddSubstitution (assocTy); - return assocTy; - } - case 'y': { - var T = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); - AddSubstitution (T); - return T; - } - case 'z': { - var T = DemangleAssociatedTypeSimple (GetDependentGenericParamType (0, 0)); - AddSubstitution (T); - return T; - } - case 'Y': { - var T = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); - AddSubstitution (T); - return T; - } - case 'Z': { - var T = DemangleAssociatedTypeCompound (GetDependentGenericParamType (0, 0)); - AddSubstitution (T); - return T; - } - - default: - return null; - } - } - - Node DemangleAssociatedTypeSimple(Node genericParamIndex) { - var GPI = CreateType (genericParamIndex); - var atName = PopAssocTypeName (); - return CreateType (CreateWithChildren (NodeKind.DependentMemberType, GPI, atName)); - } - - Node DemangleAssociatedTypeCompound(Node genericParamIdx) - { - var assocTypeNames = new List (4); - bool firstElem = false; - do { - firstElem = PopNode (NodeKind.FirstElementMarker) != null; - var assocTyName = PopAssocTypeName (); - if (assocTyName == null) - return null; - assocTypeNames.Add (assocTyName); - } while (!firstElem); - - var baseClass = genericParamIdx; - - for (int index = assocTypeNames.Count - 1; index >= 0; index--) { - var assocTy = assocTypeNames [index]; - var depTy = new Node (NodeKind.DependentMemberType); - depTy = AddChild (depTy, CreateType (baseClass)); - baseClass = AddChild (depTy, assocTy); - } - return CreateType (baseClass); - } - - - - Node PopAssocTypeName() - { - var proto = PopNode (NodeKind.Type); - if (proto != null && proto.Children [0].Kind != NodeKind.Protocol) - return null; - - var id = PopNode (NodeKind.Identifier); - var assocTy = ChangeKind (id, NodeKind.DependentAssociatedTypeRef); - AddChild (assocTy, proto); - return assocTy; - } - - Node GetDependentGenericParamType(int depth, int index) - { - if (depth < 0 || index < 0) - return null; - - StringBuilder name = new StringBuilder (); - int idxChar = index; - do { - name.Append ((char)('A' + (idxChar % 26))); - idxChar /= 26; - } while (idxChar != 0); - if (depth != 0) - name.Append (depth); - var paramTy = new Node (NodeKind.DependentGenericParamType, name.ToString ()); - paramTy.Children.Add (new Node (NodeKind.Index, depth)); - paramTy.Children.Add (new Node (NodeKind.Index, index)); - return paramTy; - } - - Node DemangleGenericParamIndex() - { - if (NextIf('d')) { - var depth = DemangleIndex () + 1; - var index = DemangleIndex (); - return GetDependentGenericParamType (depth, index); - } - if (NextIf('z')) { - return GetDependentGenericParamType (0, 0); - } - return GetDependentGenericParamType (0, DemangleIndex () + 1); - } - - - Node PopProtocolConformance() - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var module = PopModule (); - var proto = PopProtocol (); - var type = PopNode (NodeKind.Type); - Node ident = null; - if (type == null) { - ident = PopNode (NodeKind.Identifier); - type = PopNode (NodeKind.Type); - } - if (genSig != null) { - type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); - } - var conf = CreateWithChildren (NodeKind.ProtocolConformance, type, proto, module); - AddChild (conf, ident); - return conf; - } - - Node DemangleThunkOrSpecialization() - { - char c = NextChar (); - switch (c) { - case 'c': return CreateWithChild (NodeKind.CurryThunk, PopNode (Node.IsEntity)); - case 'o': return new Node (NodeKind.ObjCAttribute); - case 'O': return new Node (NodeKind.NonObjCAttribute); - case 'D': return new Node (NodeKind.DynamicAttribute); - case 'd': return new Node (NodeKind.DirectMethodReferenceAttribute); - case 'a': return new Node (NodeKind.PartialApplyObjCForwarder); - case 'A': return new Node (NodeKind.PartialApplyForwarder); - case 'm': return new Node (NodeKind.MergedFunction); - case 'V': { - var baseClass = PopNode (Node.IsEntity); - var derived = PopNode (Node.IsEntity); - return CreateWithChildren (NodeKind.VTableThunk, derived, baseClass); - } - case 'W': { - var entity = PopNode (Node.IsEntity); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.ProtocolWitness, conf, entity); - } - case 'R': - case 'r': { - var thunk = new Node (c == 'R' ? NodeKind.ReabstractionThunkHelper : NodeKind.ReabstractionThunk); - var genSig = PopNode (NodeKind.DependentGenericSignature); - if (genSig != null) { - AddChild (thunk, genSig); - } - var ty2 = PopNode (NodeKind.Type); - thunk = AddChild (thunk, PopNode (NodeKind.Type)); - return AddChild (thunk, ty2); - - } - case 'g': return DemangleGenericSpecialization (NodeKind.GenericSpecialization); - case 'G': return DemangleGenericSpecialization (NodeKind.GenericSpecializationNotReAbstracted); - case 'p': { - var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecialization); - var parameter = CreateWithChild (NodeKind.GenericSpecialization, PopNode (NodeKind.Type)); - return AddChild (spec, parameter); - } - case 'P': { - var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecializationNotReAbstracted); - var parameter = CreateWithChild (NodeKind.GenericSpecialization, PopNode (NodeKind.Type)); - return AddChild (spec, parameter); - } - case 'f': return DemangleFunctionSpecialization (); - case 'K': - case 'k': { - var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper : NodeKind.KeyPathSetterThunkHelper; - var types = new List (); - var node = PopNode (); - if (node == null || node.Kind != NodeKind.Type) - return null; - do { - types.Add (node); - node = PopNode (); - } while (node != null && node.Kind == NodeKind.Type); - Node result = null; - if (node != null) { - if (node.Kind == NodeKind.DependentGenericSignature) { - var decl = PopNode (); - result = CreateWithChildren (nodeKind, decl, node); - } else { - result = CreateWithChild (nodeKind, node); - } - } else { - return null; - } - foreach (var i in types) { - result.Children.Add (i); - } - return result; - } - case 'H': - case 'h': { - var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper : NodeKind.KeyPathHashThunkHelper; - Node genericSig = null; - var types = new List (); - var node = PopNode (); - if (node != null) { - if (node.Kind == NodeKind.DependentGenericSignature) { - genericSig = node; - } else if (node.Kind == NodeKind.Type) { - types.Add (node); - } else { - return null; - } - } else { - return null; - } - - while ((node = PopNode ()) != null) { - if (node.Kind != NodeKind.Type) { - return null; - } - types.Add (node); - } - - var result = new Node (nodeKind); - foreach (var i in types) { - result.Children.Add (i); - } - if (genericSig != null) - result.Children.Add (genericSig); - return result; - } - default: - return null; - - } - } - - Node DemangleGenericSpecialization(NodeKind specKind) - { - var spec = DemangleSpecAttributes (specKind); - if (spec == null) - return null; - var typeList = PopTypeList (); - if (typeList == null) - return null; - foreach (var ty in typeList.Children) { - spec.Children.Add (CreateWithChild (NodeKind.GenericSpecializationParam, ty)); - } - return spec; - } - - Node DemangleFunctionSpecialization() - { - var spec = DemangleSpecAttributes (NodeKind.FunctionSignatureSpecialization, true); - uint parmIdx = 0; - while (spec != null && !NextIf('_')) { - spec = AddChild (spec, DemangleFuncSpecParam (parmIdx)); - parmIdx++; - } - if (!NextIf ('n')) - spec = AddChild (spec, DemangleFuncSpecParam (~(ulong)0)); - - if (spec == null) - return null; - - for (int idx = 0, num = spec.Children.Count; idx < num; idx++) { - var param = spec.Children [num - idx - 1]; - if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) - continue; - - if (param.Children.Count == 0) - continue; - var kindNd = param.Children [0]; - var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; - - switch (paramKind) { - case FunctionSigSpecializationParamKind.ConstantPropFunction: - case FunctionSigSpecializationParamKind.ConstantPropGlobal: - case FunctionSigSpecializationParamKind.ConstantPropString: - case FunctionSigSpecializationParamKind.ClosureProp: { - int fixedChildren = param.Children.Count; - Node ty = null; - while ((ty = PopNode(NodeKind.Type)) != null) { - if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) - return null; - param = AddChild (param, ty); - } - var name = PopNode (NodeKind.Identifier); - if (name == null) - return null; - string text = name.Text; - if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && - text.Length > 0 && text[0] == '_') { - text = text.Substring (1); - } - AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, text)); - param.ReverseChildren (fixedChildren); - break; - } - default: - break; - } - } - return spec; - } - - Node DemangleFuncSpecParam(ulong paramIdx) - { - var param = new Node (NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); - switch (NextChar ()) { - case 'n': - return param; - case 'c': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ClosureProp)); - case 'p': - switch (NextChar ()) { - case 'f': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropFunction)); - case 'g': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); - case 'i': - return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropInteger); - case 'd': - return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropFloat); - case 's': { - string encoding = null; - switch (NextChar ()) { - case 'b': encoding = "u8"; break; - case 'w': encoding = "u16"; break; - case 'c': encoding = "objc"; break; - default: - return null; - } - AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropString)); - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); - } - default: - return null; - } - case 'd': { - uint value = (uint)FunctionSigSpecializationParamKind.Dead; - if (NextIf ('G')) - value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'g': { - uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'x': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.SROA)); - case 'i': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.BoxToValue)); - case 's': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.BoxToStack)); - default: - return null; - } - } - - Node AddFuncSpecParamNumber(Node param, FunctionSigSpecializationParamKind kind) - { - param.Children.Add (new Node (NodeKind.FunctionSignatureSpecializationParamKind, (long)kind)); - StringBuilder str = new StringBuilder (); - while (Char.IsDigit(PeekChar())) { - str.Append (NextChar ()); - } - if (str.Length == 0) - return null; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString())); - } - - Node DemangleSpecAttributes(NodeKind specKind, bool demangleUniqueID = false) - { - bool isFragile = NextIf ('q'); - - var passID = (int)NextChar () - '0'; - if (passID < 0 || passID > 9) - return null; - - var idx = -1; - if (demangleUniqueID) - idx = DemangleNatural (); - - Node specNd = null; - if (idx >= 0) { - specNd = new Node (specKind, idx); - } else { - specNd = new Node (specKind); - } - if (isFragile) - specNd.Children.Add (new Node (NodeKind.SpecializationIsFragile)); - specNd.Children.Add (new Node (NodeKind.SpecializationPassID, passID)); - return specNd; - } - - Node DemangleWitness() - { - switch (NextChar ()) { - case 'V': - return CreateWithChild (NodeKind.ValueWitnessTable, PopNode (NodeKind.Type)); - case 'v': { - uint directness = 0; - switch (NextChar ()) { - case 'd': directness = (uint)Directness.Direct; break; - case 'i': directness = (uint)Directness.Indirect; break; - default: return null; - } - return CreateWithChildren (NodeKind.FieldOffset, new Node (NodeKind.Directness, (long)directness), - PopNode (Node.IsEntity)); - } - case 'P': - return CreateWithChild (NodeKind.ProtocolWitnessTable, PopProtocolConformance ()); - case 'G': - return CreateWithChild (NodeKind.GenericProtocolWitnessTable, PopProtocolConformance ()); - case 'I': - return CreateWithChild (NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance ()); - case 'l': { - var conf = PopProtocolConformance (); - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.LazyProtocolWitnessTableAccessor, type, conf); - } - case 'L': { - var conf = PopProtocolConformance (); - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); - } - case 'a': - return CreateWithChild (NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance ()); - case 't': { - var name = PopNode (Node.IsDeclName); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name); - } - case 'T': { - var protoTy = PopNode (NodeKind.Type); - var name = PopNode (Node.IsDeclName); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name, protoTy); - } - case 'y': { - return CreateWithChild (NodeKind.OutlinedCopy, PopNode (NodeKind.Type)); - } - case 'e': { - return CreateWithChild (NodeKind.OutlinedConsume, PopNode (NodeKind.Type)); - } - case 'r': { - return CreateWithChild (NodeKind.OutlinedRetain, PopNode (NodeKind.Type)); - } - case 's': { - return CreateWithChild (NodeKind.OutlinedRelease, PopNode (NodeKind.Type)); - } - default: - return null; - } - } - - Node DemangleSpecialType() - { - var specialChar = NextChar (); - switch (specialChar) { - case 'f': - return PopFunctionType (NodeKind.ThinFunctionType); - case 'K': - return PopFunctionType (NodeKind.AutoClosureType); - case 'U': - return PopFunctionType (NodeKind.UncurriedFunctionType); - case 'B': - return PopFunctionType (NodeKind.ObjCBlock); - case 'C': - return PopFunctionType (NodeKind.CFunctionPointer); - case 'o': - return CreateType (CreateWithChild (NodeKind.Unowned, PopNode (NodeKind.Type))); - case 'u': - return CreateType (CreateWithChild (NodeKind.Unmanaged, PopNode (NodeKind.Type))); - case 'w': - return CreateType (CreateWithChild (NodeKind.Weak, PopNode (NodeKind.Type))); - case 'b': - return CreateType (CreateWithChild (NodeKind.SILBoxType, PopNode (NodeKind.Type))); - case 'D': - return CreateType (CreateWithChild (NodeKind.DynamicSelf, PopNode (NodeKind.Type))); - case 'M': { - var MTR = DemangleMetatypeRepresentation (); - var type = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.Metatype, MTR, type)); - } - case 'm': { - var MTR = DemangleMetatypeRepresentation (); - var type = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.ExistentialMetatype, MTR, type)); - } - case 'p': - return CreateType (CreateWithChild (NodeKind.ExistentialMetatype, PopNode (NodeKind.Type))); - case 'c': { - var superClass = PopNode (NodeKind.Type); - var protocols = DemangleProtocolList (); - return CreateType (CreateWithChildren (NodeKind.ProtocolListWithClass, protocols, superClass)); - } - case 'l': { - var protocols = DemangleProtocolList (); - return CreateType (CreateWithChild (NodeKind.ProtocolListWithAnyObject, protocols)); - } - case 'X': - case 'x': { - Node signature = null, genericArgs = null; - if (specialChar == 'X') { - signature = PopNode (NodeKind.DependentGenericSignature); - if (signature == null) - return null; - genericArgs = PopTypeList (); - if (genericArgs == null) - return null; - } - - var fieldTypes = PopTypeList (); - if (fieldTypes == null) - return null; - - var layout = new Node (NodeKind.SILBoxLayout); - for (int i = 0; i < fieldTypes.Children.Count; i++) { - var fieldType = fieldTypes.Children [i]; - var isMutable = false; - if (fieldType.Children [0].Kind == NodeKind.InOut) { - isMutable = true; - fieldType = CreateType (fieldType.Children [0].Children [0]); - } - var field = new Node (isMutable ? NodeKind.SILBoxMutableField : NodeKind.SILBoxImmutableField); - field.Children.Add (fieldType); - layout.Children.Add (field); - } - var boxTy = new Node (NodeKind.SILBoxTypeWithLayout); - boxTy.Children.Add (layout); - if (signature != null) { - boxTy.Children.Add (signature); - boxTy.Children.Add (genericArgs); - } - return CreateType (boxTy); - } - case 'e': - return CreateType (new Node (NodeKind.ErrorType)); - default: - return null; - } - } - - Node DemangleMetatypeRepresentation() - { - switch (NextChar ()) { - case 't': - return new Node (NodeKind.MetatypeRepresentation, "@thin"); - case 'T': - return new Node (NodeKind.MetatypeRepresentation, "@thick"); - case 'o': - return new Node (NodeKind.MetatypeRepresentation, "@objc_metatype"); - default: - return null; - } - } - - Node DemangleFunctionEntity() - { - var kind = NodeKind.EmptyList; - var args = FunctionEntityArgs.None; - switch (NextChar ()) { - case 'D': args = FunctionEntityArgs.None; kind = NodeKind.Deallocator; break; - case 'd': args = FunctionEntityArgs.None; kind = NodeKind.Destructor; break; - case 'E': args = FunctionEntityArgs.None; kind = NodeKind.IVarDestroyer; break; - case 'e': args = FunctionEntityArgs.None; kind = NodeKind.IVarInitializer; break; - case 'i': args = FunctionEntityArgs.None; kind = NodeKind.Initializer; break; - case 'C': args = FunctionEntityArgs.TypeAndMaybePrivateName; kind = NodeKind.Allocator; break; - case 'c': args = FunctionEntityArgs.TypeAndMaybePrivateName; kind = NodeKind.Constructor; break; - case 'g': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.Getter; break; - case 'G': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.GlobalGetter; break; - case 's': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.Setter; break; - case 'm': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.MaterializeForSet; break; - case 'w': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.WillSet; break; - case 'W': args = FunctionEntityArgs.TypeAndName; kind = NodeKind.DidSet; break; - case 'a': { - args = FunctionEntityArgs.TypeAndName; - switch (NextChar ()) { - case 'O': kind = NodeKind.OwningMutableAddressor; break; - case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; - case 'P': kind = NodeKind.NativePinningMutableAddressor; break; - case 'u': kind = NodeKind.UnsafeMutableAddressor; break; - default: return null; - } - } - break; - case 'l': { - args = FunctionEntityArgs.TypeAndName; - switch (NextChar ()) { - case 'O': kind = NodeKind.OwningAddressor; break; - case 'o': kind = NodeKind.NativeOwningAddressor; break; - case 'p': kind = NodeKind.NativePinningAddressor; break; - case 'u': kind = NodeKind.UnsafeAddressor; break; - default: - return null; - } - } - break; - case 'U': args = FunctionEntityArgs.TypeAndIndex; kind = NodeKind.ExplicitClosure; break; - case 'u': args = FunctionEntityArgs.TypeAndIndex; kind = NodeKind.ImplicitClosure; break; - case 'A': args = FunctionEntityArgs.Index; kind = NodeKind.DefaultArgumentInitializer; break; - case 'p': return DemangleEntity (NodeKind.GenericTypeParamDecl); - default: - return null; - - } - - Node child1 = null, child2 = null; - switch (args) { - case FunctionEntityArgs.None: - break; - case FunctionEntityArgs.Type: - child1 = PopNode (NodeKind.Type); - break; - case FunctionEntityArgs.TypeAndName: - child2 = PopNode (NodeKind.Type); - child1 = PopNode (Node.IsDeclName); - break; - case FunctionEntityArgs.TypeAndMaybePrivateName: - child1 = PopNode (NodeKind.PrivateDeclName); - child2 = PopNode (NodeKind.Type); - break; - case FunctionEntityArgs.TypeAndIndex: - child1 = DemangleIndexAsNode (); - child2 = PopNode (NodeKind.Type); - break; - case FunctionEntityArgs.Index: - child1 = DemangleIndexAsNode (); - break; - } - var entity = CreateWithChild (kind, PopContext ()); - switch (args) { - case FunctionEntityArgs.None: - break; - case FunctionEntityArgs.Type: - case FunctionEntityArgs.Index: - entity = AddChild (entity, child1); - break; - case FunctionEntityArgs.TypeAndMaybePrivateName: - if (child1 != null) - entity = AddChild (entity, child1); - entity = AddChild (entity, child2); - break; - case FunctionEntityArgs.TypeAndName: - case FunctionEntityArgs.TypeAndIndex: - entity = AddChild (entity, child1); - entity = AddChild (entity, child2); - break; - } - return entity; - } - - Node DemangleEntity(NodeKind kind) - { - var type = PopNode (NodeKind.Type); - var name = PopNode (Node.IsDeclName); - var context = PopContext (); - return CreateWithChildren (kind, context, name, type); - } - - Node DemangleProtocolList() - { - var typeList = new Node (NodeKind.TypeList); - var protoList = CreateWithChild (NodeKind.ProtocolList, typeList); - if (PopNode(NodeKind.EmptyList) == null) { - bool firstElem = false; - do { - firstElem = PopNode (NodeKind.FirstElementMarker) != null; - var proto = PopProtocol (); - if (proto == null) - return null; - typeList.Children.Add (proto); - } while (!firstElem); - typeList.ReverseChildren (); - } - return protoList; - } - - Node DemangleProtocolListType() - { - var protoList = DemangleProtocolList (); - return CreateType (protoList); - } - - Node DemangleGenericSignature(bool hasParamCounts) - { - var sig = new Node (NodeKind.DependentGenericSignature); - if (hasParamCounts) { - while (!NextIf('l')) { - var count = 0; - if (!NextIf ('z')) - count = DemangleIndex () + 1; - if (count < 0) - return null; - sig.Children.Add (new Node (NodeKind.DependentGenericParamCount, count)); - } - } else { - sig.Children.Add (new Node (NodeKind.DependentGenericParamCount, 1L)); - } - if (sig.Children.Count == 0) - return null; - var numCounts = sig.Children.Count; - Node req = null; - while ((req = PopNode(Node.IsRequirement)) != null) { - sig.Children.Add (req); - } - sig.ReverseChildren (numCounts); - return sig; - } - - Node DemangleGenericRequirement() - { - GenericTypeKind typeKind = GenericTypeKind.Assoc; - GenericConstraintKind constraintKind = GenericConstraintKind.BaseClass; - - switch (NextChar ()) { - case 'c': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Assoc; break; - case 'C': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.CompoundAssoc; break; - case 'b': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Generic; break; - case 'B': constraintKind = GenericConstraintKind.BaseClass; typeKind = GenericTypeKind.Substitution; break; - case 't': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Assoc; break; - case 'T': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.CompoundAssoc; break; - case 's': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Generic; break; - case 'S': constraintKind = GenericConstraintKind.SameType; typeKind = GenericTypeKind.Substitution; break; - case 'm': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Assoc; break; - case 'M': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.CompoundAssoc; break; - case 'l': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Generic; break; - case 'L': constraintKind = GenericConstraintKind.Layout; typeKind = GenericTypeKind.Substitution; break; - case 'p': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Assoc; break; - case 'P': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.CompoundAssoc; break; - case 'Q': constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Substitution; break; - default: constraintKind = GenericConstraintKind.Protocol; typeKind = GenericTypeKind.Generic; PushBack (); break; - } - - Node constrTy = null; - switch (typeKind) { - case GenericTypeKind.Generic: - constrTy = CreateType (DemangleGenericParamIndex ()); - break; - case GenericTypeKind.Assoc: - constrTy = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); - AddSubstitution (constrTy); - break; - case GenericTypeKind.CompoundAssoc: - constrTy = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); - AddSubstitution (constrTy); - break; - case GenericTypeKind.Substitution: - constrTy = PopNode (NodeKind.Type); - break; - } - - switch (constraintKind) { - case GenericConstraintKind.Protocol: - return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, constrTy, PopProtocol ()); - case GenericConstraintKind.BaseClass: - return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, constrTy, PopNode (NodeKind.Type)); - case GenericConstraintKind.SameType: - return CreateWithChildren (NodeKind.DependentGenericSameTypeRequirement, constrTy, PopNode (NodeKind.Type)); - case GenericConstraintKind.Layout: { - var c = NextChar (); - Node size = null; - Node alignment = null; - string name = null; - if (c == 'U') { - name = "U"; - } else if (c == 'R') { - name = "R"; - } else if (c == 'N') { - name = "N"; - } else if (c == 'C') { - name = "C"; - } else if (c == 'D') { - name = "D"; - } else if (c == 'T') { - name = "T"; - } else if (c == 'E') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - name = "E"; - } else if (c == 'e') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - name = "e"; - } else if (c == 'M') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - alignment = DemangleIndexAsNode (); - name = "M"; - } else if (c == 'm') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - name = "m"; - } else { - return null; - } - - var nameNode = new Node (NodeKind.Identifier, name); - var layoutRequirement = CreateWithChildren (NodeKind.DependentGenericLayoutRequirement, constrTy, nameNode); - if (size != null) - AddChild (layoutRequirement, size); - if (alignment != null) - AddChild (layoutRequirement, alignment); - return layoutRequirement; - } - } - return null; - } - - Node DemangleGenericType() - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var ty = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, ty)); - } - - static int DecodeValueWitnessKind(string codeStr) - { - switch (codeStr) { - case "al": return (int)ValueWitnessKind.AllocateBuffer; - case "ca": return (int)ValueWitnessKind.AssignWithCopy; - case "ta": return (int)ValueWitnessKind.AssignWithTake; - case "de": return (int)ValueWitnessKind.DeallocateBuffer; - case "xx": return (int)ValueWitnessKind.Destroy; - case "XX": return (int)ValueWitnessKind.DestroyBuffer; - case "Xx": return (int)ValueWitnessKind.DestroyArray; - case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; - case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; - case "cp": return (int)ValueWitnessKind.InitializeWithCopy; - case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; - case "tk": return (int)ValueWitnessKind.InitializeWithTake; - case "pr": return (int)ValueWitnessKind.ProjectBuffer; - case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; - case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; - case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; - case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; - case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; - case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; - case "ug": return (int)ValueWitnessKind.GetEnumTag; - case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; - case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; - default: - return -1; - } - } - - Node DemangleValueWitness() - { - char [] code = new char [2]; - code [0] = NextChar (); - code [1] = NextChar (); - var kind = DecodeValueWitnessKind (new string (code, 0, 2)); - if (kind < 0) - return null; - var vw = new Node (NodeKind.ValueWitness, (long)kind); - return AddChild (vw, PopNode (NodeKind.Type)); - } - } - -} diff --git a/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs b/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs deleted file mode 100644 index 8e0b30e2a1f7..000000000000 --- a/src/SwiftReflector/Demangling/Swift4NodeToTLDefinition.cs +++ /dev/null @@ -1,1887 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Demangling { - public class Swift4NodeToTLDefinition { - static List nominalNodeKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure - }; - static List nominalAndProtocolNodeKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol - }; - - static List boundGenericNominalNodeKinds = new List { - NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure - }; - - static List identifierOrOperator = new List { - NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator - }; - - static List identifierOrOperatorOrPrivateDecl = new List { - NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator,NodeKind.PrivateDeclName - }; - - static List identifierOrPrivateDeclName = new List { - NodeKind.Identifier, NodeKind.PrivateDeclName - }; - string mangledName; - ulong offset; - - RuleRunner ruleRunner; - List rules; - - public Swift4NodeToTLDefinition (string mangledName, ulong offset = 0) - { - this.mangledName = mangledName; - this.offset = offset; - rules = BuildMatchRules (); - ruleRunner = new RuleRunner (rules); - } - - List BuildMatchRules () - { - return new List { - new MatchRule { - Name = "ReturnType", - NodeKind = NodeKind.ReturnType, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "ArgumentTuple", - NodeKind = NodeKind.ArgumentTuple, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "Tuple", - NodeKind = NodeKind.Tuple, - Reducer = ConvertToTuple - }, - new MatchRule { - Name = "Structure", - NodeKind = NodeKind.Structure, - Reducer = ConvertToStruct - }, - new MatchRule { - Name = "ClassEnum", - NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "Weak", - NodeKind = NodeKind.Weak, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "AutoClosure", - NodeKind = NodeKind.AutoClosureType, - Reducer = ConvertToFunctionType - }, - new MatchRule { - Name = "ProtocolList", - NodeKind = NodeKind.ProtocolList, - Reducer = ConvertToProtocolList, - ChildRules = new List { - new MatchRule { - Name = "TypeList", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "Protocol", - NodeKind = NodeKind.Protocol, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "NamedTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToNamedTupleElement, - ChildRules = new List { - new MatchRule { - Name = "NamedTupleElementName", - NodeKind = NodeKind.TupleElementName - }, - new MatchRule { - Name = "NamedTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "VariadicNamedTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToNamedTupleElement, - ChildRules = new List { - new MatchRule { - Name = "VariadicNamedTupleElementMarker", - NodeKind = NodeKind.VariadicMarker - }, - new MatchRule { - Name = "VariadicNamedTupleElementName", - NodeKind = NodeKind.TupleElementName - }, - new MatchRule { - Name = "VariadicNamedTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "VariadicMarkerTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToUnnamedTupleElement, - ChildRules = new List { - new MatchRule { - Name = "VariadicNamedTupleElementMarker", - NodeKind = NodeKind.VariadicMarker - }, - new MatchRule { - Name = "VariadicMarkerTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "TupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToUnnamedTupleElement, - ChildRules = new List { - new MatchRule { - Name = "TupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "VariadicTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToVariadicTupleElement, - ChildRules = new List { - new MatchRule { - Name = "VariadicElementType", - NodeKind = NodeKind.VariadicMarker, - }, - new MatchRule { - Name = "NamedTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "ProtocolListWithAnyObject", - NodeKind = NodeKind.ProtocolListWithAnyObject, - Reducer = ConvertToAnyObject - }, - new MatchRule { - Name = "InOutType", - NodeKind = NodeKind.Type, - Reducer = ConvertToReferenceType, - ChildRules = new List { - new MatchRule { - Name = "InOutChild", - NodeKind = NodeKind.InOut - } - } - }, - new MatchRule { - Name = "ProtocolWitnessTable", - NodeKindList = new List { - NodeKind.ProtocolWitnessTable, - NodeKind.ProtocolWitnessTableAccessor - }, - Reducer = ConvertToProtocolWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChild", - NodeKind = NodeKind.ProtocolConformance, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChildTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildProtocolTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildModuleChild", - NodeKind = NodeKind.Identifier - } - } - } - } - }, - new MatchRule { - Name = "ValueWitnessTable", - NodeKind = NodeKind.ValueWitnessTable, - Reducer = ConvertToValueWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ValueWitnessTableChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "Static", - NodeKind = NodeKind.Static, - Reducer = ConvertToStatic, - }, - new MatchRule { - Name = "UncurriedFunction", - NodeKind = NodeKind.Function, - Reducer = ConvertToMethod, - ChildRules = new List { - new MatchRule { - Name = "FunctionNominalChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "UncurriedGenericFunction", - NodeKind = NodeKind.Function, - Reducer = ConvertToMethod, - ChildRules = new List { - new MatchRule { - Name = "GenericFunctionNominalChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "GenericFunctionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "GenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "GenericFunctionTypeChildChild", - NodeKind = NodeKind.DependentGenericType - } - } - } - } - }, - new MatchRule { - Name = "Constructor", - NodeKind = NodeKind.Constructor, - Reducer = ConvertToNonAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ConstructorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "Allocator", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "Destructor", - NodeKind = NodeKind.Destructor, - Reducer = ConvertToDestructor, - ChildRules = new List { - new MatchRule { - Name = "DestructorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "Deallocator", - NodeKind = NodeKind.Deallocator, - Reducer = ConvertToDeallocator, - ChildRules = new List { - new MatchRule { - Name = "DeallocatorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "Function", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "GlobalMutableAddressor", - NodeKind = NodeKind.UnsafeMutableAddressor, - Reducer = ConvertToGlobalUnsafeMutableAddressor, - ChildRules = new List { - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "FunctionExtension", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule { - Name = "FunctionExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "FunctionExtIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "FunctionExtTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "GenericFunctionExtension", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule { - Name = "GenericFunctionExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "GenericFunctionExtensionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "GenericFunctionExtensionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "GenericFunctionExtensionTypeChildChild", - NodeKind = NodeKind.DependentGenericType - } - } - }, - } - }, - new MatchRule { - Name = "GenericFunction", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "FunctionIdentifierChild", - NodeKindList = identifierOrOperatorOrPrivateDecl, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.DependentGenericType, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - } - } - }, - } - }, - new MatchRule { - Name = "FunctionThrowsType", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionThrowsType, - ChildRules = new List { - new MatchRule { - Name = "FunctionChildThrows", - NodeKind = NodeKind.ThrowsAnnotation - }, - new MatchRule { - Name = "FunctionChildArgumentTuple", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule { - Name = "FunctionChildReturnType", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule { - Name = "FunctionType", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionType, - ChildRules = new List { - new MatchRule { - Name = "FunctionChildArgumentTuple", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule { - Name = "FunctionChildReturnType", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule { - Name = "CFunctionPointerType", - NodeKind = NodeKind.CFunctionPointer, - Reducer = ConvertToCFunctionPointerType, - ChildRules = new List { - new MatchRule { - Name = "CFunctionPointerChildArgumentTuple", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule { - Name = "CFunctionPointerChildReturnType", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule { - Name = "SubscriptGetter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToSubscriptGetter, - ChildRules = new List { - new MatchRule { - Name = "SubscriptGetterContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "SubscriptGetterIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "SubscriptGetterTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "SubscriptFunction", - NodeKind = NodeKind.FunctionType - } - } - } - } - }, - new MatchRule { - Name = "SubscriptSetter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSubscriptSetter, - ChildRules = new List { - new MatchRule { - Name = "SubscriptGetterContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "SubscriptGetterIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "SubscriptGetterTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "SubscriptFunction", - NodeKind = NodeKind.FunctionType - } - } - } - } - }, - new MatchRule { - Name = "Getter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToGetter, - ChildRules = new List { - new MatchRule { - Name = "GetterContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "GetterIdentifierChild", - NodeKindList = identifierOrPrivateDeclName - }, - new MatchRule { - Name = "GetterTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "Setter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSetter, - ChildRules = new List { - new MatchRule { - Name = "SetterContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "SetterIdentifierChild", - NodeKindList = identifierOrPrivateDeclName - }, - new MatchRule { - Name = "SetterTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "DidSet", - NodeKind = NodeKind.DidSet, - Reducer = ConvertToDidSet, - ChildRules = new List { - new MatchRule { - Name = "DidSetContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "DidSetIdentifierChild", - NodeKindList = identifierOrPrivateDeclName - }, - new MatchRule { - Name = "DidSetTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "WillSet", - NodeKind = NodeKind.WillSet, - Reducer = ConvertToWillSet, - ChildRules = new List { - new MatchRule { - Name = "WillSetContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "WillSetIdentifierChild", - NodeKindList = identifierOrPrivateDeclName - }, - new MatchRule { - Name = "WillSetTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "MaterializeForSet", - NodeKind = NodeKind.MaterializeForSet, - Reducer = ConvertToMaterializer, - ChildRules = new List { - new MatchRule { - Name = "MaterializerContextChild", - NodeKindList = nominalAndProtocolNodeKinds, - }, - new MatchRule { - Name = "MaterializerIdentifierChild", - NodeKindList = identifierOrPrivateDeclName - }, - new MatchRule { - Name = "MaterializerTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "MaterializeForSetExtension", - NodeKind = NodeKind.MaterializeForSet, - Reducer = ConvertToMaterializer, - ChildRules = new List { - new MatchRule { - Name = "MaterializeForSetExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "MaterializeForSetExtensionIdentifierChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "MaterializeForSetExtensionTypeChild", - NodeKind = NodeKind.Type, - }, - } - }, - new MatchRule { - Name = "GlobalGetter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToGlobalGetter, - ChildRules = new List { - new MatchRule { - Name = "GetterModuleChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "GetterIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "GetterTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "GlobalExtensionGetter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToGlobalGetter, - ChildRules = new List { - new MatchRule { - Name = "GetterExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "GetterExtIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "GetterExtTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "GlobalSetter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToGlobalSetter, - ChildRules = new List { - new MatchRule { - Name = "SetterModuleChild", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "SetterIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "SetterTypeChild", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "GlobalExtensionSetter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToGlobalSetter, - ChildRules = new List { - new MatchRule { - Name = "SetterExtensionModuleChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "SetterExtensionIdentifierChild", - NodeKind = NodeKind.Identifier - }, - new MatchRule { - Name = "SetterExtensionTypeChild", - NodeKind = NodeKind.Type - } - } - }, - - new MatchRule { - Name = "DependentGenericFunctionType", - NodeKind = NodeKind.DependentGenericType, - Reducer = ConvertToGenericFunction, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - }, - new MatchRule { - Name = "BoundGenericNominal", - NodeKindList = boundGenericNominalNodeKinds, - Reducer = ConvertToBoundGeneric, - ChildRules = new List { - new MatchRule { - Name = "TypeChild", - NodeKind = NodeKind.Type - }, - new MatchRule { - Name = "TypeListChild", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "Variable", - NodeKind = NodeKind.Variable, - Reducer = ConvertToVariable, - ChildRules = new List { - new MatchRule { - Name = "VariableChildContext", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "VariableChildIdentifier", - NodeKind = NodeKind.Identifier, - }, - new MatchRule { - Name = "VariableChildType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "DependentGenericParameter", - NodeKind = NodeKind.DependentGenericParamType, - Reducer = ConvertToGenericReference, - ChildRules = new List { - new MatchRule { - Name = "Depth", - NodeKind = NodeKind.Index - }, - new MatchRule { - Name = "Index", - NodeKind = NodeKind.Index - } - } - }, - new MatchRule { - Name = "DependentMemberType", - NodeKind = NodeKind.DependentMemberType, - Reducer = ConvertFirstChildToSwiftType, - ChildRules = new List { - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type - }, - } - }, - - new MatchRule { - Name = "DynamicSelf", - NodeKind = NodeKind.DynamicSelf, - Reducer = ConvertFirstChildToSwiftType, - MatchChildCount = false - }, - - new MatchRule { - Name = "ExitentialMetatype", - NodeKind = NodeKind.ExistentialMetatype, - Reducer = ConvertToMetatype, - ChildRules = new List { - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type - }, - } - }, - - // Probably should be last - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type, - Reducer = ConvertFirstChildToSwiftType, - MatchChildCount = false - } - }; - } - - public TLDefinition Convert (Node node) - { - Exceptions.ThrowOnNull (node, nameof (node)); - - - switch (node.Kind) { - case NodeKind.Type: - return Convert (node.Children [0]); - case NodeKind.Static: - return ConvertStatic (node); - case NodeKind.Function: - return ConvertFunction (node); - case NodeKind.Constructor: - case NodeKind.Allocator: - return ConvertFunctionConstructor (node); - case NodeKind.Destructor: - case NodeKind.Deallocator: - return ConvertFunctionDestructor (node); - case NodeKind.Getter: - case NodeKind.Setter: - case NodeKind.DidSet: - case NodeKind.MaterializeForSet: - case NodeKind.WillSet: - return ConvertFunctionProp (node); - case NodeKind.Variable: - return ConvertVariable (node, false); - case NodeKind.TypeMetadataAccessFunction: - return ConvertCCtor (node); - case NodeKind.TypeMetadata: - return ConvertMetadata (node); - case NodeKind.NominalTypeDescriptor: - return ConvertNominalTypeDescriptor (node); - case NodeKind.ProtocolDescriptor: - return ConvertProtocolDescriptor (node); - case NodeKind.Initializer: - return ConvertInitializer (node); - case NodeKind.TypeMetadataLazyCache: - return ConvertLazyCacheVariable (node); - case NodeKind.ProtocolWitnessTable: - case NodeKind.ProtocolWitnessTableAccessor: - case NodeKind.ValueWitnessTable: - return ConvertProtocolWitnessTable (node); - case NodeKind.FieldOffset: - return ConvertFieldOffset (node); - case NodeKind.DefaultArgumentInitializer: - return ConvertDefaultArgumentInitializer (node); - case NodeKind.Metaclass: - return ConvertMetaclass (node); - case NodeKind.UnsafeMutableAddressor: - return ConvertUnsafeMutableAddressor (node); - case NodeKind.CurryThunk: - return ConvertCurryThunk (node); - case NodeKind.Global: - return Convert (node); - default: - return null; - } - } - - TLFunction ConvertFunction (Node node) - { - var swiftType = ConvertToSwiftType (node, false, null); - var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) { - // method - var context = uncurriedFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = new SwiftName (context.Last (), false); - return new TLFunction (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset); - } - - var plainFunction = swiftType as SwiftFunctionType; - if (plainFunction != null) { - var context = plainFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context [context.Length - 2] [0] == '|') { - Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); - } - var functionName = new SwiftName (context.Last (), false); - return new TLFunction (mangledName, module, functionName, null, plainFunction, offset, operatorType); - } - return null; - } - - TLDefinition ConvertStatic (Node node) - { - if (node.Children [0].Kind == NodeKind.Variable) { - return ConvertVariable (node.Children [0], true); - } - var swiftType = ConvertToSwiftType (node, false, null); - var propType = swiftType as SwiftPropertyType; - if (propType != null) { - var context = propType.DiscretionaryString.Split ('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); - } - - var staticFunction = swiftType as SwiftStaticFunctionType; - if (staticFunction != null) { - var context = staticFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context [context.Length - 2] [0] == '|') { - Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); - } - var functionName = new SwiftName (context.Last (), false); - return new TLFunction (mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); - } - return null; - } - - TLFunction ConvertFunctionConstructor (Node node) - { - var swiftType = ConvertToSwiftType (node, false, null); - var constructor = swiftType as SwiftConstructorType; - if (constructor != null) { - var context = constructor.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = constructor.Name; - var metaType = constructor.UncurriedParameter as SwiftMetaClassType; - return new TLFunction (mangledName, module, functionName, metaType.Class, constructor, offset); - } - return null; - } - - TLFunction ConvertFunctionDestructor (Node node) - { - var swiftType = ConvertToSwiftType (node, false, null); - var destructor = swiftType as SwiftDestructorType; - if (destructor != null) { - var context = destructor.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = destructor.Name; - var className = destructor.Parameters as SwiftClassType; - if (className == null) - throw new NotSupportedException ($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType ().Name}"); - return new TLFunction (mangledName, module, functionName, className, destructor, offset); - } - return null; - } - - TLFunction ConvertFunctionProp (Node node) - { - var propType = ConvertToSwiftType (node, false, null) as SwiftPropertyType; - if (propType == null) - return null; - var context = propType.DiscretionaryString.Split ('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); - } - - TLVariable ConvertVariable (Node node, bool isStatic) - { - if (node.Children.Count != 3) - throw new ArgumentOutOfRangeException (nameof (node), $"Expected 3 children in a variable node, but got {node.Children.Count}"); - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (classType == null && !node.Children [0].HasText) - return null; - var module = classType != null ? classType.ClassName.Module : new SwiftName (node.Children [0].Text, false); - var name = new SwiftName (PrivateNamePublicName (node.Children [1]).Item2, false); - var variableType = ConvertToSwiftType (node.Children [2], false, null); - return new TLVariable (mangledName, module, classType, name, variableType, isStatic, offset); - } - - TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer (Node node) - { - if (node.Children.Count != 2) - return null; - var baseFunction = ConvertToSwiftType (node.Children [0], false, null) as SwiftBaseFunctionType; - if (baseFunction == null) - return null; - var context = baseFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var argumentIndex = (int)node.Children [1].Index; - return new TLDefaultArgumentInitializer (mangledName, module, baseFunction, argumentIndex, offset); - } - - TLFieldOffset ConvertFieldOffset (Node node) - { - if (node.Children.Count != 2 || node.Children [0].Kind != NodeKind.Directness) - return null; - var variable = ConvertToVariable (node.Children [1], false, null) as SwiftInitializerType; - if (variable == null) - return null; - - var context = variable.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var className = variable.Owner; - - return new TLFieldOffset (mangledName, module, className, node.Children [0].Index == 0, variable.Name, - variable.ReturnType, offset); - } - - TLFunction ConvertCCtor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var metaType = new SwiftMetaClassType (classType, false); - var cctor = new SwiftClassConstructorType (metaType, false); - return new TLFunction (mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, - cctor, offset); - } - - TLDirectMetadata ConvertMetadata (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLDirectMetadata (mangledName, classType.ClassName.Module, classType, offset); - } - - - TLNominalTypeDescriptor ConvertNominalTypeDescriptor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLNominalTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); - } - - TLProtocolTypeDescriptor ConvertProtocolDescriptor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLProtocolTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); - } - - TLFunction ConvertInitializer (Node node) - { - var swiftInitializer = ConvertToSwiftType (node.Children [0], false, null) as SwiftInitializerType; - var context = swiftInitializer.DiscretionaryString.Split ('.'); - return new TLFunction (mangledName, new SwiftName (context [0], false), swiftInitializer.Name, swiftInitializer.Owner, swiftInitializer, offset); - } - - TLLazyCacheVariable ConvertLazyCacheVariable (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLLazyCacheVariable (mangledName, classType.ClassName.Module, classType, offset); - } - - TLFunction ConvertProtocolWitnessTable (Node node) - { - var witnessTable = ConvertToSwiftType (node, false, null) as SwiftWitnessTableType; - - var rebuiltWitnessTable = new SwiftWitnessTableType (witnessTable.WitnessType, witnessTable.ProtocolType); - - return new TLFunction (mangledName, new SwiftName (witnessTable.DiscretionaryString, false), null, - witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); - } - - TLMetaclass ConvertMetaclass (Node node) - { - if (node.Children [0].Kind != NodeKind.Type) - return null; - var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; - if (classType == null) - return null; - var module = classType.ClassName.Module; - return new TLMetaclass (mangledName, module, classType, offset); - } - - SwiftType ConvertToGlobalUnsafeMutableAddressor (Node node, bool isReference, SwiftName name) - { - string module = node.Children [0].Text; - var operatorType = ToOperatorType (node.Children [1].Kind); - var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; - var functionName = module + - (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + - "." + funcName; - var function = ConvertToSwiftType (node.Children [2], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; - function.DiscretionaryString = functionName; - return function; - } - - TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (classType != null) { - var privatePublicName = PrivateNamePublicName (node.Children [1]).Item2; - var ofType = ConvertToSwiftType (node.Children [2], false, null); - if (classType == null || ofType == null) - return null; - - return new TLUnsafeMutableAddressor (mangledName, classType.ClassName.Module, classType, new SwiftName (privatePublicName, false), ofType, offset); - } else { - var funcType = ConvertToSwiftType (node, false, null) as SwiftFunctionType; - if (funcType != null) { - var parts = funcType.DiscretionaryString.Split ('.'); - var moduleName = parts [0]; - var funcName = funcType.Name; - return new TLUnsafeMutableAddressor (mangledName, new SwiftName (moduleName, false), null, funcName, funcType, offset); - } - } - return null; - } - - TLThunk ConvertCurryThunk (Node node) - { - TLFunction func = ConvertFunction (node.Children [0]); - return new TLThunk (ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); - } - - - - - - - - - // All the ConvertTo... functions are called from the tree reduction rules - - SwiftType ConvertToSwiftType (Node node, bool isReference, SwiftName name) - { - return ruleRunner.RunRules (node, isReference, name); - } - - SwiftType ConvertFirstChildToSwiftType (Node node, bool isReference, SwiftName name) - { - if (node.Children.Count == 0) - throw new ArgumentOutOfRangeException (nameof (node)); - return ConvertToSwiftType (node.Children [0], isReference, name); - } - - SwiftType ConvertToReferenceType (Node node, bool isReference, SwiftName name) - { - return ConvertToSwiftType (node.Children [0].Children [0], true, name); - } - - SwiftType ConvertToMetatype (Node node, bool isReference, SwiftName name) - { - var subType = ConvertFirstChildToSwiftType (node, isReference, name); - var classType = subType as SwiftClassType; - if (classType == null) - throw new ArgumentOutOfRangeException (nameof (node)); - return new SwiftMetaClassType (classType, isReference); - } - - SwiftType ConvertToTuple (Node node, bool isReference, SwiftName name) - { - if (node.Children.Count == 0) - return SwiftTupleType.Empty; - var args = new List (); - foreach (var n in node.Children) { - args.Add (ConvertToSwiftType (n, false, null)); - } - var st = new SwiftTupleType (args, isReference, name); - return st; - } - - SwiftType ConvertToVariable (Node node, bool isReference, SwiftName name) - { - var context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var variableName = node.Children [1].Text; - var variableType = ConvertToSwiftType (node.Children [2], false, null); - var initializerExpr = new SwiftInitializerType (InitializerType.Variable, variableType, context, new SwiftName (variableName, false)); - initializerExpr.DiscretionaryString = context.ClassName.ToFullyQualifiedName (true); - return initializerExpr; - } - - SwiftType ConvertToGenericReference (Node node, bool isReference, SwiftName name) - { - long depth = node.Children [0].Index; - long index = node.Children [1].Index; - return new SwiftGenericArgReferenceType ((int)depth, (int)index, isReference, name); - } - - SwiftType ConvertToBoundGeneric (Node node, bool isReference, SwiftName name) - { - var baseType = ConvertToSwiftType (node.Children [0], false, null); - var boundTypes = ConvertTypeList (node.Children [1]); - return new SwiftBoundGenericType (baseType, boundTypes, isReference, name); - } - - List ConvertTypeList (Node node) - { - var typeList = new List (node.Children.Count); - foreach (var childNode in node.Children) { - typeList.Add (ConvertToSwiftType (childNode, false, null)); - } - return typeList; - } - - SwiftType ConvertToNamedTupleElement (Node node, bool isReference, SwiftName name) - { - var offset = node.Children [0].Kind == NodeKind.VariadicMarker ? 1 : 0; - name = new SwiftName (node.Children [0 + offset].Text, false); - SwiftType type = ConvertToSwiftType (node.Children [1 + offset], isReference, name); - if (node.Children [0].Kind == NodeKind.VariadicMarker) - type.IsVariadic = true; - return type; - } - - SwiftType ConvertToVariadicTupleElement (Node node, bool isReference, SwiftName name) - { - SwiftType type = ConvertToSwiftType (node.Children [1], isReference, name); - type.IsVariadic = true; - return type; - } - - SwiftType ConvertToSubscript (Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - SwiftClassType context = null; - SwiftType extensionOn = null; - string module = null; - if (node.Children [0].Kind == NodeKind.Extension) { - var extNode = node.Children [0]; - extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); - module = extNode.Children [0].Text; - } else { - context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - module = context.ClassName.Module.Name; - } - - - var propName = new SwiftName (node.Children [1].Text, false); - var getterType = ConvertToSwiftType (node.Children [2], false, null) as SwiftFunctionType; - if (propertyType == PropertyType.Setter && getterType.ReturnType != null && !getterType.ReturnType.IsEmptyTuple) { - // oh hooray! - // If I define an indexer in swift like this: - // public subscript(T index) -> U { - // get { return getSomeUValue(index); } - // set (someUValue) { setSomeUValue(index, someUValue); } - // } - // This signature of the function attached to both properties is: - // T -> U - // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but - // the setter is (T, U) -> void - // - // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect - // what's really happening. - - // need to change this so that the tail parameters get names? Maybe just the head? - SwiftTupleType newParameters = getterType.ParameterCount == 1 ? - new SwiftTupleType (false, null, getterType.ReturnType, - getterType.Parameters.RenamedCloneOf (new SwiftName (getterType.ReturnType.Name == null || - getterType.ReturnType.Name.Name != "a" ? "a" : "b", false))) - : new SwiftTupleType (Enumerable.Concat (getterType.ReturnType.Yield (), getterType.EachParameter), - false, null); - getterType = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, getterType.CanThrow, getterType.Name); - - } - var prop = new SwiftPropertyType (context, propertyType, propName, null, getterType, false, isReference); - prop.ExtensionOn = extensionOn; - prop.DiscretionaryString = module; - return prop; - } - - SwiftType ConvertToSubscriptGetter (Node node, bool isReference, SwiftName name) - { - return ConvertToSubscript (node, isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSubscriptSetter (Node node, bool isReference, SwiftName name) - { - return ConvertToSubscript (node, isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToProperty (Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - var context = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var privatePublicName = PrivateNamePublicName (node.Children [1]); - var propName = new SwiftName (privatePublicName.Item2, false); - var privateName = privatePublicName.Item1 != null ? new SwiftName (privatePublicName.Item1, false) : null; - - if (Decomposer.IsSubscript (propName)) - return ConvertToSubscript (node, isReference, name, propertyType); - - var getterType = ConvertToSwiftType (node.Children [2], false, propertyType == PropertyType.Setter ? new SwiftName ("newValue", false) : null); - var prop = new SwiftPropertyType (context, propertyType, propName, privateName, getterType, false, isReference); - prop.DiscretionaryString = context.ClassName.ToFullyQualifiedName (true); - return prop; - } - - SwiftType ConvertToGetter (Node node, bool isReference, SwiftName name) - { - return ConvertToProperty (node, isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSetter (Node node, bool isReference, SwiftName name) - { - return ConvertToProperty (node, isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToMaterializer (Node node, bool isReference, SwiftName name) - { - if (node.Children [0].Kind == NodeKind.Extension) { - return ConvertToGlobalProperty (node, isReference, name, PropertyType.Materializer); - } - return ConvertToProperty (node, isReference, name, PropertyType.Materializer); - } - - SwiftType ConvertToDidSet (Node node, bool isReference, SwiftName name) - { - return ConvertToProperty (node, isReference, name, PropertyType.DidSet); - } - - SwiftType ConvertToWillSet (Node node, bool isReference, SwiftName name) - { - return ConvertToProperty (node, isReference, name, PropertyType.WillSet); - } - - - SwiftType ConvertToGlobalProperty (Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - string module = null; - SwiftType extensionOn = null; - if (node.Children [0].Kind == NodeKind.Extension) { - var extNode = node.Children [0]; - module = extNode.Children [0].Text; - extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); - } else { - module = node.Children [0].Text; - } - SwiftName propName = null; - SwiftName privateName = null; - if (node.Children [1].Kind == NodeKind.PrivateDeclName) { - propName = new SwiftName (node.Children [1].Children [0].Text, false); - privateName = new SwiftName (node.Children [1].Children [1].Text, false); - - } else if (node.Children [1].Kind == NodeKind.Identifier) { - propName = new SwiftName (node.Children [1].Text, false); - // materializers are formatted oddly and come in - // as globals like willSet and didSet - // We don't care very much about materializers, but enough - // that they should go to the correct place (subscript vs property). - if (Decomposer.IsSubscript (propName)) { - return ConvertToSubscript (node, isReference, name, propertyType); - } - } - var getterType = ConvertToSwiftType (node.Children [2], false, null); - var prop = new SwiftPropertyType (null, propertyType, propName, privateName, getterType, false, isReference, extensionOn); - prop.DiscretionaryString = module; - return prop; - } - - SwiftType ConvertToGlobalGetter (Node node, bool isReference, SwiftName name) - { - return ConvertToGlobalProperty (node, isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToGlobalSetter (Node node, bool isReference, SwiftName name) - { - return ConvertToGlobalProperty (node, isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToUnnamedTupleElement (Node node, bool isReference, SwiftName name) - { - var offset = node.Children [0].Kind == NodeKind.VariadicMarker ? 1 : 0; - return ConvertToSwiftType (node.Children [offset], false, null); - } - - SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name) - { - if (node.Children.Count != 1) - throw new NotSupportedException ("ProtocolList node with more than 1 child not supported"); - if (node.Children [0].Kind != NodeKind.TypeList || node.Children [0].Children.Count > 1) - throw new NotSupportedException ($"Given a ProtocolList node with child type {node.Children [0].Kind.ToString ()} and {node.Children [0].Children.Count} children, but expected a TypeList with exactly 1 child."); - // If the number of elements is 0, it means that this is an "Any" type in swift. - // I'm assuming it's lodged here as a protocol list is that an empty protocol list is - // represented by an existential container which is also used to represent a protocol list. - if (node.Children [0].Children.Count == 0) { - var className = SwiftClassName.FromFullyQualifiedName ("Swift.Any", OperatorType.None, 'P'); - var classType = new SwiftClassType (className, isReference, name); - return classType; - } - return ConvertToSwiftType (node.Children [0].Children [0], isReference, name); - } - - SwiftType ConvertToProtocolWitnessTable (Node node, bool isReference, SwiftName name) - { - var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? - WitnessType.Protocol : WitnessType.ProtocolAccessor; - var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; - var protoType = ConvertToSwiftType (node.Children [0].Children [1], false, null) as SwiftClassType; - var protoWitness = new SwiftWitnessTableType (witnessType, protoType, classType); - protoWitness.DiscretionaryString = node.Children [0].Children [2].Text; - return protoWitness; - } - - SwiftType ConvertToValueWitnessTable (Node node, bool isReference, SwiftName name) - { - var valueType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var valueWitnessTable = new SwiftWitnessTableType (WitnessType.Value, null, valueType); - valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; - return valueWitnessTable; - } - - SwiftType ConvertToFunction (Node node, bool isReference, SwiftName name) - { - string module = null; - SwiftType extensionOn = null; - if (node.Children [0].Kind == NodeKind.Extension) { - var extNode = node.Children [0]; - module = extNode.Children [0].Text; - extensionOn = ConvertToSwiftType (extNode.Children [1], false, null); - } else { - module = node.Children [0].Text; - } - var operatorType = ToOperatorType (node.Children [1].Kind); - var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; - var functionName = module + - (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + - "." + funcName; - var function = ConvertToSwiftType (node.Children [2], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; - if (extensionOn != null) - function.ExtensionOn = extensionOn; - function.DiscretionaryString = functionName; - return function; - } - - SwiftType ConvertToFunctionType (Node node, bool isReference, SwiftName name) - { - var args = ConvertToSwiftType (node.Children [0], false, null); - var ret = ConvertToSwiftType (node.Children [1], false, null); - var function = new SwiftFunctionType (args, ret, isReference, false, name); - return function; - } - - SwiftType ConvertToCFunctionPointerType (Node node, bool isReference, SwiftName name) - { - var args = ConvertToSwiftType (node.Children [0], false, null); - var ret = ConvertToSwiftType (node.Children [1], false, null); - var function = new SwiftCFunctionPointerType (args, ret, isReference, false, name); - return function; - } - - SwiftType ConvertToFunctionThrowsType (Node node, bool isReference, SwiftName name) - { - var args = ConvertToSwiftType (node.Children [1], false, null); - var ret = ConvertToSwiftType (node.Children [2], false, null); - var function = new SwiftFunctionType (args, ret, isReference, true, name); - return function; - } - - SwiftType ConvertToStatic (Node node, bool isReference, SwiftName name) - { - var functionType = ConvertToSwiftType (node.Children [0], isReference, name); - if (functionType == null) - return null; - var propType = functionType as SwiftPropertyType; - if (propType != null) { - return propType.RecastAsStatic (); - } - var uncurriedFunction = functionType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) { - var staticFunction = new SwiftStaticFunctionType (uncurriedFunction.Parameters, uncurriedFunction.ReturnType, - uncurriedFunction.IsReference, uncurriedFunction.CanThrow, - uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); - staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; - return staticFunction; - } - var baseFunctionType = functionType as SwiftBaseFunctionType; - if (baseFunctionType != null) { - var staticFunction = new SwiftStaticFunctionType (baseFunctionType.Parameters, baseFunctionType.ReturnType, - baseFunctionType.IsReference, baseFunctionType.CanThrow, - null, baseFunctionType.Name); - staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; - staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; - return staticFunction; - } - var initializerType = functionType as SwiftInitializerType; - if (initializerType != null) { - return initializerType; // this doesn't need a static recast? - } - throw new ArgumentOutOfRangeException ($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType ().Name}"); - } - - SwiftType ConvertToMethod (Node node, bool isReference, SwiftName name) - { - var instanceType = ConvertToSwiftType (node.Children [0], false, null); - var sct = instanceType as SwiftClassType; - if (sct == null) - throw new NotSupportedException ($"Expected an SwiftClassType for the instance type but got {instanceType.GetType ().Name}."); - var operatorType = ToOperatorType (node.Children [1].Kind); - var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; - var functionName = sct.ClassName.ToFullyQualifiedName (true) + - (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + - "." + funcName; - - sct.ClassName.Operator = operatorType; - var functionType = node.Children [2].Children [0]; - var genericArguments = new List (); - if (functionType.Children[0].Kind == NodeKind.DependentGenericSignature) { - genericArguments = GetGenericArguments (functionType); - functionType = functionType.Children [1].Children[0]; - } - var throws = functionType.Children.Count == 3; - var startIndex = throws ? 1 : 0; - var args = ConvertToSwiftType (functionType.Children [startIndex + 0], false, null); - var ret = ConvertToSwiftType (functionType.Children [startIndex + 1], false, null); - var uncurriedFunction = new SwiftUncurriedFunctionType (instanceType, args, ret, isReference, throws, name); - uncurriedFunction.DiscretionaryString = functionName; - uncurriedFunction.GenericArguments.AddRange (genericArguments); - return uncurriedFunction; - } - - SwiftType ConvertToAnyObject(Node node, bool isReference, SwiftName name) - { - var className = SwiftClassName.FromFullyQualifiedName ("Swift.AnyObject", OperatorType.None, 'C'); - var classType = new SwiftClassType (className, isReference, name); - return classType; - } - - OperatorType ToOperatorType (NodeKind kind) - { - switch (kind) { - default: - case NodeKind.Identifier: - return OperatorType.None; - case NodeKind.PrefixOperator: - return OperatorType.Prefix; - case NodeKind.InfixOperator: - return OperatorType.Infix; - case NodeKind.PostfixOperator: - return OperatorType.Postfix; - } - } - - SwiftType ConvertToAllocatingConstructor (Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor (node, isReference, name, true); - } - - SwiftType ConvertToNonAllocatingConstructor (Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor (node, isReference, name, false); - } - - SwiftType ConvertToConstructor (Node node, bool isReference, SwiftName name, bool isAllocating) - { - var instanceType = ConvertToSwiftType (node.Children [0], false, null); - var sct = instanceType as SwiftClassType; - if (sct == null) - throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in constructor but got {instanceType.GetType ().Name}."); - var metadata = new SwiftMetaClassType (sct, false, null); - var functionType = node.Children [1].Children [0]; - var functionThrows = functionType.Children.Count == 3 && functionType.Children [0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; - var args = ConvertToSwiftType (functionType.Children [0 + functionThrows], false, null); - var ret = ConvertToSwiftType (functionType.Children [1 + functionThrows], false, null); - var constructor = new SwiftConstructorType (isAllocating, metadata, args, ret, isReference, functionThrows != 0); - constructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); - return constructor; - } - - SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor (node, isReference, name, false); - } - - SwiftType ConvertToDeallocator (Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor (node, isReference, name, true); - } - - SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name, bool isDeallocating) - { - var instanceType = ConvertToSwiftType (node.Children [0], false, null); - var sct = instanceType as SwiftClassType; - if (sct == null) - throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType ().Name}."); - var destructor = new SwiftDestructorType (isDeallocating, sct, isReference, false); - destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); - return destructor; - } - - SwiftType ConvertToStruct (Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName (node); - var bit = TryAsBuiltInType (node, className, isReference, name); - return (SwiftType)bit ?? new SwiftClassType (className, isReference, name); - } - - SwiftType ConvertToClass (Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName (node); - return new SwiftClassType (className, isReference, name); - } - - SwiftClassName ToSwiftClassName (Node node) - { - var memberNesting = new List (); - var nestingNames = new List (); - var moduleName = BuildMemberNesting (node, memberNesting, nestingNames); - - moduleName = PatchClassName (moduleName, nestingNames); - return new SwiftClassName (moduleName, memberNesting, nestingNames); - } - - SwiftType ConvertToGenericFunction (Node node, bool isReference, SwiftName name) - { - List args = GetGenericArguments (node); - var theFunction = ConvertToSwiftType (node.Children [1], isReference, name) as SwiftBaseFunctionType; - theFunction.GenericArguments.AddRange (args); - return theFunction; - } - - List GetGenericArguments(Node node) - { - var paramCountNode = node.Children [0].Children [0]; - if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) - throw new NotSupportedException ($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString ()}"); - - var paramCount = (int)paramCountNode.Index; - List args = new List (paramCount); - for (int i = 0; i < paramCount; i++) { - args.Add (new GenericArgument (0, i)); - } - if (node.Children [0].Children.Count > 1) { - var dependentGenericSignature = node.Children [0]; - // the 0th child is the number of generic parameters (see above) - for (int i = 1; i < dependentGenericSignature.Children.Count; i++) { - var genericParamReference = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [0], false, null) as SwiftGenericArgReferenceType; - var genericConstraintType = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [1], false, null) as SwiftClassType; - MarkGenericConstraint (args, genericParamReference, genericConstraintType); - } - } - return args; - } - - static void MarkGenericConstraint (List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) - { - foreach (var genArg in args) { - if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) { - genArg.Constraints.Add (constraintType); - return; - } - } - } - - static SwiftBuiltInType TryAsBuiltInType (Node node, SwiftClassName className, bool isReference, SwiftName name) - { - switch (className.ToFullyQualifiedName ()) { - case "Swift.Int": - return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); - case "Swift.Float": - return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); - case "Swift.Bool": - return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); - case "Swift.UInt": - return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); - case "Swift.Double": - return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); - default: - return null; - } - } - - static SwiftName BuildMemberNesting (Node node, List nestings, List names) - { - var nesting = MemberNesting.Class; - switch (node.Kind) { - case NodeKind.Class: - break; - case NodeKind.Structure: - nesting = MemberNesting.Struct; - break; - case NodeKind.Enum: - nesting = MemberNesting.Enum; - break; - case NodeKind.Protocol: - nesting = MemberNesting.Protocol; - break; - default: - throw new ArgumentOutOfRangeException (nameof (node), $"Expected a nominal type node kind but got {node.Kind.ToString ()}"); - } - - var privatePublicName = PrivateNamePublicName (node.Children [1]); - var className = new SwiftName (privatePublicName.Item2, false); - SwiftName moduleName = null; - if (node.Children [0].Kind == NodeKind.Identifier || node.Children [0].Kind == NodeKind.Module) { - moduleName = new SwiftName (node.Children [0].Text, false); - } else { - // recurse before adding names. - moduleName = BuildMemberNesting (node.Children [0], nestings, names); - } - names.Add (className); - nestings.Add (nesting); - return moduleName; - } - - static Node ExtractFunctionType (Node n) - { - if (n.Kind == NodeKind.Type && n.Children.Count == 1 && n.Children [0].Kind == NodeKind.FunctionType) { - return n.Children [0]; - } - return null; - } - - - static Tuple PrivateNamePublicName (Node node) - { - if (node.Kind == NodeKind.Identifier) - return new Tuple (null, node.Text); - if (node.Kind == NodeKind.PrivateDeclName) - return new Tuple (node.Children [1].Text, node.Children [0].Text); - throw new ArgumentOutOfRangeException (nameof (node)); - } - - - - // Swift does...weird...things with some of the core types from C. - // The mangler doesn't put in the appropriate swift module, but instead lumps them all - // together into the module __C. - // The mangler also puts a number of Foundation types into the namespace __ObjC. - // Why? No idea. - // I determined this list of __ObjC types by running the following command on all the Apple built libraries: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq - // which also includes a number of inner types which we don't care about (yet). - - // The command to do this for the __C namespace is: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq - - static Dictionary classNameOntoModule = new Dictionary { - { "AVError", "AVFoundation" }, - { "AudioBuffer", "AudioToolbox" }, - { "AudioBufferList", "AudioToolbox" }, - { "CATransform3D", "CoreAnimation" }, - { "CGAffineTransform", "CoreGraphics" }, - { "CGColorSapceModel", "CoreGraphics" }, - { "CGPoint", "CoreGraphics" }, - { "CGRect", "CoreGraphics" }, - { "CGSize", "CoreGraphics" }, - { "CGVector", "CoreGraphics" }, - { "CLError", "CoreLocation" }, - { "CMTime", "CoreMedia" }, - { "CMTimeFlags", "CoreMedia" }, - { "CMTimeMapping", "CoreMedia" }, - { "CMTimeRange", "CoreMedia" }, - { "NSComparisonResult", "Foundation" }, - { "NSDecimal", "Foundation" }, - { "NSEnumerationOptions", "Foundation" }, - { "NSKeyValueChange", "Foundation" }, - { "NSKeyValueObservingOptions", "Foundation" }, - { "NSFastEnumerationState", "Foundation" }, - { "NSKeyValueChangeKey", "Foundation" }, - { "StringTransform", "Foundation" }, - { "URLFileResourceType", "Foundation" }, - { "URLResourceKey", "Foundation" }, - { "URLThumbnailDictionaryItem", "Foundation" }, - { "URLUbiquitousItemDownloadingStatus", "Foundation" }, - { "URLUbiquitousSharedItemPermissions", "Foundation" }, - { "URLUbiquitousSharedItemRole", "Foundation" }, - { "MKCoordinateSpan", "MapKit" }, - { "NSAnimationEffect", "AppKit" }, - { "SCNGeometryPrimitiveType", "SceneKit" }, - { "SCNVector3", "SceneKit" }, - { "SCNVector4", "SceneKit" }, - { "UIContentSizeCategory", "UIKit" }, - { "UIDeviceOrientation", "UIKit" }, - { "UIEdgeInsets", "UIKit" }, - { "UIInterfaceOrientation", "UIKit" }, - { "UIOffset", "UIKit" }, - { "CKError", "CloudKit" }, - { "CNError", "Contacts" }, - { "MTLSamplePosition", "Metal" }, - { "XCUIKeyboardKey", "XCTest" }, - { "BNNSActivationFunction", "Accelerate" }, - { "BNNSDataType", "Accelerate" }, - { "simd_double2x2", "Accelerate" }, - { "simd_double2x3", "Accelerate" }, - { "simd_double2x4", "Accelerate" }, - { "simd_double3x2", "Accelerate" }, - { "simd_double3x3", "Accelerate" }, - { "simd_double3x4", "Accelerate" }, - { "simd_double4x2", "Accelerate" }, - { "simd_double4x3", "Accelerate" }, - { "simd_double4x4", "Accelerate" }, - { "simd_float2x2", "Accelerate" }, - { "simd_float2x3", "Accelerate" }, - { "simd_float2x4", "Accelerate" }, - { "simd_float3x2", "Accelerate" }, - { "simd_float3x3", "Accelerate" }, - { "simd_float3x4", "Accelerate" }, - { "simd_float4x2", "Accelerate" }, - { "simd_float4x3", "Accelerate" }, - { "simd_float4x4", "Accelerate" }, - { "simd_quatd", "Accelerate" }, - { "simd_quatf", "Accelerate" } - }; - - - static SwiftName PatchClassName (SwiftName moduleName, List nestingNames) - { - // surprise! - // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version - // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough - // bottleneck to alias it. - if (moduleName.Name == "__ObjC") - moduleName = new SwiftName ("Foundation", false); - if (moduleName.Name != "__C") - return moduleName; - if (nestingNames.Count != 1) - return moduleName; - string result = null; - if (classNameOntoModule.TryGetValue (nestingNames [0].Name, out result)) - return new SwiftName (result, false); - return moduleName; - } - } -} diff --git a/src/SwiftReflector/Demangling/Swift5Demangler.cs b/src/SwiftReflector/Demangling/Swift5Demangler.cs index b52aa4bce2f2..364025118398 100644 --- a/src/SwiftReflector/Demangling/Swift5Demangler.cs +++ b/src/SwiftReflector/Demangling/Swift5Demangler.cs @@ -677,8 +677,6 @@ Node PushMultiSubstitutions (int repeatCount, int substIdx) { if (substIdx >= substitutions.Count) return null; - if (repeatCount > Swift4Demangler.kMaxRepeatCount) - return null; var nd = substitutions [substIdx]; while (repeatCount-- > 1) { PushNode (nd); @@ -708,10 +706,8 @@ Node DemangleStandardSubstitution () } default: PushBack (); - var repeatCount = DemangleNatural (); - if (repeatCount > Swift4Demangler.kMaxRepeatCount) - return null; Node nd; + var repeatCount = DemangleNatural (); if ((nd = CreateStandardSubstitution (NextChar ())) != null) { while (repeatCount-- > 1) { PushNode (nd); diff --git a/src/samples/HelloWorld/.gitignore b/src/samples/HelloWorld/.gitignore deleted file mode 100644 index 547b76a704d3..000000000000 --- a/src/samples/HelloWorld/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -*.swiftinterface* -*.swiftdoc* -*.swiftmodule* -*.abi* -*.swiftsourceinfo* -*.dylib \ No newline at end of file From 9a1753c8e5cf7c31f2bf54b991dc222d87855f23 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 17:51:00 +0100 Subject: [PATCH 08/37] Update the BindingsTool class to use System.CommandLine --- src/SwiftBindings/src/Program.cs | 139 ++++++++++++--------- src/SwiftBindings/src/SwiftBindings.csproj | 2 +- 2 files changed, 80 insertions(+), 61 deletions(-) diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs index fd41e1427ae9..9784bff6c76c 100644 --- a/src/SwiftBindings/src/Program.cs +++ b/src/SwiftBindings/src/Program.cs @@ -1,82 +1,101 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using CommandLine; +using System; +using System.Collections.Generic; +using System.IO; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.Linq; using SwiftReflector; namespace SwiftBindings { - public class Options - { - [Option('d', "dylibs", Required = true, Separator = ',', HelpText = "Paths to the dynamic libraries (dylibs), separated by commas.")] - public IEnumerable DylibPaths { get; set; } - - [Option('s', "swiftinterfaces", Required = true, Separator = ',', HelpText = "Paths to the Swift interface files, separated by commas.")] - public IEnumerable SwiftInterfacePaths { get; set; } - - [Option('o', "output", Required = true, HelpText = "Output directory for generated bindings.")] - public string OutputDirectory { get; set; } - - [Option('h', "help", HelpText = "Display this help message.")] - public bool Help { get; set; } - } - public class BindingsTool { public static void Main(string[] args) { - Parser.Default.ParseArguments(args).WithParsed(options => + Option> dylibOption = new(aliases: new [] {"-d", "--dylib"}, description: "Path to the dynamic library.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; + Option> swiftinterfaceOption = new(aliases: new [] {"-s", "--swiftinterface"}, "Path to the Swift interface file.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; + Option outputDirectoryOption = new(aliases: new [] {"-o", "--output"}, "Output directory for generated bindings.") {IsRequired = true}; + Option verbosityOption = new(aliases: new [] {"-v", "--verbosity"}, "Prints information about work in process."); + Option helpOption = new(aliases: new [] {"-h", "--help"}, "Display a help message."); + + RootCommand rootCommand = new(description: "Swift bindings generator.") { - if (options.Help) + dylibOption, + swiftinterfaceOption, + outputDirectoryOption, + verbosityOption, + helpOption, + }; + rootCommand.SetHandler((IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory, int verbosity, bool help) => { - Console.WriteLine("Usage:"); - Console.WriteLine(" -d, --dylibs Paths to the dynamic libraries (dylibs), separated by commas."); - Console.WriteLine(" -s, --swiftinterfaces Paths to the Swift interface files, separated by commas."); - Console.WriteLine(" -o, --output Output directory for generated bindings."); - return; - } + if (help) + { + Console.WriteLine("Usage:"); + Console.WriteLine(" -d, --dylib Path to the dynamic library."); + Console.WriteLine(" -s, --swiftinterfaces Path to the Swift interface file."); + Console.WriteLine(" -o, --output Output directory for generated bindings."); + Console.WriteLine(" -v, --verbosity Information about work in process."); + return; + } + + if (ValidateOptions(dylibPaths, swiftinterfacePaths, outputDirectory)) + { + for (int i = 0; i < dylibPaths.Count(); i++) + { + string dylibPath = dylibPaths.ElementAt(i); + string swiftInterfacePath = swiftinterfacePaths.ElementAt(i); - if (options.DylibPaths == null || options.SwiftInterfacePaths == null || options.OutputDirectory == null) - { - Console.WriteLine("Error: Missing required argument(s)."); - return; - } + if (!File.Exists(dylibPath)) + { + Console.Error.WriteLine($"Error: Dynamic library not found at path '{dylibPath}'."); + return; + } - if (options.DylibPaths.Count() != options.SwiftInterfacePaths.Count()) - { - Console.WriteLine("Error: Number of dylibs, interface files, and modules must match."); - return; - } + if (!File.Exists(swiftInterfacePath)) + { + Console.Error.WriteLine($"Error: Swift interface file not found at path '{swiftInterfacePath}'."); + return; + } - if (!Directory.Exists(options.OutputDirectory)) - { - Console.WriteLine($"Error: Directory '{options.OutputDirectory}' doesn't exist."); - return; - } + GenerateBindings(dylibPath, swiftInterfacePath, outputDirectory, verbosity); + } + } - for (int i = 0; i < options.DylibPaths.Count(); i++) - { - string dylibPath = options.DylibPaths.ElementAt(i); - string swiftInterfacePath = options.SwiftInterfacePaths.ElementAt(i); + }, + dylibOption, + swiftinterfaceOption, + outputDirectoryOption, + verbosityOption, + helpOption + ); - if (!File.Exists(dylibPath)) - { - Console.WriteLine($"Error: Dynamic library not found at path '{dylibPath}'."); - return; - } + rootCommand.Invoke(args); + } - if (!File.Exists(swiftInterfacePath)) - { - Console.WriteLine($"Error: Swift interface file not found at path '{swiftInterfacePath}'."); - return; - } + private static bool ValidateOptions(IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory) + { + if (dylibPaths == null || swiftinterfacePaths == null || outputDirectory == string.Empty) + { + Console.Error.WriteLine("Error: Missing required argument(s)."); + return false; + } + + if (dylibPaths.Count() != swiftinterfacePaths.Count()) + { + Console.Error.WriteLine("Error: Number of dylib and interface files must match."); + return false; + } + + if (!Directory.Exists(outputDirectory)) + { + Console.Error.WriteLine($"Error: Directory '{outputDirectory}' doesn't exist."); + return false; + } - GenerateBindings(dylibPath, swiftInterfacePath, options.OutputDirectory); - } - }); + return true; } - public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory) + public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory, int verbositry = 0) { BindingsCompiler bindingsCompiler = new BindingsCompiler(); var errors = new ErrorHandling (); diff --git a/src/SwiftBindings/src/SwiftBindings.csproj b/src/SwiftBindings/src/SwiftBindings.csproj index b7264f2a28f0..991ccbd4e6fa 100644 --- a/src/SwiftBindings/src/SwiftBindings.csproj +++ b/src/SwiftBindings/src/SwiftBindings.csproj @@ -11,6 +11,6 @@ - + From cad936e8632dd4709b3b6d794e0d892166a14c8d Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 17:53:21 +0100 Subject: [PATCH 09/37] Remove SyntaxDynamo.SwiftLang files --- .../TypeMapping/SwiftTypeToSLType.cs | 169 -------- src/SwiftReflector/TypeMapping/TypeMapper.cs | 20 - .../TypeMapping/TypeSpecToSLType.cs | 393 ------------------ .../SyntaxDynamo.SwiftLang/Enums.cs | 89 ---- .../SyntaxDynamo.SwiftLang/ISLExpr.cs | 11 - .../SyntaxDynamo.SwiftLang/ISLLineable.cs | 8 - .../SyntaxDynamo.SwiftLang/ISLStatement.cs | 8 - .../SyntaxDynamo.SwiftLang/SLAddressOf.cs | 29 -- .../SyntaxDynamo.SwiftLang/SLArgument.cs | 35 -- .../SyntaxDynamo.SwiftLang/SLAsExpr.cs | 19 - .../SyntaxDynamo.SwiftLang/SLAttribute.cs | 81 ---- .../SyntaxDynamo.SwiftLang/SLBaseExpr.cs | 82 ---- .../SyntaxDynamo.SwiftLang/SLBinaryExpr.cs | 93 ----- .../SyntaxDynamo.SwiftLang/SLBinding.cs | 54 --- .../SyntaxDynamo.SwiftLang/SLClass.cs | 163 -------- .../SyntaxDynamo.SwiftLang/SLClosure.cs | 39 -- .../SyntaxDynamo.SwiftLang/SLClosureCall.cs | 26 -- .../SyntaxDynamo.SwiftLang/SLCodeBlock.cs | 35 -- .../SyntaxDynamo.SwiftLang/SLCommaListExpr.cs | 30 -- .../SyntaxDynamo.SwiftLang/SLComment.cs | 42 -- .../SLConditionalCompilation.cs | 48 --- .../SyntaxDynamo.SwiftLang/SLConstant.cs | 69 --- .../SyntaxDynamo.SwiftLang/SLDeclaration.cs | 63 --- .../SyntaxDynamo.SwiftLang/SLDoCatch.cs | 63 --- .../SyntaxDynamo.SwiftLang/SLFile.cs | 75 ---- .../SyntaxDynamo.SwiftLang/SLFunc.cs | 162 -------- .../SyntaxDynamo.SwiftLang/SLFunctionCall.cs | 68 --- .../SLGenericConstraint.cs | 26 -- .../SLGenericTypeDeclaration.cs | 111 ----- .../SyntaxDynamo.SwiftLang/SLIdentifier.cs | 29 -- .../SyntaxDynamo.SwiftLang/SLIfElse.cs | 61 --- .../SyntaxDynamo.SwiftLang/SLImport.cs | 83 ---- .../SyntaxDynamo.SwiftLang/SLInheritance.cs | 21 - .../SyntaxDynamo.SwiftLang/SLInject.cs | 19 - .../SyntaxDynamo.SwiftLang/SLLetMatch.cs | 30 -- .../SyntaxDynamo.SwiftLang/SLLine.cs | 29 -- .../SLLineableOperator.cs | 24 -- .../SyntaxDynamo.SwiftLang/SLNameTypePair.cs | 66 --- .../SLNamedClosureCall.cs | 26 -- .../SyntaxDynamo.SwiftLang/SLParameter.cs | 73 ---- .../SyntaxDynamo.SwiftLang/SLParameterList.cs | 40 -- .../SLParenthesisExpression.cs | 21 - .../SyntaxDynamo.SwiftLang/SLPostBang.cs | 32 -- .../SyntaxDynamo.SwiftLang/SLProperty.cs | 63 --- .../SyntaxDynamo.SwiftLang/SLReturn.cs | 26 -- .../SyntaxDynamo.SwiftLang/SLSubscript.cs | 73 ---- .../SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs | 37 -- .../SyntaxDynamo.SwiftLang/SLSwitch.cs | 107 ----- .../SyntaxDynamo.SwiftLang/SLThrow.cs | 25 -- .../SyntaxDynamo.SwiftLang/SLTryBang.cs | 30 -- .../SyntaxDynamo.SwiftLang/SLTupleExpr.cs | 29 -- .../SyntaxDynamo.SwiftLang/SLType.cs | 389 ----------------- .../SyntaxDynamo.SwiftLang/SLUnaryExpr.cs | 36 -- .../SyntaxDynamo.SwiftLang/SLVariadicExpr.cs | 28 -- 54 files changed, 3508 deletions(-) delete mode 100644 src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs delete mode 100644 src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs delete mode 100644 src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs diff --git a/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs b/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs deleted file mode 100644 index 46b11243e918..000000000000 --- a/src/SwiftReflector/TypeMapping/SwiftTypeToSLType.cs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SyntaxDynamo.SwiftLang; -using SwiftReflector.ExceptionTools; -using System.Collections.Generic; -using System.Linq; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.TypeMapping { - public class SwiftTypeToSLType { - TypeMapper typeMapper; - bool IncludeModule { get; } - public SwiftTypeToSLType (TypeMapper typeMapper, bool includeModule = false) - { - this.typeMapper = Exceptions.ThrowOnNull (typeMapper, "typeMapper"); - IncludeModule = includeModule; - } - - - public SLType MapType (SLImportModules modules, SwiftType st) - { - switch (st.Type) { - case CoreCompoundType.Scalar: - return ToScalar ((SwiftBuiltInType)st); - case CoreCompoundType.Tuple: - return ToTuple (modules, (SwiftTupleType)st); - case CoreCompoundType.MetaClass: - // Steve sez: - // Today, type objects are never explicit arguments to functions - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 3, "Asked to map an internal type object to an SLType - this should never happen"); - case CoreCompoundType.Class: - return ToClass (modules, (SwiftClassType)st); - case CoreCompoundType.BoundGeneric: - return ToClass (modules, (SwiftBoundGenericType)st); - case CoreCompoundType.ProtocolList: - return ToProtocol (modules, (SwiftProtocolListType)st); - case CoreCompoundType.GenericReference: - return ToGenericArgReference (modules, (SwiftGenericArgReferenceType)st); - case CoreCompoundType.Function: - return ToClosure (modules, (SwiftFunctionType)st); - default: - throw new NotImplementedException (); - } - } - - public SLType MapType (SLImportModules modules, SwiftClassName cl) - { - return ToClass (modules, cl); - } - - - static SLType ToScalar (SwiftBuiltInType st) - { - switch (st.BuiltInType) { - case CoreBuiltInType.Bool: - return SLSimpleType.Bool; - case CoreBuiltInType.Double: - return SLSimpleType.Double; - case CoreBuiltInType.Float: - return SLSimpleType.Float; - case CoreBuiltInType.Int: - return SLSimpleType.Int; - case CoreBuiltInType.UInt: - return SLSimpleType.UInt; - default: - throw new ArgumentOutOfRangeException (nameof (st)); - } - } - - public void MapParams (SLImportModules modules, List output, SwiftType parameters) - { - if (parameters is SwiftTupleType) { - SLTupleType sltuple = typeMapper.SwiftTypeMapper.ToParameters (modules, (SwiftTupleType)parameters); - output.AddRange (sltuple.Elements); - } else { - output.Add (new SLNameTypePair (parameters.IsReference || MustBeInOut (parameters) ? SLParameterKind.InOut : SLParameterKind.None, new SLIdentifier ("noName"), MapType (modules, parameters))); - } - } - - bool MustBeInOut (SwiftType st) - { - SwiftProtocolListType protList = st as SwiftProtocolListType; - if (protList != null) { - if (protList.Protocols.Count > 1) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 14, "Protocol lists of size > 1 aren't supported. Yet."); - return MustBeInOut (protList.Protocols [0]); - } - if (st.IsClass) - return false; - return typeMapper.MustForcePassByReference (st); - } - - public SLTupleType ToParameters (SLImportModules modules, SwiftTupleType st) - { - List contents = st.Contents.Select ( - (swiftType, i) => new SLNameTypePair ( - swiftType.IsReference || MustBeInOut (swiftType) ? SLParameterKind.InOut : SLParameterKind.None, - ConjureIdentifier (swiftType.Name, i), - MapType (modules, swiftType))).ToList (); - return new SLTupleType (contents); - } - - - SLTupleType ToTuple (SLImportModules modules, SwiftTupleType st) - { - List contents = st.Contents.Select ( - (swiftType, i) => new SLNameTypePair ( - (swiftType.Name == null ? SLIdentifier.Anonymous : new SLIdentifier (swiftType.Name.Name)), - MapType (modules, swiftType))).ToList (); - return new SLTupleType (contents); - } - - SLSimpleType ToClass (SLImportModules modules, SwiftClassType st) - { - return ToClass (modules, st.ClassName, IncludeModule); - } - - SLType ToClass (SLImportModules modules, SwiftBoundGenericType gt) - { - SLType slType = MapType (modules, gt.BaseType); - SLSimpleType baseType = slType as SLSimpleType; - if (baseType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 15, $"Mapping SwiftType to SLType, expected a simple type, but got {baseType.GetType ().Name}."); - IEnumerable boundTypes = gt.BoundTypes.Select (st => MapType (modules, st)); - return new SLBoundGenericType (baseType.Name, boundTypes); - } - - static SLSimpleType ToClass (SLImportModules modules, SwiftClassName className, bool includeModule = false) - { - modules.AddIfNotPresent (className.Module.Name); - return new SLSimpleType (className.ToFullyQualifiedName (includeModule)); - } - - SLSimpleType ToProtocol (SLImportModules modules, SwiftProtocolListType protocol) - { - if (protocol.Protocols.Count > 1) - throw new NotSupportedException ("Protocol lists > 1 not supported (yet)."); - SwiftClassType cl = protocol.Protocols [0]; - return ToClass (modules, cl); - } - - SLType ToGenericArgReference (SLImportModules modules, SwiftGenericArgReferenceType arg) - { - return new SLGenericReferenceType (arg.Depth, arg.Index, associatedTypePath: arg.AssociatedTypePath); - } - - SLType ToClosure (SLImportModules modules, SwiftFunctionType func) - { - var args = func.EachParameter.Select (p => new SLUnnamedParameter (MapType (modules, p), ToParameterKind (p))); - var returnType = MapType (modules, func.ReturnType); - var closureResult = new SLFuncType (returnType, args); - return closureResult; - } - - static SLIdentifier ConjureIdentifier (SwiftName name, int index) - { - return new SLIdentifier (name != null ? name.Name : String.Format ("noName{0}", index)); - } - - static SLParameterKind ToParameterKind (SwiftType p) - { - if (p.IsReference) - return SLParameterKind.InOut; - return SLParameterKind.None; - } - } -} diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/TypeMapping/TypeMapper.cs index 6305deeaef0e..ea2ad9d4840e 100644 --- a/src/SwiftReflector/TypeMapping/TypeMapper.cs +++ b/src/SwiftReflector/TypeMapping/TypeMapper.cs @@ -16,8 +16,6 @@ namespace SwiftReflector.TypeMapping { public class TypeMapper { public TypeDatabase TypeDatabase { get; private set; } - TypeSpecToSLType specMapper, overrideSpecMapper; - SwiftTypeToSLType swiftTypeMapper; UnicodeMapper unicodeMapper; HashSet loadedFiles = new HashSet (); @@ -25,20 +23,6 @@ public TypeMapper (List typeDatabasePaths, UnicodeMapper unicodeMapper) { TypeDatabase = new TypeDatabase (); this.unicodeMapper = unicodeMapper; - - // We check 'SwiftyOptions' for errors so each 'typeDatabasePath' at this point should be a valid directory. - // foreach (var typeDatabasePath in typeDatabasePaths) { - // if (Directory.Exists (typeDatabasePath)) { - // foreach (string fileName in Directory.GetFiles (typeDatabasePath)) - // AddTypeDatabase (fileName); - // } else if (File.Exists (typeDatabasePath)) { - // AddTypeDatabase (typeDatabasePath); - // } - // } - - specMapper = new TypeSpecToSLType (this, false); - overrideSpecMapper = new TypeSpecToSLType (this, true); - swiftTypeMapper = new SwiftTypeToSLType (this); } public void AddTypeDatabase (string fileName) @@ -1094,10 +1078,6 @@ public bool MustForcePassByReference (BaseDeclaration context, TypeSpec sp) return MustForcePassByReference (en); } - public TypeSpecToSLType TypeSpecMapper { get { return specMapper; } } - public TypeSpecToSLType OverrideTypeSpecMapper { get { return overrideSpecMapper; } } - public SwiftTypeToSLType SwiftTypeMapper { get { return swiftTypeMapper; } } - public static bool IsSwiftPointerType (string fullTypeName) { return fullTypeName == "Swift.UnsafePointer" || fullTypeName == "Swift.UnsafeMutablePointer" diff --git a/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs b/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs deleted file mode 100644 index 8ea5691ce834..000000000000 --- a/src/SwiftReflector/TypeMapping/TypeSpecToSLType.cs +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SyntaxDynamo.SwiftLang; -using System.Collections.Generic; -using SwiftReflector.SwiftXmlReflection; -using System.Linq; -using SwiftReflector.ExceptionTools; -using SyntaxDynamo; - -namespace SwiftReflector.TypeMapping { - public class TypeSpecToSLType { - TypeMapper parent; - bool isForOverride; - public TypeSpecToSLType (TypeMapper parent, bool forOverride) - { - this.parent = Exceptions.ThrowOnNull (parent, nameof (parent)); - isForOverride = forOverride; - } - - public SLType MapTypeSimplified (SLImportModules modules, TypeSpec spec) - { - switch (spec.Kind) { - case TypeSpecKind.Named: - var named = (NamedTypeSpec)spec; - if (TypeSpec.IsBuiltInValueType (spec)) { - return new SLSimpleType (named.Name); - } else { - return new SLSimpleType ("UnsafeRawPointer"); - } - case TypeSpecKind.Closure: - case TypeSpecKind.Tuple: - case TypeSpecKind.ProtocolList: - return new SLSimpleType ("UnsafeRawPointer"); - default: - throw new ArgumentOutOfRangeException ("spec"); - } - } - - public SLType MapType (BaseDeclaration declContext, SLImportModules modules, TypeSpec spec, bool isForReturn) - { - switch (spec.Kind) { - case TypeSpecKind.Named: - return MapType (declContext, modules, (NamedTypeSpec)spec); - case TypeSpecKind.Closure: - return MapType (declContext, modules, (ClosureTypeSpec)spec, isForReturn); - case TypeSpecKind.Tuple: - return MapType (declContext, modules, (TupleTypeSpec)spec); - case TypeSpecKind.ProtocolList: - return MapType (declContext, modules, (ProtocolListTypeSpec)spec); - default: - throw new ArgumentOutOfRangeException ("spec"); - } - } - - SLType MapType (BaseDeclaration declContext, SLImportModules modules, NamedTypeSpec spec) - { - SLType retval = null; - if (spec.HasModule (declContext, this.parent)) - modules.AddIfNotPresent (spec.Module); - if (declContext.IsTypeSpecGeneric (spec) && !spec.ContainsGenericParameters) { - Tuple depthIndex = declContext.GetGenericDepthAndIndex (spec); - retval = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); - } else if (spec.ContainsGenericParameters) { - retval = new SLBoundGenericType (spec.NameWithoutModule, spec.GenericParameters.Select (p => MapType (declContext, modules, p, false))); - } else { - if (declContext.IsProtocolWithAssociatedTypesFullPath (spec, parent)) { - // for T.AssocType - var genPart = spec.Module; - var depthIndex = declContext.GetGenericDepthAndIndex (genPart); - var newGenPart = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); - retval = new SLSimpleType ($"{newGenPart}.{spec.NameWithoutModule}"); - } else { - retval = new SLSimpleType (spec.NameWithoutModule); - } - } - - if (spec.InnerType == null) - return retval; - else - return new SLCompoundType (retval, MapType (declContext, modules, spec.InnerType)); - } - - SLType MapType (BaseDeclaration declContext, SLImportModules modules, ClosureTypeSpec spec, bool isForReturn) - { - var argumentTypes = new List (); - if (spec.Arguments is TupleTypeSpec) { - argumentTypes.AddRange (((TupleTypeSpec)spec.Arguments).Elements.Select (arg => MapType (declContext, modules, arg, false))); - } else { - argumentTypes.Add (MapType (declContext, modules, spec.Arguments, false)); - } - - - SLFuncType funcType = null; - if (isForOverride) { - var arguments = new SLTupleType (argumentTypes.Select (at => new SLNameTypePair ((string)null, at)).ToList ()); - if (spec.ReturnType.IsEmptyTuple) { - // Action -> - funcType = new SLFuncType (arguments ?? new SLTupleType (), new SLTupleType (), hasThrows: spec.Throws); - } else { - // Func - SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); - funcType = new SLFuncType (arguments ?? new SLTupleType (), slRetType, hasThrows: spec.Throws); - } - if (spec.IsEscaping) { - SLAttribute.Escaping ().AttachBefore (funcType); - } - } else if (isForReturn) { - var arguments = argumentTypes.Select (at => new SLNameTypePair ("_", at)).ToList (); - - if (spec.ReturnType.IsEmptyTuple) { - // Action -> - // (UnsafeMutablePointer<(argumentTypes)>) -> () - var pointerToArgTuple = arguments.Count != 0 ? - new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) - : null; - if (pointerToArgTuple != null) { - funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", pointerToArgTuple)), - new SLTupleType ()); - } else { // should never happen? - funcType = new SLFuncType (new SLTupleType (), new SLTupleType ()); - } - } else { - // Func - // (UnsafeMutablePointer,UnsafeMutablePointer<(argumentTypes)>) -> () - SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); - var pointerToArgTuple = arguments.Count != 0 ? - new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) - : null; - SLType returnSLType = null; - if (spec.Throws && !spec.IsAsync) { - var returnTuple = new SLTupleType (new SLNameTypePair ((string)null, slRetType), - new SLNameTypePair ((string)null, new SLSimpleType ("Swift.Error")), - new SLNameTypePair ((string)null, SLSimpleType.Bool)); - returnSLType = new SLBoundGenericType ("UnsafeMutablePointer", returnTuple); - } else if (spec.IsAsync) { - throw new NotImplementedException ("Not handling async return closure mapping (yet)"); - } else { - returnSLType = new SLBoundGenericType ("UnsafeMutablePointer", slRetType); - } - - if (pointerToArgTuple != null) { - funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", returnSLType), - new SLNameTypePair ("_", pointerToArgTuple)), new SLTupleType ()); - } else { - funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", returnSLType)), - new SLTupleType ()); - } - } - } else { - var arguments = argumentTypes.Select (at => new SLNameTypePair ("_", at)).ToList (); - var opaquePointerArg = new SLNameTypePair ("_", SLSimpleType.OpaquePointer); - - if (spec.ReturnType.IsEmptyTuple) { - // Action -> - // (UnsafeMutablePointer<(argumentTypes)>, OpaquePointer) -> () - var pointerToArgTuple = arguments.Count != 0 ? - new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) - : null; - if (pointerToArgTuple != null) { - funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", pointerToArgTuple), opaquePointerArg), - new SLTupleType ()); - } else { // should never happen? - funcType = new SLFuncType (new SLTupleType (opaquePointerArg), new SLTupleType ()); - } - - } else { - // Func - // (UnsafeMutablePointer,UnsafeMutablePointer<(argumentTypes)>) -> () - // SLType slRetType = MapType (declContext, modules, spec.ReturnType, true); - // var pointerToArgTuple = arguments.Count != 0 ? - // new SLBoundGenericType ("UnsafeMutablePointer", new SLTupleType (arguments)) - // : null; - // var slReturnTypePtr = MethodWrapping.ClosureReturnType (slRetType, spec); - // if (pointerToArgTuple != null) { - // funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", slReturnTypePtr), - // new SLNameTypePair ("_", pointerToArgTuple), - // opaquePointerArg), - // new SLTupleType ()); - // } else { - // funcType = new SLFuncType (new SLTupleType (new SLNameTypePair ("_", slReturnTypePtr), - // opaquePointerArg), - // new SLTupleType ()); - // } - } - - if (!isForReturn) { - funcType.Attributes.Add (new SLAttribute ("escaping", null)); - } - } - - - return funcType; - } - - SLType MapType (BaseDeclaration declContext, SLImportModules modules, TupleTypeSpec spec) - { - return new SLTupleType (spec.Elements.Select (p => new SLNameTypePair ((string)null, MapType (declContext, modules, p, false))).ToList ()); - } - - SLType MapType (BaseDeclaration declContext, SLImportModules modules, ProtocolListTypeSpec spec) - { - return new SLProtocolListType (spec.Protocols.Keys.Select (proto => MapType (declContext, modules, proto))); - } - - public void MapParams (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, List output, List parameters, - bool dontChangeInOut, SLGenericTypeDeclarationCollection genericDeclaration = null, bool remapSelf = false, string selfReplacement = "") - { - output.AddRange (parameters.Select ((p, i) => ToParameter (typeMapper, func, modules, p, i, dontChangeInOut, genericDeclaration, remapSelf, selfReplacement))); - } - - public void MapParamsToCSharpTypes (SLImportModules modules, List output, List parameters) - { - output.AddRange (parameters.Select ((p, i) => ToParameterToCSharpTypes (modules, p, i))); - } - - SLParameter ToParameterToCSharpTypes (SLImportModules modules, ParameterItem p, int index) - { - return new SLParameter (p.PublicName, p.PrivateName, MapTypeSimplified (modules, p.TypeSpec), - p.IsInOut && TypeSpec.IsBuiltInValueType (p.TypeSpec) ? SLParameterKind.InOut : SLParameterKind.None); - } - - public SLParameter ToParameter (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, ParameterItem p, int index, - bool dontChangeInOut, SLGenericTypeDeclarationCollection genericDecl = null, bool remapSelf = false, string remappedSelfName = "") - { - var pIsGeneric = func.IsTypeSpecGeneric (p) && p.TypeSpec is NamedTypeSpec; - var parmTypeEntity = !pIsGeneric ? typeMapper.GetEntityForTypeSpec (p.TypeSpec) : null; - if (parmTypeEntity == null && !pIsGeneric && p.IsInOut) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 45, $"In function {func.ToFullyQualifiedName ()}, unknown type parameter type {p.PublicName}:{p.TypeName}."); - var parmKind = p.IsInOut && (pIsGeneric || !parmTypeEntity.IsStructOrEnum) ? SLParameterKind.InOut : SLParameterKind.None; - SLType parmType = null; - - var pTypeSpec = remapSelf ? p.TypeSpec.ReplaceName ("Self", remappedSelfName) : p.TypeSpec; - - if (genericDecl != null) { - GatherGenerics (typeMapper, func, modules, pTypeSpec, genericDecl); - } - if (pIsGeneric) { - if (pTypeSpec.ContainsGenericParameters) { - var ns = pTypeSpec as NamedTypeSpec; - var boundGen = new SLBoundGenericType (ns.Name, - pTypeSpec.GenericParameters.Select (genParm => { - return MapType (func, modules, genParm, true); - })); - if (parent.MustForcePassByReference (func, ns)) { - boundGen = new SLBoundGenericType ("UnsafeMutablePointer", boundGen); - } - parmType = boundGen; - } else { - var namedType = pTypeSpec as NamedTypeSpec; - if (namedType == null) - throw new NotImplementedException ("Can only have a named type spec here."); - var depthIndex = func.GetGenericDepthAndIndex (namedType.Name); - var gd = func.GetGeneric (depthIndex.Item1, depthIndex.Item2); - var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2, func.IsTypeSpecGenericMetatypeReference (namedType)); - parmType = genRef; - } - } else { - parmType = MapType (func, modules, pTypeSpec, false); - if (pIsGeneric) { - Tuple depthIndex = func.GetGenericDepthAndIndex (pTypeSpec); - parmType = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); - } else if (parent.MustForcePassByReference (func, pTypeSpec) && !dontChangeInOut) { - parmType = new SLBoundGenericType (p.IsInOut ? "UnsafeMutablePointer" : "UnsafePointer", parmType); - } - } - if (isForOverride && p.IsVariadic) { - // if we get here, then parmType is an SLSimpleType of SwiftArray - // we're going to turn it into "someType ..." - var oldParmType = parmType as SLBoundGenericType; - parmType = new SLVariadicType (oldParmType.BoundTypes [0]); - } - var publicName = !p.NameIsRequired ? null : ConjureIdentifier (p.PublicName, index); - var privateName = !String.IsNullOrEmpty (p.PrivateName) ? p.PrivateName : null; - return new SLParameter (publicName, ConjureIdentifier (privateName, index), parmType, parmKind); - } - - - void GatherGenerics (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type, - SLGenericTypeDeclarationCollection genericDeclations) - { - var redundantConstraints = new Dictionary> (); - GatherGenerics (typeMapper, func, modules, type, genericDeclations, redundantConstraints); - - // In the process of gathering generics, there may be generic types with - // constraints that are redundant. In the process of gathering the generics, I - // collect all the generic reference types that have constraints that would be - // considered redundant. - // After gathering, all constraints are looked up and if they're redundant, they get removed. - - foreach (var generic in genericDeclations) { - var genericName = generic.Name.Name; - List forbiddenList = null; - if (!redundantConstraints.TryGetValue (genericName, out forbiddenList)) - continue; - for (int i = generic.Constraints.Count - 1; i >= 0; i--) { - var candidateConstraint = generic.Constraints [i]; - foreach (var forbidden in forbiddenList) { - var forbiddenInherit = forbidden as InheritanceConstraint; - if (candidateConstraint.IsInheritance && forbidden != null) { - var candidateString = candidateConstraint.SecondType.ToString (); - var forbiddenNamedTypeSpec = forbiddenInherit.InheritsTypeSpec as NamedTypeSpec; - if (forbiddenNamedTypeSpec == null) - continue; - var verbottenString = forbiddenNamedTypeSpec.NameWithoutModule; - if (candidateString == verbottenString) { - generic.Constraints.RemoveAt (i); - break; - } - } - } - } - } - } - - void GatherGenerics (TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type, - SLGenericTypeDeclarationCollection genericDecl, Dictionary> redundantConstraints) - { - if (!func.IsTypeSpecGeneric (type)) - return; - - if (type.ContainsGenericParameters) { - var entity = typeMapper.GetEntityForTypeSpec (type); - if (entity != null) { - for (int i = 0; i < entity.Type.Generics.Count; i++) { - var genDecl = entity.Type.Generics [i]; - var originalGenTypeSpec = type.GenericParameters [i]; - if (originalGenTypeSpec is NamedTypeSpec named) { - var depthIndex = func.GetGenericDepthAndIndex (originalGenTypeSpec); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - continue; - var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); - var genRefName = genRef.Name; - List constList = null; - if (!redundantConstraints.TryGetValue (genRefName, out constList)) { - constList = new List (); - redundantConstraints.Add (genRefName, constList); - } - constList.AddRange (genDecl.Constraints); - } else if (originalGenTypeSpec is ClosureTypeSpec closure) { - GatherGenerics (typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints); - GatherGenerics (typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints); - } else if (originalGenTypeSpec is TupleTypeSpec tuple) { - foreach (var tupleSpec in tuple.Elements) { - GatherGenerics (typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints); - } - } - } - } - foreach (var subType in type.GenericParameters) - GatherGenerics (typeMapper, func, modules, subType, genericDecl, redundantConstraints); - } else { -// if (type is NamedTypeSpec named) { -// var depthIndex = func.GetGenericDepthAndIndex (type); -// var gd = func.GetGeneric (depthIndex.Item1, depthIndex.Item2); -// var genRef = new SLGenericReferenceType (depthIndex.Item1, depthIndex.Item2); -// var sldecl = new SLGenericTypeDeclaration (new SLIdentifier (genRef.Name)); -// #if SWIFT4 -// if (depthIndex.Item1 >= func.GetMaxDepth ()) { -// sldecl.Constraints.AddRange (gd.Constraints.Select (baseConstraint => -// MethodWrapping.ToSLGenericConstraint (func, baseConstraint, genRef.ToString ()) -// )); -// } -// #else -// sldecl.Constraints.AddRange (gd.Constraints.Select (bc => { -// InheritanceConstraint inh = bc as InheritanceConstraint; -// if (inh == null) -// throw new CompilerException ("Equality constraints not supported (yet)"); -// return new SLGenericConstraint (true, new SLSimpleType (genRef.Name), parent.TypeSpecMapper.MapType (func, modules, inh.InheritsTypeSpec)); -// })); -// #endif -// genericDecl.Add (sldecl); -// } else if (type is ClosureTypeSpec closure) { -// GatherGenerics (typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints); -// GatherGenerics (typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints); -// } else if (type is TupleTypeSpec tuple) { -// foreach (var tupleSpec in tuple.Elements) { -// GatherGenerics (typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints); -// } -// } - } - } - - public static SLIdentifier ConjureIdentifier (string name, int index) - { - name = name ?? $"xamarin_anonymous_parameter{index}"; - - return new SLIdentifier (name); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs deleted file mode 100644 index ef2b642d8f27..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/Enums.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public enum ImportKind { - None, - TypeAlias, - Struct, - Class, - Enum, - Protocol, - Var, - Func, - } - - public enum SLParameterKind { - None, - Var, - InOut, - } - - public enum BinaryOp { - None = -1, - Add, - Sub, - Mul, - Div, - Mod, - And, - Or, - Less, - Greater, - Equal, - NotEqual, - LessEqual, - GreaterEqual, - BitAnd, - BitOr, - BitXor, - LeftShift, - RightShift, - Dot, - AndAdd, - AndSub, - AndMul, - Assign, - } - - public enum UnaryOp { - Neg = 0, - Pos, - At, - Not, - BitNot, - } - - public enum Visibility { - None, - Public, - Private, - Internal, - Open, - FilePrivate, - } - - [Flags] - public enum FunctionKind { - None = 0, - Override = 1 << 0, - Final = 1 << 1, - Static = 1 << 2, - Throws = 1 << 3, - Constructor = 1 << 4, - Class = 1 << 5, - Rethrows = 1 << 6, - Required = 1 << 7, - Async = 1 << 8, - } - - public enum NamedType { - Class = 0, - Struct, - Extension, - Actor, - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs deleted file mode 100644 index fb0dde1b419f..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLExpr.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public interface ISLExpr : ICodeElement { - } - - public interface ISLExprList : ICodeElementSet { - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs deleted file mode 100644 index 700f123f833e..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLLineable.cs +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public interface ISLLineable { - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs deleted file mode 100644 index d6f4232d69ae..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/ISLStatement.cs +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public interface ISLStatement { - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs deleted file mode 100644 index 3ae091834905..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAddressOf.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLAddressOf : SLBaseExpr { - public SLAddressOf (SLBaseExpr expr, bool addParens) - { - Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); - AddParens = addParens; - } - - public SLBaseExpr Expr { get; private set; } - public bool AddParens { get; set; } - - #region implemented abstract members of DelegatedSimpleElem - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('&', false); - if (AddParens) - writer.Write ('(', false); - Expr.WriteAll (writer); - if (AddParens) - writer.Write (')', false); - } - #endregion - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs deleted file mode 100644 index 5912db882fce..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLArgument.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLArgument : DelegatedSimpleElement { - public SLArgument (SLIdentifier ident, SLBaseExpr expr, bool identifierIsRequired = false) - { - Identifier = identifierIsRequired ? Exceptions.ThrowOnNull (ident, nameof(ident)) : ident; - Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); - IdentifierIsRequired = identifierIsRequired; - } - - public SLArgument (string ident, SLBaseExpr expr, bool identifierIsRequired = false) - : this (!String.IsNullOrEmpty (ident) ? new SLIdentifier (ident) : null, expr, identifierIsRequired) - { - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (Identifier != null && IdentifierIsRequired) { - Identifier.WriteAll (writer); - writer.Write (": ", true); - } - Expr.WriteAll (writer); - } - - - - public SLIdentifier Identifier { get; private set; } - public SLBaseExpr Expr { get; private set; } - public bool IdentifierIsRequired { get; private set; } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs deleted file mode 100644 index de6b021abd52..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAsExpr.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLAsExpr : SLBaseExpr { - public SLAsExpr (SLType asType) - { - AsType = Exceptions.ThrowOnNull (asType, nameof (asType)); - } - - public SLType AsType { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("as ", true); - AsType.WriteAll (writer); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs deleted file mode 100644 index c405fc340d49..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLAttribute.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Reflection; -using System.Text; - -namespace SyntaxDynamo.SwiftLang { - public class SLAttribute : LineCodeElementCollection { - public SLAttribute (SLIdentifier name, CommaListElementCollection args, bool isSingleLine = false) - : base (isSingleLine, false, isSingleLine) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - Add (new SimpleElement ("@")); - var stringRep = new StringBuilder (Name.Name); - Add (Name); - if (args != null) { - Add (new SimpleElement ("(")); - Add (args); - Add (new SimpleElement (")")); - stringRep.Append ("("); - foreach (var arg in args) { - if (arg is SLIdentifier argId) { - stringRep.Append (argId.Name); - } - } - stringRep.Append (")"); - } - StringRep = stringRep.ToString (); - } - - public SLAttribute (string name, CommaListElementCollection args = null) - : this (new SLIdentifier (name), args) - { - } - - public SLAttribute (string name, bool isSingleLine, params SLBaseExpr [] args) - : this (new SLIdentifier (name), new CommaListElementCollection (args), isSingleLine) - { - } - - public SLIdentifier Name { get; private set; } - - public string StringRep { get; private set; } - - static SLAttribute objc; - - public static SLAttribute ObjC () - { - if (objc == null) { - objc = new SLAttribute ("objc"); - } - return objc; - } - - static SLAttribute convc; - - public static SLAttribute ConventionC () - { - if (convc == null) { - convc = new SLAttribute ("convention", new CommaListElementCollection () { new SLIdentifier ("c") }); - } - return convc; - } - - static SLAttribute escaping; - - public static SLAttribute Escaping () - { - if (escaping == null) { - escaping = new SLAttribute ("escaping"); - } - return escaping; - } - - void SLAttributeWriteAll (object sender, WriteEventArgs eventArgs) - { - this.WriteAll (eventArgs.Writer); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs deleted file mode 100644 index aac2bea949ce..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBaseExpr.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public abstract class SLBaseExpr : DelegatedSimpleElement, ISLExpr { - public static SLBaseExpr operator + (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Add, lhs, rhs); - } - - public static SLBaseExpr operator - (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Sub, lhs, rhs); - } - - public static SLBaseExpr operator * (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Mul, lhs, rhs); - } - - public static SLBaseExpr operator / (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Div, lhs, rhs); - } - - public static SLBaseExpr operator % (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Mod, lhs, rhs); - } - - public static SLBaseExpr operator < (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Less, lhs, rhs); - } - - public static SLBaseExpr operator > (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.Greater, lhs, rhs); - } - - public static SLBaseExpr operator <= (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.LessEqual, lhs, rhs); - } - - public static SLBaseExpr operator >= (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.GreaterEqual, lhs, rhs); - } - - public static SLBaseExpr operator & (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.BitAnd, lhs, rhs); - } - - public static SLBaseExpr operator | (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.BitOr, lhs, rhs); - } - - public static SLBaseExpr operator ^ (SLBaseExpr lhs, SLBaseExpr rhs) - { - return new SLBinaryExpr (BinaryOp.BitXor, lhs, rhs); - } - - public static SLBaseExpr operator << (SLBaseExpr lhs, int bits) - { - return new SLBinaryExpr (BinaryOp.LeftShift, lhs, SLConstant.Val (bits)); - } - - public static SLBaseExpr operator >> (SLBaseExpr lhs, int bits) - { - return new SLBinaryExpr (BinaryOp.RightShift, lhs, SLConstant.Val (bits)); - } - - public SLBaseExpr Dot (SLBaseExpr other) - { - return new SLBinaryExpr (BinaryOp.Dot, this, other); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs deleted file mode 100644 index 16bdbc6c695c..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinaryExpr.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLBinaryExpr : SLBaseExpr { - public SLBinaryExpr (BinaryOp op, ISLExpr lhs, ISLExpr rhs) - { - Operation = op; - CustomOperation = null; - Left = Exceptions.ThrowOnNull (lhs, nameof(lhs)); - Right = Exceptions.ThrowOnNull (rhs, nameof(rhs)); - } - - public SLBinaryExpr (string op, ISLExpr lhs, ISLExpr rhs) - { - CustomOperation = Exceptions.ThrowOnNull (op, nameof (op)); - Operation = BinaryOp.None; - Left = Exceptions.ThrowOnNull (lhs, nameof (lhs)); - Right = Exceptions.ThrowOnNull (rhs, nameof (rhs)); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Left.WriteAll (writer); - var operation = CustomOperation ?? OpToString (Operation); - operation = Operation == BinaryOp.Dot ? $"{operation}" : $" {operation} "; - writer.Write (operation, true); - Right.WriteAll (writer); - } - - public string CustomOperation { get; private set; } - public BinaryOp Operation { get; private set; } - public ISLExpr Left { get; private set; } - public ISLExpr Right { get; private set; } - - static string OpToString (BinaryOp op) - { - switch (op) { - case BinaryOp.Add: - return "+"; - case BinaryOp.AndAdd: - return "&+"; - case BinaryOp.Sub: - return "-"; - case BinaryOp.AndSub: - return "&-"; - case BinaryOp.Mul: - return "*"; - case BinaryOp.AndMul: - return "&*"; - case BinaryOp.Div: - return "/"; - case BinaryOp.Mod: - return "%"; - case BinaryOp.And: - return "&&"; - case BinaryOp.Or: - return "||"; - case BinaryOp.Less: - return "<"; - case BinaryOp.Greater: - return ">"; - case BinaryOp.Equal: - return "=="; - case BinaryOp.NotEqual: - return "!="; - case BinaryOp.LessEqual: - return "<="; - case BinaryOp.GreaterEqual: - return ">="; - case BinaryOp.BitAnd: - return "&"; - case BinaryOp.BitOr: - return "|"; - case BinaryOp.BitXor: - return "^"; - case BinaryOp.LeftShift: - return ">>"; - case BinaryOp.RightShift: - return "<<"; - case BinaryOp.Dot: - return "."; - case BinaryOp.Assign: - return "="; - default: - throw new ArgumentOutOfRangeException (nameof(op)); - } - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs deleted file mode 100644 index edcb7184bf65..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLBinding.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLBinding : SLBaseExpr, ISLLineable { - public SLBinding (SLIdentifier id, ISLExpr value, SLType typeAnnotation = null) - { - Name = Exceptions.ThrowOnNull (id, nameof(id)); - Value = value; - TypeAnnotation = typeAnnotation; - } - - public SLBinding (string id, ISLExpr value, SLType typeAnnotation = null) - : this (new SLIdentifier (id), value, typeAnnotation) - { - } - - public SLBinding (SLSubscriptExpr sub, ISLExpr value) - { - Name = null; - Subscript = Exceptions.ThrowOnNull (sub, nameof(sub)); - Value = value; - TypeAnnotation = null; - } - - public SLIdentifier Name { get; private set; } - public SLSubscriptExpr Subscript { get; private set; } - public SLType TypeAnnotation { get; private set; } - public ISLExpr Value { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - if (Name != null) - Name.WriteAll (writer); - else - Subscript.WriteAll (writer); - - if (TypeAnnotation != null) { - writer.Write (": ", true); - TypeAnnotation.WriteAll (writer); - } - - if (Value != null) { - writer.Write (" = ", true); - Value.WriteAll (writer); - } - writer.EndLine (); - } - - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs deleted file mode 100644 index d3a2bd82c826..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClass.cs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLClass : ICodeElementSet { - public SLClass (Visibility vis, SLIdentifier name, IEnumerable methods = null, - bool isStatic = false, bool isSealed = false, NamedType namedType = NamedType.Class, - bool isFinal = false) - { - // swift hates when you put public on an extension on a public type - Visibility = vis == Visibility.Public && namedType == NamedType.Extension ? Visibility.None : vis; - IsStatic = isStatic; - IsSealed = isSealed; - IsFinal = isFinal; - NamedType = namedType; - Name = Exceptions.ThrowOnNull (name, "name"); - Inheritance = new SLInheritance (); - Fields = new List (); - Constructors = new List (); - Methods = new List (); - Properties = new List (); - InnerClasses = new SLClasses (); - Subscripts = new List (); - Generics = new SLGenericTypeDeclarationCollection (); - - if (methods != null) - Methods.AddRange (methods); - } - - public SLClass (Visibility vis, string name, - IEnumerable members = null, bool isStatic = false, bool isSealed = false, NamedType namedType = NamedType.Class, - bool isFinal = false) - : this (vis, new SLIdentifier (name), members, isStatic, isSealed, namedType, isFinal) - { - } - - public Visibility Visibility { get; private set; } - public bool IsStatic { get; private set; } - public bool IsSealed { get; private set; } - public bool IsFinal { get; private set; } - public NamedType NamedType { get; private set; } - public SLIdentifier Name { get; private set; } - public SLInheritance Inheritance { get; private set; } - public List Fields { get; private set; } - public List Constructors { get; private set; } - public List Methods { get; private set; } - public List Properties { get; private set; } - public SLClasses InnerClasses { get; private set; } - public List Subscripts { get; private set; } - public SLGenericTypeDeclarationCollection Generics { get; private set; } - - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - static SLIdentifier IdentifierForNamedType (NamedType nt) - { - switch (nt) { - case NamedType.Class: return new SLIdentifier ("class"); - case NamedType.Struct: return new SLIdentifier ("struct"); - case NamedType.Extension: return new SLIdentifier ("extension"); - case NamedType.Actor: return new SLIdentifier ("actor"); - default: - throw new ArgumentOutOfRangeException ($"Unknown named type {nt}", nameof (nt)); - } - } - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - var decl = new LineCodeElementCollection (true, false, true); - if (Visibility != Visibility.None) - decl.Add (new SimpleElement (SLFunc.ToVisibilityString (Visibility) + " ")); - if (IsStatic) - decl.Add (new SimpleElement ("static ", true)); - if (IsSealed) - decl.Add (new SimpleElement ("sealed ", true)); - if (IsFinal) - decl.Add (new SimpleElement ("final ", true)); - decl.Add (IdentifierForNamedType (NamedType)); - decl.Add (SimpleElement.Spacer); - decl.Add (Name); - if (Generics.Count > 0) { - decl.Add (Generics); - } - if (Inheritance.Count > 0) { - decl.Add (new SimpleElement (" : ", true)); - decl.Add (Inheritance); - } - yield return decl; - - foreach (var constraint in Generics.ConstraintElements) { - yield return constraint; - } - - var contents = new DecoratedCodeElementCollection ("{", "}", - true, true, true); - - contents.AddRange (Fields); - contents.AddRange (Constructors); - contents.AddRange (Methods); - contents.AddRange (Properties); - contents.AddRange (Subscripts); - contents.Add (InnerClasses); - - yield return contents; - } - } - - #endregion - } - - public class SLClasses : CodeElementCollection { - public SLClasses (IEnumerable classes = null) - : base () - { - if (classes != null) - AddRange (classes); - } - - public SLClasses And (SLClass use) - { - Add (use); - return this; - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs deleted file mode 100644 index 3f7673f32f57..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosure.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLClosure : SLBaseExpr { - public SLClosure (SLType type, SLTupleType parms, CodeElementCollection body, bool throws) - { - OuterBlock = new SLCodeBlock (null); - Parameters = parms; - if (parms != null) { - OuterBlock.Add (parms); - OuterBlock.Add (SimpleElement.Spacer); - if (throws) { - OuterBlock.Add (new SimpleElement ("throws ")); - } - if (type != null) { - Type = type; - OuterBlock.Add (new SimpleElement ("-> ")); - OuterBlock.Add (Type); - OuterBlock.Add (SimpleElement.Spacer); - } - OuterBlock.Add (new SimpleElement ("in ")); - OuterBlock.Add (body); - } - } - - public SLTupleType Parameters { get; private set; } - public SLCodeBlock OuterBlock { get; private set; } - public CodeElementCollection Body { get; private set; } - public SLType Type { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - OuterBlock.WriteAll (writer); - } - } - -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs deleted file mode 100644 index cf170627aeb8..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLClosureCall.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLClosureCall : SLBaseExpr, ISLLineable { - - public SLClosureCall (SLClosure closure, DelegatedCommaListElemCollection paramList) - { - Closure = Exceptions.ThrowOnNull (closure, "closure"); - Parameters = paramList ?? new DelegatedCommaListElemCollection (SLFunctionCall.WriteElement); - } - - public SLClosure Closure { get; private set; } - public DelegatedCommaListElemCollection Parameters { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Closure.WriteAll (writer); - writer.Write ("(", false); - Parameters.WriteAll (writer); - writer.Write (")", false); - } - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs deleted file mode 100644 index 08ebf0361efd..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCodeBlock.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLCodeBlock : DecoratedCodeElementCollection, ISLStatement { - public SLCodeBlock (IEnumerable statements) - : this ("{", "}", statements) - { - } - - public SLCodeBlock (string start, string end, IEnumerable statements) - : base (Exceptions.ThrowOnNull (start, nameof(start)), - Exceptions.ThrowOnNull (end, nameof(end)), - true, true, true) - { - if (statements != null) { - foreach (ICodeElement elem in statements) { - And (elem); - } - } - } - - public SLCodeBlock And (ICodeElement elem) - { - if (!((elem is ISLStatement) || (elem is ISLLineable))) - throw new ArgumentException ("contents must each be an ISLStatement or ISLLineable"); - Add (elem); - return this; - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs deleted file mode 100644 index 15f59adf1e6b..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLCommaListExpr.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLCommaListExpr : SLBaseExpr { - public SLCommaListExpr (params SLBaseExpr [] exprs) - { - Exprs = new List (); - if (exprs != null) - Exprs.AddRange (exprs); - } - - public List Exprs { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - bool isFirst = true; - foreach (SLBaseExpr expr in Exprs) { - if (!isFirst) - writer.Write (", ", true); - isFirst = false; - expr.WriteAll (writer); - } - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs deleted file mode 100644 index 1c0342c30c16..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLComment.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SyntaxDynamo.SwiftLang { - public class SLComment : DelegatedSimpleElement { - public SLComment (string contents, bool onOwnLine) - { - Contents = contents; - OnOwnLine = onOwnLine; - } - - public bool OnOwnLine { get; set; } - public string Contents { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (OnOwnLine) { - writer.BeginNewLine (true); - } else { - SimpleElement.Spacer.Write (writer, o); - } - writer.Write ("// ", false); - writer.Write (Contents, false); - writer.EndLine (); - } - - public void AttachBefore (ICodeElement item) - { - item.Begin += (s, writeEventArgs) => { - this.WriteAll (writeEventArgs.Writer); - }; - } - - public void AttachAfter (ICodeElement item) - { - item.End += (s, writeEventArgs) => { - this.WriteAll (writeEventArgs.Writer); - }; - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs deleted file mode 100644 index fe2045f0b50a..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConditionalCompilation.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLConditionalCompilation : LineCodeElementCollection { - SLConditionalCompilation (SLIdentifier tag, SLIdentifier condition) - : base (true, false, false) - { - Add (tag); - if (condition != null) { - Add (SimpleElement.Spacer); - Add (condition); - } - } - - public SLConditionalCompilation AttachBefore (ICodeElement thing) - { - Exceptions.ThrowOnNull (thing, nameof (thing)); - thing.Begin += (s, eventArgs) => { - this.WriteAll (eventArgs.Writer); - }; - return this; - } - - public SLConditionalCompilation AttachAfter (ICodeElement thing) - { - Exceptions.ThrowOnNull (thing, nameof (thing)); - thing.End += (s, eventArgs) => { - this.WriteAll (eventArgs.Writer); - }; - return this; - } - - - - static SLConditionalCompilation _else = new SLConditionalCompilation (new SLIdentifier ("#else"), null); - public static SLConditionalCompilation Else { get { return _else; } } - static SLConditionalCompilation _endif = new SLConditionalCompilation (new SLIdentifier ("#endif"), null); - public static SLConditionalCompilation Endif { get { return _endif; } } - - public static SLConditionalCompilation If (SLIdentifier condition) - { - return new SLConditionalCompilation (new SLIdentifier ("#if"), Exceptions.ThrowOnNull (condition, nameof (condition))); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs deleted file mode 100644 index 6bf543ae99ff..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLConstant.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; -using System.CodeDom.Compiler; -using System.CodeDom; - -namespace SyntaxDynamo.SwiftLang { - public class SLConstant : SLBaseExpr { - public SLConstant (string val) - { - Value = Exceptions.ThrowOnNull (val, nameof(val)); - } - - public string Value { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Value, false); - } - - public static SLConstant Val (byte b) { return new SLConstant (b.ToString ()); } - public static SLConstant Val (sbyte sb) { return new SLConstant (sb.ToString ()); } - public static SLConstant Val (ushort us) { return new SLConstant (us.ToString ()); } - public static SLConstant Val (short s) { return new SLConstant (s.ToString ()); } - public static SLConstant Val (uint ui) { return new SLConstant (ui.ToString ()); } - public static SLConstant Val (int i) { return new SLConstant (i.ToString ()); } - public static SLConstant Val (ulong ul) { return new SLConstant (ul.ToString ()); } - public static SLConstant Val (long l) { return new SLConstant (l.ToString ()); } - public static SLConstant Val (float f) - { - return new SLConstant (f.ToString ()); // AFAIK, there is no explicit way to distinguish between a float or double - // constant in swift - } - public static SLConstant Val (double d) { return new SLConstant (d.ToString ()); } - public static SLConstant Val (bool b) { return new SLConstant (b ? "true" : "false"); } - public static SLConstant Val (char c) { return new SLConstant (ToCharLiteral (c)); } - public static SLConstant Val (string s) { return new SLConstant (ToStringLiteral (s)); } - - static SLConstant any = new SLConstant ("_"); - public static SLConstant Any { get { return any; } } - - static SLConstant kNil = new SLConstant ("nil"); - public static SLConstant Nil { get { return kNil; } } - - static string ToCharLiteral (char c) // uses C# semantics. Eh. - { - using (var writer = new StringWriter ()) { - using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { - provider.GenerateCodeFromExpression (new CodePrimitiveExpression (c), writer, null); - return writer.ToString (); - } - } - } - - static string ToStringLiteral (string s) - { - using (var writer = new StringWriter ()) { - using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { - provider.GenerateCodeFromExpression (new CodePrimitiveExpression (s), writer, null); - return writer.ToString (); - } - } - } - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs deleted file mode 100644 index 832581fd4902..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDeclaration.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLDeclaration : LineCodeElementCollection, ISLExpr, ISLLineable { - public SLDeclaration (bool isLet, SLBinding binding, Visibility vis = Visibility.Private, bool isStatic = false) - : base (null, false, true) - { - IsLet = isLet; - IsStatic = isStatic; - And (new SimpleElement (SLFunc.ToVisibilityString (vis))).And (SimpleElement.Spacer); - if (IsStatic) - Add (new SimpleElement ("static ", true)); - And (new SimpleElement (isLet ? "let" : "var")).And (SimpleElement.Spacer); - Binding = binding; - Add (Binding); - } - - public SLDeclaration (bool isLet, string name, SLType typeAnnotation = null, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - : this (isLet, new SLIdentifier (Exceptions.ThrowOnNull (name, nameof(name))), typeAnnotation, value, vis, isStatic) - { - } - - public SLDeclaration (bool isLet, SLIdentifier name, SLType typeAnnotation = null, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - : this (isLet, new SLBinding (name, value, typeAnnotation), vis, isStatic) - { - } - - public bool IsLet { get; private set; } - public Visibility Visibilty { get; private set; } - public SLBinding Binding { get; private set; } - public bool IsStatic { get; private set; } - - - public static SLLine LetLine (SLIdentifier name, SLType typeAnnotation, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - { - return new SLLine (new SLDeclaration (true, name, typeAnnotation, value, vis, isStatic)); - } - - public static SLLine LetLine (string name, SLType typeAnnotation, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - { - return new SLLine (new SLDeclaration (true, name, typeAnnotation, value, vis, isStatic)); - } - - public static SLLine VarLine (SLIdentifier name, SLType typeAnnotation, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - { - return new SLLine (new SLDeclaration (false, name, typeAnnotation, value, vis, isStatic)); - } - - public static SLLine VarLine (string name, SLType typeAnnotation, ISLExpr value = null, - Visibility vis = Visibility.Private, bool isStatic = false) - { - return new SLLine (new SLDeclaration (false, name, typeAnnotation, value, vis, isStatic)); - } - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs deleted file mode 100644 index ca67c0572766..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLDoCatch.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLCatch : DelegatedSimpleElement, ISLStatement { - public SLCatch (ICodeElement catchExpr, SLCodeBlock body) - { - CatchExpr = catchExpr; - Body = body ?? new SLCodeBlock (null); - } - - public SLCatch () - : this ((ICodeElement)null, null) - { - } - - public SLCatch (string name, SLType typeMatch) - : this (SLLetMatch.LetAs (name, typeMatch), null) - { - } - - public ICodeElement CatchExpr { get; private set; } - public SLCodeBlock Body { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write ("catch ", false); - if (CatchExpr != null) { - CatchExpr.WriteAll (writer); - } - writer.EndLine (); - Body.WriteAll (writer); - writer.EndLine (); - } - } - - public class SLDo : CodeElementCollection, ISLStatement { - public SLDo (SLCodeBlock doBlock, params SLCatch [] catchBlocks) - { - DoBlock = doBlock ?? new SLCodeBlock (null); - CatchBlocks = new CodeElementCollection (); - CatchBlocks.AddRange (catchBlocks); - - Add (new SimpleElement ("do ", true)); - Add (DoBlock); - Add (CatchBlocks); - } - - public SLDo (SLCodeBlock doBlock, string name, SLType catchType) - : this (doBlock, new SLCatch (name, catchType)) - { - } - - public SLCodeBlock DoBlock { get; private set; } - public CodeElementCollection CatchBlocks { get; private set; } - - public override void Write (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - base.Write (writer, o); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs deleted file mode 100644 index 3975ddd09fa0..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFile.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLFile : ICodeElementSet { - public SLFile (SLImportModules import) - { - Imports = import ?? new SLImportModules (); - Declarations = new List (); - Classes = new SLClasses (); - Functions = new List (); - Trailer = new List (); - } - - public SLImportModules Imports { get; private set; } - public List Declarations { get; private set; } - public SLClasses Classes { get; private set; } - public List Functions { get; private set; } - public List Trailer { get; private set; } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - protected virtual void OnEnd (WriteEventArgs args) - { - End (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - yield return Imports; - foreach (var decl in Declarations) - yield return decl; - yield return Classes; - foreach (var func in Functions) - yield return func; - foreach (var trailerElem in Trailer) - yield return trailerElem; - } - } - - #endregion - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs deleted file mode 100644 index 0c48271a0cc9..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunc.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLFunc : ICodeElementSet { - public SLFunc (Visibility vis, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body) - : this (vis, type, name, parms, body, false) - { - } - - public SLFunc (Visibility vis, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body, bool throws) - : this (vis, (throws ? FunctionKind.Throws : FunctionKind.None), type, name, parms, body) - { - } - - public SLFunc (Visibility vis, FunctionKind funcKind, SLType type, SLIdentifier name, SLParameterList parms, SLCodeBlock body, bool isOptional = false) - { - GenericParams = new SLGenericTypeDeclarationCollection (); - Visibility = vis; - ReturnType = type; - bool isConstructor = (funcKind & FunctionKind.Constructor) != 0; - Name = isConstructor ? new SLIdentifier (isOptional ? "init?" : "init") : Exceptions.ThrowOnNull (name, nameof (name)); - Parameters = parms ?? new SLParameterList (); - Body = Exceptions.ThrowOnNull (body, nameof (body)); - FuncKind = funcKind; - IsConstructor = isConstructor; - IsOptional = isOptional; - } - - public bool IsConstructor { get; private set; } - public FunctionKind FuncKind { get; private set; } - public Visibility Visibility { get; private set; } - public SLType ReturnType { get; private set; } - public SLIdentifier Name { get; private set; } - public SLParameterList Parameters { get; private set; } - public SLCodeBlock Body { get; private set; } - public SLGenericTypeDeclarationCollection GenericParams { get; private set; } - public bool IsOptional { get; private set; } - - - public static string ToVisibilityString (Visibility vis) - { - switch (vis) { - case Visibility.Private: - return "private"; - case Visibility.Public: - return "public"; - case Visibility.None: - return ""; - case Visibility.Internal: - return "internal"; - case Visibility.Open: - return "open"; - case Visibility.FilePrivate: - return "fileprivate"; - default: - throw new ArgumentOutOfRangeException (nameof (vis)); - } - } - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - public IEnumerable Elements { - get { - if (Visibility != Visibility.None) { - yield return new SimpleElement (ToVisibilityString (Visibility), false); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Final) != 0) { - yield return new SimpleElement ("final"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Override) != 0) { - yield return new SimpleElement ("override"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Required) != 0) { - yield return new SimpleElement ("required"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Static) != 0) { - yield return new SimpleElement ("static"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Class) != 0) { - yield return new SimpleElement ("class"); - yield return SimpleElement.Spacer; - } - - if (!IsConstructor) { - yield return new SimpleElement ("func"); - yield return SimpleElement.Spacer; - } - - - yield return Name; - yield return GenericParams; - yield return Parameters; - - if ((FuncKind & FunctionKind.Async) != 0) { - yield return SimpleElement.Spacer; - yield return new SimpleElement ("async"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Throws) != 0) { - yield return SimpleElement.Spacer; - yield return new SimpleElement ("throws"); - yield return SimpleElement.Spacer; - } - if ((FuncKind & FunctionKind.Rethrows) != 0) { - yield return SimpleElement.Spacer; - yield return new SimpleElement ("rethrows"); - yield return SimpleElement.Spacer; - } - if (!IsConstructor && ReturnType != null) { - yield return SimpleElement.Spacer; - yield return new SimpleElement ("->"); - yield return SimpleElement.Spacer; - yield return ReturnType; - } - foreach (ICodeElement constr in GenericParams.ConstraintElements) { - yield return constr; - } - - yield return Body; - } - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs deleted file mode 100644 index b225a8dd8cc8..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLFunctionCall.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLFunctionCall : SLBaseExpr, ISLLineable { - public SLFunctionCall (SLIdentifier ident, DelegatedCommaListElemCollection paramList) - { - Name = ident; - Parameters = paramList ?? new DelegatedCommaListElemCollection (WriteElement); - } - - public SLFunctionCall (string identifier, bool isConstructor, params SLArgument [] parameters) - : this (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), - isConstructor ? new DelegatedCommaListElemCollection (WriteAllElements, parameters) : - new DelegatedCommaListElemCollection (WriteElement, parameters)) - { - } - - public SLFunctionCall (string identifier, bool isConstructor, bool writeAllParameterParts, params SLArgument [] parameters) - : this (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), - writeAllParameterParts ? new DelegatedCommaListElemCollection (WriteAllElements, parameters) : - new DelegatedCommaListElemCollection (WriteElement, parameters)) - { - } - - - protected override void LLWrite (ICodeWriter writer, object o) - { - Name.WriteAll (writer); - writer.Write ("(", false); - Parameters.WriteAll (writer); - writer.Write (")", false); - } - - public SLIdentifier Name { get; private set; } - public DelegatedCommaListElemCollection Parameters { get; private set; } - public bool IncludeFirstParameterLabel { get; set; } - - public static void WriteElement (ICodeWriter writer, int i, SLArgument arg) - { - if (i == 0 && !arg.IdentifierIsRequired) { - arg.Expr.WriteAll (writer); - } else { - arg.WriteAll (writer); - } - } - - public static void WriteAllElements (ICodeWriter writer, int i, SLArgument arg) - { - arg.WriteAll (writer); - } - - - public static SLLine FunctionCallLine (SLIdentifier identifier, params SLArgument [] parameters) - { - return new SLLine (new SLFunctionCall (identifier, - new DelegatedCommaListElemCollection (WriteElement, parameters))); - } - - public static SLLine FunctionCallLine (string identifier, params SLArgument [] parameters) - { - return new SLLine (new SLFunctionCall (new SLIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), - new DelegatedCommaListElemCollection (WriteElement, parameters))); - } - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs deleted file mode 100644 index dd427f69b2af..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericConstraint.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLGenericConstraint : DelegatedSimpleElement { - public SLGenericConstraint (bool isInheritance, SLType firstType, SLType secondType) - { - IsInheritance = isInheritance; - FirstType = Exceptions.ThrowOnNull (firstType, nameof (firstType)); - SecondType = Exceptions.ThrowOnNull (secondType, nameof (secondType)); - } - - public bool IsInheritance { get; private set; } - public SLType FirstType { get; private set; } - public SLType SecondType { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - FirstType.Write (writer, o); - writer.Write (String.Format (" {0} ", IsInheritance ? ":" : "=="), true); - SecondType.Write (writer, o); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs deleted file mode 100644 index fb2145ff2d16..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLGenericTypeDeclaration.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang -{ - public class SLGenericTypeDeclaration - { - public SLGenericTypeDeclaration(SLIdentifier name) - { - Name = Exceptions.ThrowOnNull(name, nameof(name)); - Constraints = new List(); - } - - public SLIdentifier Name { get; private set; } - public List Constraints { get; private set; } - } - - public class SLGenericTypeDeclarationCollection : List, ICodeElementSet - { - public SLGenericTypeDeclarationCollection() - : base() - { - } - - public IEnumerable ConstraintElements - { - get - { - List constrained = this.Where(decl => decl.Constraints.Count > 0).ToList(); - if (constrained.Count == 0) - yield break; - yield return new SimpleElement(" where ", true); - bool first = true; - foreach (SLGenericTypeDeclaration decl in constrained) - { - foreach (SLGenericConstraint constraint in decl.Constraints) - { - if (!first) - { - yield return new SimpleElement(",", true); - yield return SimpleElement.Spacer; - } - else - { - first = false; - } - yield return constraint; - } - } - } - } - - public IEnumerable Elements - { - get - { - if (this.Count > 0) - { - yield return new SimpleElement("<"); - bool first = true; - foreach (SLGenericTypeDeclaration decl in this) - { - if (!first) - { - yield return new SimpleElement(",", true); - yield return SimpleElement.Spacer; - } - else { - first = false; - } - yield return decl.Name; - } - yield return new SimpleElement(">"); - } - } - } - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite(ICodeWriter writer) - { - OnBeginWrite(new WriteEventArgs(writer)); - return null; - } - - protected virtual void OnBeginWrite(WriteEventArgs args) - { - Begin(this, args); - } - - public virtual void Write(ICodeWriter writer, object o) - { - } - - public virtual void EndWrite(ICodeWriter writer, object o) - { - OnEndWrite(new WriteEventArgs(writer)); - } - - protected virtual void OnEndWrite(WriteEventArgs args) - { - End.FireInReverse(this, args); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs deleted file mode 100644 index fe0455f0dc5f..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIdentifier.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLIdentifier : SLBaseExpr { - public SLIdentifier (string name) - { - Name = Exceptions.ThrowOnNull (name, nameof(name)); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Name, false); - } - - public string Name { get; private set; } - - public override string ToString () - { - return Name; - } - - static SLIdentifier anonymousIdentifier = new SLIdentifier ("_"); - public static SLIdentifier Anonymous { get { return anonymousIdentifier; } } - static SLIdentifier superIdentifier = new SLIdentifier ("super"); - public static SLIdentifier Super { get { return superIdentifier; } } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs deleted file mode 100644 index 52dc88e706d6..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLIfElse.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLIfElse : CodeElementCollection, ISLStatement { - class IfElem : DelegatedSimpleElement, ISLStatement { - public IfElem (SLBaseExpr condition, bool isCase) - : base () - { - Condition = condition; - IsCase = isCase; - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write ("if ", false); - if (IsCase) - writer.Write ("case ", true); - Condition.WriteAll (writer); - writer.EndLine (); - } - - public bool IsCase { get; private set; } - public SLBaseExpr Condition { get; private set; } - } - - public SLIfElse (SLBaseExpr condition, SLCodeBlock ifClause, SLCodeBlock elseClause = null, bool isCase = false) - : base () - { - Condition = new IfElem (Exceptions.ThrowOnNull (condition, nameof(condition)), isCase); - IfClause = Exceptions.ThrowOnNull (ifClause, nameof(ifClause)); - ElseClause = elseClause; - - Add (Condition); - Add (IfClause); - if (ElseClause != null && ElseClause.Count > 0) { - Add (new SimpleLineElement ("else", false, true, false)); - Add (ElseClause); - } - } - - public SLIfElse (SLBaseExpr expr, IEnumerable ifClause, IEnumerable elseClause, bool isCase) - : this (expr, new SLCodeBlock (ifClause), - elseClause != null ? new SLCodeBlock (elseClause) : null, isCase) - - { - - } - - public DelegatedSimpleElement Condition { get; private set; } - public SLCodeBlock IfClause { get; private set; } - public SLCodeBlock ElseClause { get; private set; } - - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs deleted file mode 100644 index 9ecf7337e8e8..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLImport.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLImport : SimpleLineElement { - public SLImport (string module, ImportKind kind = ImportKind.None) - : base (string.Format ("import {0}{1}", ToImportKindString (kind), - Exceptions.ThrowOnNull (module, nameof(module))), - false, false, false) - { - Module = module; - } - - public string Module { get; private set; } - - static string ToImportKindString (ImportKind kind) - { - switch (kind) { - case ImportKind.None: - return ""; - case ImportKind.Class: - return "class "; - case ImportKind.Enum: - return "enum "; - case ImportKind.Func: - return "func "; - case ImportKind.Protocol: - return "protocol "; - case ImportKind.Struct: - return "struct "; - case ImportKind.TypeAlias: - return "typealias "; - case ImportKind.Var: - return "var "; - default: - throw new ArgumentOutOfRangeException (nameof(kind)); - } - } - } - - public class SLImportModules : CodeElementCollection { - public SLImportModules () : base () { } - public SLImportModules (params SLImport [] imp) - : this () - { - AddRange (imp); - } - public SLImportModules (params string [] imp) - : this () - { - AddRange (imp.Select (s => new SLImport (s))); - } - - public SLImportModules And (SLImport use) - { - if (OwningModule != null && use.Module == OwningModule) - return this; - if (use.Module == "Self") - return this; - Add (use); - return this; - } - - public SLImportModules And (string package) { return And (new SLImport (package)); } - - public void AddIfNotPresent (string package) - { - SLImport target = new SLImport (package); - if (package == "Self") - return; - - if (package != OwningModule && !this.Exists (imp => imp.Contents == target.Contents)) - Add (target); - } - - public string OwningModule { get; set; } - } - -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs deleted file mode 100644 index 3d9c423a43fc..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInheritance.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLInheritance : CommaListElementCollection { - public SLInheritance (IEnumerable identifiers) - { - if (identifiers != null) - AddRange (identifiers); - } - - public SLInheritance (params string [] identifiers) - : this (identifiers.Select (str => new SLIdentifier (str))) - { - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs deleted file mode 100644 index 21b321d2944c..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLInject.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLInject : SLIdentifier { - // SLInject is a way to more formalize the notion of code that is just plain easier to - // inject as raw text. It's not strictly necessary, but when you see a CSInject, it will make - // it clear that you're doing something not quite on the up and up. - public SLInject (string name) - : base (name) - { - } - - public static explicit operator SLInject (string name) - { - return new SLInject (name); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs deleted file mode 100644 index 4b732c3d6b6b..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLetMatch.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLLetMatch : SLBaseExpr, ISLLineable { - public SLLetMatch (SLIdentifier name, ISLExpr expr) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - Expr = expr; - } - - public SLIdentifier Name { get; private set; } - public ISLExpr Expr { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("let ", true); - Name.WriteAll (writer); - if (Expr != null) { - SimpleElement.Spacer.WriteAll (writer); - Expr.WriteAll (writer); - } - } - - public static SLLetMatch LetAs (string name, SLType asType) - { - return new SLLetMatch (new SLIdentifier (name), asType != null ? new SLAsExpr (asType) : null); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs deleted file mode 100644 index 9e9aaf63b33c..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLine.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLLine : DelegatedSimpleElement, ISLStatement { - public SLLine (ISLExpr contents, bool addSemicolon = true) - { - Contents = Exceptions.ThrowOnNull (contents, nameof(contents)); - if (!(contents is ISLLineable) && addSemicolon) - throw new ArgumentException ("contents must be ISLineable and require a semicolon", nameof (contents)); - AddSemicolon = addSemicolon; - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - Contents.WriteAll (writer); - if (AddSemicolon) - writer.Write (';', false); - writer.EndLine (); - } - - public ISLExpr Contents { get; private set; } - public bool AddSemicolon { get; private set; } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs deleted file mode 100644 index 77dc690b045f..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLLineableOperator.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SyntaxDynamo.SwiftLang { - public class SLLineableOperator : SLBaseExpr, ISLLineable { - public SLLineableOperator (SLUnaryExpr unaryExpr) - { - OperatorExpr = Exceptions.ThrowOnNull (unaryExpr, nameof (unaryExpr)); - } - - public SLLineableOperator (SLBinaryExpr binaryExpr) - { - OperatorExpr = Exceptions.ThrowOnNull (binaryExpr, nameof (binaryExpr)); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - OperatorExpr.WriteAll (writer); - } - - public SLBaseExpr OperatorExpr { get; private set; } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs deleted file mode 100644 index 6ad4f802d160..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNameTypePair.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLNameTypePair : DelegatedSimpleElement { - public SLNameTypePair (SLParameterKind kind, SLIdentifier id, SLType type) - : base () - { - ParameterKind = kind; - Name = id; - TypeAnnotation = type; - } - - public SLNameTypePair (SLIdentifier id, SLType type) - : this (SLParameterKind.None, id, type) - { - } - - public SLNameTypePair(SLParameterKind kind, string id, SLType type) - : this (kind, id != null ? new SLIdentifier(id) : null, type) - { - } - - public SLNameTypePair(string id, SLType type) - : this (SLParameterKind.None, id, type) - { - } - - public SLIdentifier Name { get; private set; } - public SLType TypeAnnotation { get; private set; } - public SLParameterKind ParameterKind { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (Name != null) { - Name.WriteAll (writer); - } - if (TypeAnnotation != null) { - if (Name != null) - writer.Write (": ", true); - if (ParameterKind != SLParameterKind.None) { - writer.Write (ToParameterKindString (ParameterKind), false); - writer.Write (' ', false); - } - TypeAnnotation.WriteAll (writer); - } - } - - internal static string ToParameterKindString (SLParameterKind kind) - { - switch (kind) { - case SLParameterKind.None: - return ""; - case SLParameterKind.Var: - return "var"; - case SLParameterKind.InOut: - return "inout"; - default: - throw new ArgumentOutOfRangeException (nameof(kind), "unexpected value " + kind.ToString ()); - } - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs deleted file mode 100644 index afb678456892..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLNamedClosureCall.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLNamedClosureCall : SLBaseExpr, ISLLineable { - - public SLNamedClosureCall (SLBaseExpr closureExpr, CommaListElementCollection paramList) - { - Closure = Exceptions.ThrowOnNull (closureExpr, "closure"); - Parameters = paramList ?? new CommaListElementCollection (); - } - - public SLBaseExpr Closure { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Closure.WriteAll (writer); - writer.Write ("(", false); - Parameters.WriteAll (writer); - writer.Write (")", false); - } - - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs deleted file mode 100644 index 4e4ad7f5fabb..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameter.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SyntaxDynamo.SwiftLang { - - public class SLUnnamedParameter : DelegatedSimpleElement { - public SLUnnamedParameter (SLType type, SLParameterKind kind = SLParameterKind.None) - { - ParameterKind = kind; - TypeAnnotation = Exceptions.ThrowOnNull (type, nameof (type)); - } - public SLParameterKind ParameterKind { get; private set; } - public SLType TypeAnnotation { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (ParameterKind != SLParameterKind.None) { - writer.Write (SLNameTypePair.ToParameterKindString (ParameterKind), false); - writer.Write (' ', false); - } - TypeAnnotation.WriteAll (writer); - } - } - - - public class SLParameter : SLUnnamedParameter { - public SLParameter (SLIdentifier publicName, SLIdentifier privateName, SLType type, SLParameterKind kind = SLParameterKind.None) - : base (type, kind) - { - PublicName = publicName; - PrivateName = Exceptions.ThrowOnNull (privateName, nameof (privateName)); - } - - public SLParameter (string publicName, string privateName, SLType type, SLParameterKind kind = SLParameterKind.None) - : this (publicName != null ? new SLIdentifier (publicName) : null, new SLIdentifier (privateName), type, kind) - { - } - - public SLParameter (SLIdentifier name, SLType type, SLParameterKind kind = SLParameterKind.None) - : this (name, name, type, kind) - { - - } - - public SLParameter (string name, SLType type, SLParameterKind kind = SLParameterKind.None) - : this (name, name, type, kind) - { - - } - - public SLIdentifier PublicName { get; private set; } - public SLIdentifier PrivateName { get; private set; } - public bool PublicNameIsOptional { get { return PublicName == null || String.IsNullOrEmpty (PublicName.Name); } } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (PublicNameIsOptional) { - writer.Write ("_ ", true); - PrivateName.WriteAll (writer); - } else if (PublicName.Name == PrivateName.Name) { - PrivateName.WriteAll (writer); - } else { - PublicName.WriteAll (writer); - writer.Write (" ", true); - PrivateName.WriteAll (writer); - } - writer.Write (": ", true); - base.LLWrite (writer, o); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs deleted file mode 100644 index d0d0494892e9..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParameterList.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLParameterList : DelegatedSimpleElement { - public SLParameterList () - { - Parameters = new List (); - } - - public SLParameterList (IEnumerable parameters) - : this () - { - Parameters.AddRange (parameters); - } - - public SLParameterList (params SLParameter[] parameters) - : this () - { - Parameters.AddRange (parameters); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('(', true); - for (int i = 0; i < Parameters.Count; i++) { - if (i > 0) { - writer.Write (", ", true); - } - Parameters [i].WriteAll (writer); - } - writer.Write (')', true); - } - - public List Parameters { get; private set; } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs deleted file mode 100644 index 58ca3fdd70d0..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLParenthesisExpression.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SyntaxDynamo.SwiftLang { - public class SLParenthesisExpression : SLBaseExpr { - public SLParenthesisExpression (SLBaseExpr within) - { - Within = Exceptions.ThrowOnNull (within, "within"); - } - - public SLBaseExpr Within { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('(', true); - Within.WriteAll (writer); - writer.Write (')', true); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs deleted file mode 100644 index 70735f8f2d0f..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLPostBang.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - public class SLPostBang : SLBaseExpr, ISLLineable { - public SLPostBang (SLBaseExpr expr, bool addParens) - { - Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); - AddParens = addParens; - } - - public SLBaseExpr Expr { get; private set; } - public bool AddParens { get; set; } - - #region implemented abstract members of DelegatedSimpleElem - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (AddParens) - writer.Write ('(', false); - Expr.WriteAll (writer); - if (AddParens) - writer.Write (')', false); - writer.Write ('!', false); - } - - #endregion - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs deleted file mode 100644 index 8be3e538c387..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLProperty.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLProperty : CodeElementCollection { - public SLProperty (Visibility vis, FunctionKind funcKind, SLType type, SLIdentifier name, - SLCodeBlock getter, SLCodeBlock setter, bool isAsync = false) - { - Visibility = vis; - Type = Exceptions.ThrowOnNull (type, nameof(type)); - Name = Exceptions.ThrowOnNull (name, nameof(name)); - GetterBody = Exceptions.ThrowOnNull (getter, nameof(getter)); - SetterBody = setter; - IsAsync = isAsync; - - List elems = new List (); - if (vis != Visibility.None) - elems.Add (SLFunc.ToVisibilityString (vis) + " "); - if ((funcKind & FunctionKind.Final) != 0) - elems.Add ("final "); - if ((funcKind & FunctionKind.Required) != 0) - elems.Add ("required "); - if ((funcKind & FunctionKind.Override) != 0) - elems.Add ("override "); - if ((funcKind & FunctionKind.Static) != 0) - elems.Add ("static "); - if ((funcKind & FunctionKind.Class) != 0) - elems.Add ("class "); - - elems.Add ("var "); - AddRange (elems.Select ((el, i) => i == 0 ? (ICodeElement)new SimpleLineElement (el, false, true, true) : new SimpleElement (el))); - Add (Name); - Add (new SimpleElement (":")); - Add (SimpleElement.Spacer); - Add (Type); - SLCodeBlock block = new SLCodeBlock (null); - block.Add (new SimpleElement ("get")); - block.Add (SimpleElement.Spacer); - if (isAsync) { - block.Add (new SimpleElement ("async")); - block.Add (SimpleElement.Spacer); - } - block.Add (GetterBody); - if (SetterBody != null) { - block.Add (new SimpleElement ("set")); - block.Add (SimpleElement.Spacer); - block.Add (SetterBody); - } - Add (block); - } - public Visibility Visibility { get; private set; } - public SLType Type { get; private set; } - public SLIdentifier Name { get; private set; } - public SLTupleType Parameters { get; private set; } - public SLCodeBlock GetterBody { get; private set; } - public SLCodeBlock SetterBody { get; private set; } - public bool IsAsync { get; private set; } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs deleted file mode 100644 index 45020c6fdf57..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLReturn.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLReturn : DelegatedSimpleElement, ISLExpr, ISLLineable { - public SLReturn (ISLExpr expr) - { - Value = expr; - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("return ", true); - if (Value != null) - Value.WriteAll (writer); - } - - public ISLExpr Value { get; private set; } - - public static SLLine ReturnLine (ISLExpr expr) - { - return new SLLine (new SLReturn (expr)); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs deleted file mode 100644 index 9cdca1537562..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscript.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Linq; - -namespace SyntaxDynamo.SwiftLang { - public class SLSubscript : CodeElementCollection { - // VIS subscript(parms) -> type { - // get { - // } - // set { // newValue:type is implicit - // } - // } - // get is mandatory, set is optional - - public SLSubscript (Visibility vis, FunctionKind funcKind, SLType type, - SLParameterList parms, SLCodeBlock getter, SLCodeBlock setter, - bool isAsync = false) - { - IsAsync = isAsync; - Visibility = vis; - Type = Exceptions.ThrowOnNull (type, nameof(type)); - Parameters = Exceptions.ThrowOnNull (parms, nameof(parms)); - GetterBody = Exceptions.ThrowOnNull (getter, nameof(getter)); - SetterBody = setter; // can be null - - List elems = new List (); - if (vis != Visibility.None) - elems.Add (SLFunc.ToVisibilityString (vis) + " "); - if ((funcKind & FunctionKind.Final) != 0) - elems.Add ("final "); - if ((funcKind & FunctionKind.Override) != 0) - elems.Add ("override "); - if ((funcKind & FunctionKind.Required) != 0) - elems.Add ("required "); - if ((funcKind & FunctionKind.Static) != 0) - elems.Add ("static "); - if ((funcKind & FunctionKind.Class) != 0) - elems.Add ("class "); - elems.Add ("subscript "); - - AddRange (elems.Select ((el, i) => i == 0 ? (ICodeElement)new SimpleLineElement (el, false, true, true) : new SimpleElement (el))); - Add (Parameters); - Add (SimpleElement.Spacer); - Add (new SimpleElement ("->")); - Add (SimpleElement.Spacer); - Add (Type); - SLCodeBlock block = new SLCodeBlock (null); - block.Add (new SimpleElement ("get")); - block.Add (SimpleElement.Spacer); - if (isAsync) { - block.Add (new SimpleElement ("async")); - block.Add (SimpleElement.Spacer); - } - block.Add (GetterBody); - if (SetterBody != null) { - block.Add (new SimpleElement ("set")); - block.Add (SimpleElement.Spacer); - block.Add (SetterBody); - } - Add (block); - } - - public Visibility Visibility { get; private set; } - public SLType Type { get; private set; } - public SLParameterList Parameters { get; private set; } - public SLCodeBlock GetterBody { get; private set; } - public SLCodeBlock SetterBody { get; private set; } - public bool IsAsync { get; private set; } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs deleted file mode 100644 index 951344f167a4..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSubscriptExpr.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLSubscriptExpr : SLBaseExpr { - public SLSubscriptExpr (SLIdentifier ident, CommaListElementCollection paramList) - { - Name = Exceptions.ThrowOnNull (ident, nameof(ident)); - Parameters = Exceptions.ThrowOnNull (paramList, nameof(paramList)); - } - - public SLSubscriptExpr (string identifier, params SLBaseExpr [] parameters) - : this (new SLIdentifier (identifier), new CommaListElementCollection (parameters)) - { - } - - public SLSubscriptExpr (SLIdentifier identifier, IEnumerable parameters) - : this (identifier, new CommaListElementCollection (parameters)) - { - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Name.WriteAll (writer); - writer.Write ("[", false); - Parameters.WriteAll (writer); - writer.Write ("]", false); - } - - public SLIdentifier Name { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs deleted file mode 100644 index ef6dea408660..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLSwitch.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLCase : DelegatedSimpleElement, ISLStatement { - public SLCase (ICodeElement caseExpr, ICodeElement actions) - { - CaseExpr = caseExpr; - Actions = actions; - } - - public ICodeElement CaseExpr { get; private set; } - public ICodeElement Actions { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - if (CaseExpr != null) { - writer.Write ("case ", true); - CaseExpr.WriteAll (writer); - } else { - writer.Write ("default", true); - } - writer.Write (" : ", true); - if (Actions != null) { - if (Actions is ICodeElementSet) { - writer.EndLine (); - writer.Indent (); - writer.BeginNewLine (true); - } - Actions.WriteAll (writer); - writer.EndLine (); - if (Actions is ICodeElementSet) { - writer.Exdent (); - } - } - } - } - - public class SLSwitch : ICodeElementSet, ISLStatement, ISLLineable { - public SLSwitch (ISLExpr switchOn, IEnumerable cases) - { - Cases = new List (); - if (cases != null) { - Cases.AddRange (cases); - } - SwitchOn = switchOn; - } - - public ISLExpr SwitchOn { get; set; } - public List Cases { get; private set; } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - writer.BeginNewLine (true); - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - yield return new SimpleElement ("switch"); - yield return SimpleElement.Spacer; - yield return SwitchOn; - yield return SimpleElement.Spacer; - SLCodeBlock caseBlock = new SLCodeBlock (Cases); - yield return caseBlock; - } - } - - #endregion - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs deleted file mode 100644 index bc4ebcef0544..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLThrow.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang -{ - public class SLThrow : SLBaseExpr, ISLStatement, ISLLineable - { - public SLThrow (SLBaseExpr expr) - { - Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); - } - - public SLBaseExpr Expr { get; private set; } - - #region implemented abstract members of DelegatedSimpleElem - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("throw ", true); - Expr.WriteAll (writer); - } - - #endregion - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs deleted file mode 100644 index 93de5f989d88..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTryBang.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo.SwiftLang { - - public class SLTry : SLBaseExpr, ISLLineable { - public SLTry (SLBaseExpr expr) - : this (expr, false) - { - } - - public SLTry (SLBaseExpr expr, bool isTryBang) - { - Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); - IsTryBang = isTryBang; - } - - public SLBaseExpr Expr { get; private set; } - public bool IsTryBang { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - string bang = IsTryBang ? "!" : ""; - writer.Write ($"try{bang} ", true); - Expr.WriteAll (writer); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs deleted file mode 100644 index 9fa7b7b11cf0..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLTupleExpr.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; - -namespace SyntaxDynamo.SwiftLang { - public class SLTupleExpr : SLBaseExpr { - public SLTupleExpr (IEnumerable values) - { - Values = new List (); - Values.AddRange (Exceptions.ThrowOnNull (values, nameof(values))); - } - - public List Values { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('(', true); - for (int i = 0; i < Values.Count; i++) { - if (i > 0) { - writer.Write (", ", true); - } - Values [i].WriteAll (writer); - } - writer.Write (')', true); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs deleted file mode 100644 index fdf113757ed8..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLType.cs +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.IO; - -namespace SyntaxDynamo.SwiftLang { - public abstract class SLType : DelegatedSimpleElement { - public SLType (bool isAny = false) - { - IsAny = isAny; - } - public override string ToString () => CodeWriter.WriteToString (this); - public bool IsAny { get; set; } - protected string AnyString => IsAny ? "any " : ""; - } - - public class SLCompoundType : SLType { - public SLCompoundType(SLType parent, SLType child, bool isAny = false) - : base (isAny) - { - Parent = Exceptions.ThrowOnNull (parent, nameof (parent)); - Child = Exceptions.ThrowOnNull (child, nameof (child)); - } - public SLType Parent { get; private set; } - public SLType Child { get; private set; } - - protected override void LLWrite(ICodeWriter writer, object o) - { - writer.Write (AnyString, true); - Parent.Write (writer, o); - writer.Write ('.', false); - Child.Write (writer, o); - } - } - - public class SLSimpleType : SLType { - public SLSimpleType (string name, bool isAny = false) - : base (isAny) - { - Name = Exceptions.ThrowOnNull (name, nameof(name)); - } - - public string Name { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (AnyString, true); - writer.Write (Name, false); - } - - static SLType - tBool = new SLSimpleType ("Bool"), - tChar = new SLSimpleType ("Character"), - tInt8 = new SLSimpleType ("Int8"), - tInt16 = new SLSimpleType ("Int16"), - tInt32 = new SLSimpleType ("Int32"), - tInt64 = new SLSimpleType ("Int64"), - tInt = new SLSimpleType ("Int"), - tUint8 = new SLSimpleType ("UInt8"), - tUint16 = new SLSimpleType ("UInt16"), - tUint32 = new SLSimpleType ("UInt32"), - tUint64 = new SLSimpleType ("UInt64"), - tUint = new SLSimpleType ("UInt"), - tFloat = new SLSimpleType ("Float"), - tDouble = new SLSimpleType ("Double"), - tString = new SLSimpleType ("String"), - tVoid = new SLSimpleType ("Void"), - tOpaquePointer = new SLSimpleType("OpaquePointer") - ; - - public static SLType Bool { get { return tBool; } } - public static SLType Char { get { return tChar; } } - public static SLType Int { get { return tInt; } } - public static SLType Int8 { get { return tInt8; } } - public static SLType Int16 { get { return tInt16; } } - public static SLType Int32 { get { return tInt32; } } - public static SLType Int64 { get { return tInt64; } } - public static SLType UInt { get { return tUint; } } - public static SLType UInt8 { get { return tUint8; } } - public static SLType UInt16 { get { return tUint16; } } - public static SLType UInt32 { get { return tUint32; } } - public static SLType UInt64 { get { return tUint64; } } - public static SLType Float { get { return tFloat; } } - public static SLType Double { get { return tDouble; } } - public static SLType String { get { return tString; } } - public static SLType Void { get { return tVoid; } } - public static SLType OpaquePointer { get { return tOpaquePointer; } } - - } - - public class SLProtocolListType : SLType { - public SLProtocolListType () - { - Protocols = new List (); - } - - public SLProtocolListType (IEnumerable types) - : this () - { - Exceptions.ThrowOnNull (types, nameof (types)); - Protocols.AddRange (types); - } - - public List Protocols { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (Protocols.Count < 2) - throw new Exception ("Protocol list types must have at least two elements"); - Protocols [0].WriteAll (writer); - for (int i = 1; i < Protocols.Count; i++) { - writer.Write (" & ", true); - Protocols [i].WriteAll (writer); - } - } - } - - public class SLOptionalType : SLType { - public SLOptionalType (SLType opt) - : base (false) - { - Optional = Exceptions.ThrowOnNull (opt, nameof (opt)); - } - - public SLType Optional { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - bool containsFuncType = Optional is SLFuncType; - if (containsFuncType) - writer.Write ('(', true); - Optional.WriteAll (writer); - if (containsFuncType) - writer.Write (')', true); - writer.Write ('?', true); - } - } - - public class SLBoundGenericType : SLType { - public SLBoundGenericType (string name, IEnumerable boundTypes) - : base (false) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - BoundTypes = new List (); - if (boundTypes != null) - BoundTypes.AddRange (boundTypes); - } - - public SLBoundGenericType (string name, string singleBoundType) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - BoundTypes = new List (); - BoundTypes.Add (new SLSimpleType (singleBoundType)); - } - - public SLBoundGenericType (string name, SLType singleBoundType) - : this (name, new SLType [] { singleBoundType }) - { - } - - public string Name { get; private set; } - public List BoundTypes { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Name, false); - writer.Write ('<', true); - for (int i = 0; i < BoundTypes.Count; i++) { - if (i > 0) - writer.Write (", ", true); - BoundTypes [i].WriteAll (writer); - } - writer.Write ('>', true); - } - - } - - public class SLArrayType : SLType { - public SLArrayType (SLType elementType) - : base (false) - { - ElementType = Exceptions.ThrowOnNull (elementType, nameof (elementType)); - } - - public SLType ElementType { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('[', true); - ElementType.WriteAll (writer); - writer.Write (']', true); - } - - } - - public class SLTupleType : SLType { - public SLTupleType (List pairs) - : base (false) - { - Elements = new List (); - if (pairs != null) - Elements.AddRange (pairs); - } - - public SLTupleType (params SLNameTypePair [] pairs) - : base (false) - { - Elements = new List (); - Elements.AddRange (pairs); - } - - public List Elements { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('(', true); - for (int i = 0; i < Elements.Count; i++) { - if (i > 0) { - writer.Write (", ", true); - } - Elements [i].WriteAll (writer); - } - writer.Write (')', true); - } - - public static SLTupleType Of (SLIdentifier id, SLType type) - { - return new SLTupleType (new SLNameTypePair [] { new SLNameTypePair (id, type) }); - } - - public static SLTupleType Of (string id, SLType type) - { - return Of (new SLIdentifier (id), type); - } - } - - - public class SLFuncType : SLType { - public SLFuncType (SLType argType, SLType retType, bool hasThrows = false, bool isAsync = false) - : this (retType, ConvertSLTypeToParameters (argType), hasThrows, isAsync) - { - } - - public SLFuncType (SLType retType, IEnumerable parameters, - bool hasThrows = false, bool isAsync = false) - : base (false) - { - Exceptions.ThrowOnNull (parameters, nameof (parameters)); - Attributes = new List (); - Parameters = new List (); - if (parameters != null) - Parameters.AddRange (parameters); - ReturnType = Exceptions.ThrowOnNull (retType, nameof (retType)); - Throws = hasThrows; - IsAsync = isAsync; - } - - public List Parameters { get; private set; } - public SLType ReturnType { get; private set; } - public List Attributes { get; private set; } - public bool Throws { get; private set; } - public bool IsAsync { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - foreach (var attr in Attributes) { - attr.WriteAll (writer); - writer.Write (' ', true); - } - writer.Write ('(', true); - for (int i = 0; i < Parameters.Count; i++) { - if (i > 0) - writer.Write (", ", true); - Parameters [i].WriteAll (writer); - } - writer.Write (") ", true); - if (IsAsync) { - writer.Write ("async ", true); - } - if (Throws) { - writer.Write ("throws", true); - } - writer.Write ("-> ", true); - ReturnType.WriteAll (writer); - } - - static IEnumerable ConvertSLTypeToParameters (SLType type) - { - if (type is SLTupleType tuple) { - foreach (var elem in tuple.Elements) { - yield return new SLUnnamedParameter (elem.TypeAnnotation, elem.ParameterKind); - } - } else { - yield return new SLUnnamedParameter (type); - } - } - } - - public class SLDictionaryType : SLType { - public SLDictionaryType (SLType keyType, SLType valueType) - : base (false) - { - KeyType = Exceptions.ThrowOnNull (keyType, nameof (keyType)); - ValueType = Exceptions.ThrowOnNull (valueType, nameof (valueType)); - } - - public SLType KeyType { get; private set; } - public SLType ValueType { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("[", true); - KeyType.WriteAll (writer); - writer.Write (" : ", true); - ValueType.WriteAll (writer); - writer.Write ("]", true); - } - } - - - public class SLGenericReferenceType : SLType { - public SLGenericReferenceType (int depth, int index, bool isMetatype = false, List associatedTypePath = null) - : base (false) - { - if (depth < 0) - throw new ArgumentOutOfRangeException (nameof (depth)); - if (index < 0) - throw new ArgumentOutOfRangeException (nameof (index)); - Depth = depth; - Index = index; - IsMetatype = isMetatype; - AssociatedTypePath = associatedTypePath; - } - - public int Depth { get; private set; } - public int Index { get; private set; } - public bool IsMetatype { get; private set; } - public Func ReferenceNamer { get; set; } - public List AssociatedTypePath { get; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - var suffix = IsMetatype ? ".Type" : ""; - string name; - if (AssociatedTypePath != null && AssociatedTypePath.Any ()) { - name = $"{Name}.{AssociatedTypePath.First ()}{suffix}"; - } else { - name = $"{Name}{suffix}"; - } - writer.Write (name, true); - } - - public string Name { - get { - Func namer = ReferenceNamer ?? DefaultNamer; - return namer (Depth, Index); - } - } - - const string kNames = "TUVWABCDEFGHIJKLMN"; - - public static string DefaultNamer (int depth, int index) - { - if (depth < 0 || depth >= kNames.Length) - throw new ArgumentOutOfRangeException (nameof (depth)); - if (index < 0) - throw new ArgumentOutOfRangeException (nameof (index)); - return String.Format ("{0}{1}", kNames [depth], index); - } - } - - public class SLVariadicType : SLType { - public SLVariadicType (SLType repeatingType) - : base (repeatingType.IsAny) - { - RepeatingType = Exceptions.ThrowOnNull (repeatingType, nameof (repeatingType)); - } - - public SLType RepeatingType { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - RepeatingType.WriteAll (writer); - writer.Write (" ...", true); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs deleted file mode 100644 index 31eaadbd7712..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLUnaryExpr.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SyntaxDynamo.SwiftLang { - public class SLUnaryExpr : SLBaseExpr { - public SLUnaryExpr (string op, ISLExpr expr, bool isPrefix) - { - Operation = Exceptions.ThrowOnNull (op, nameof (op)); - Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); - IsPrefix = isPrefix; - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (IsPrefix) { - writer.Write (' ', false); - writer.Write (Operation, false); - Expr.WriteAll (writer); - } else { - Expr.WriteAll (writer); - writer.Write (Operation, false); - writer.Write (' ', false); - } - } - - public bool IsPrefix { get; private set; } - public string Operation { get; private set; } - public ISLExpr Expr { get; private set; } - - public static SLUnaryExpr Await (ISLExpr expr) - { - return new SLUnaryExpr ("await ", expr, true); - } - } -} diff --git a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs b/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs deleted file mode 100644 index 6eaba12e94aa..000000000000 --- a/src/SyntaxDynamo/SyntaxDynamo.SwiftLang/SLVariadicExpr.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SyntaxDynamo.SwiftLang { - public class SLVariadicExpr : SLBaseExpr { - public SLVariadicExpr (DelegatedCommaListElemCollection paramList) - { - Parameters = paramList ?? new DelegatedCommaListElemCollection (WriteElement); - } - - public SLVariadicExpr (params SLBaseExpr [] paramList) - : this (new DelegatedCommaListElemCollection (WriteElement, paramList)) - { - } - - public static void WriteElement (ICodeWriter writer, int i, SLBaseExpr arg) - { - arg.WriteAll (writer); - } - - public DelegatedCommaListElemCollection Parameters { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Parameters.WriteAll (writer); - } - } -} From 61aeb9e9030f5af1e0b81f813565de2b4db432df Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 18:21:29 +0100 Subject: [PATCH 10/37] Update README.md --- README.md | 10 +++++----- src/SwiftBindings/src/Program.cs | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f07814db03e4..05e1ef7c08ac 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@ The tool will be available as a NuGet CLI package in the [`dotnet-experimental`] Options: ``` - -d, --dylibs Required. Paths to the dynamic libraries (dylibs), separated by commas. - -s, --swiftinterfaces Required. Paths to the Swift interface files, separated by commas. - -o, --output Required. Output directory for generated bindings. - -h, --help Display this help message. - --version Display version information. + -d, --dylib Required. Path to the dynamic library. + -s, --swiftinterface Required. Path to the Swift interface file. + -o, --output Required. Output directory for generated bindings. + -v, --verbosity Information about work in process. + -h, --help Display this help message. ``` ## .NET Foundation diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs index 9784bff6c76c..9609ec7eb895 100644 --- a/src/SwiftBindings/src/Program.cs +++ b/src/SwiftBindings/src/Program.cs @@ -31,9 +31,9 @@ public static void Main(string[] args) if (help) { Console.WriteLine("Usage:"); - Console.WriteLine(" -d, --dylib Path to the dynamic library."); - Console.WriteLine(" -s, --swiftinterfaces Path to the Swift interface file."); - Console.WriteLine(" -o, --output Output directory for generated bindings."); + Console.WriteLine(" -d, --dylib Required. Path to the dynamic library."); + Console.WriteLine(" -s, --swiftinterface Required. Path to the Swift interface file."); + Console.WriteLine(" -o, --output Required. Output directory for generated bindings."); Console.WriteLine(" -v, --verbosity Information about work in process."); return; } From 002ac6a176f74d99e69c65a982e3f045c1bdde4e Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 18:25:35 +0100 Subject: [PATCH 11/37] Remove Swift4 support --- src/SwiftReflector/Demangling/Decomposer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/SwiftReflector/Demangling/Decomposer.cs b/src/SwiftReflector/Demangling/Decomposer.cs index 1106bee7e818..6bf75b159253 100644 --- a/src/SwiftReflector/Demangling/Decomposer.cs +++ b/src/SwiftReflector/Demangling/Decomposer.cs @@ -10,7 +10,6 @@ namespace SwiftReflector.Demangling { public class Decomposer { const string kSwiftID = "__T"; - public const string kSwift4ID = "__T0"; public const string kSwift4xID = "_$s"; public const string kSwift5ID = "_$S"; public static SwiftName kSwiftAllocatingConstructorName = new SwiftName (".ctor", false); From 5ddfc2024bf46a09b915116f46f97262362002a8 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 18:33:09 +0100 Subject: [PATCH 12/37] Rename verbose argument --- README.md | 2 +- src/SwiftBindings/src/Program.cs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 05e1ef7c08ac..9ec233973565 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Options: -d, --dylib Required. Path to the dynamic library. -s, --swiftinterface Required. Path to the Swift interface file. -o, --output Required. Output directory for generated bindings. - -v, --verbosity Information about work in process. + -v, --verbose Information about work in process. -h, --help Display this help message. ``` diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs index 9609ec7eb895..e64846a10638 100644 --- a/src/SwiftBindings/src/Program.cs +++ b/src/SwiftBindings/src/Program.cs @@ -15,7 +15,7 @@ public static void Main(string[] args) Option> dylibOption = new(aliases: new [] {"-d", "--dylib"}, description: "Path to the dynamic library.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; Option> swiftinterfaceOption = new(aliases: new [] {"-s", "--swiftinterface"}, "Path to the Swift interface file.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; Option outputDirectoryOption = new(aliases: new [] {"-o", "--output"}, "Output directory for generated bindings.") {IsRequired = true}; - Option verbosityOption = new(aliases: new [] {"-v", "--verbosity"}, "Prints information about work in process."); + Option verboseOption = new(aliases: new [] {"-v", "--verbose"}, "Prints information about work in process."); Option helpOption = new(aliases: new [] {"-h", "--help"}, "Display a help message."); RootCommand rootCommand = new(description: "Swift bindings generator.") @@ -23,10 +23,10 @@ public static void Main(string[] args) dylibOption, swiftinterfaceOption, outputDirectoryOption, - verbosityOption, + verboseOption, helpOption, }; - rootCommand.SetHandler((IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory, int verbosity, bool help) => + rootCommand.SetHandler((IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory, int verbose, bool help) => { if (help) { @@ -34,7 +34,7 @@ public static void Main(string[] args) Console.WriteLine(" -d, --dylib Required. Path to the dynamic library."); Console.WriteLine(" -s, --swiftinterface Required. Path to the Swift interface file."); Console.WriteLine(" -o, --output Required. Output directory for generated bindings."); - Console.WriteLine(" -v, --verbosity Information about work in process."); + Console.WriteLine(" -v, --verbose Information about work in process."); return; } @@ -57,7 +57,7 @@ public static void Main(string[] args) return; } - GenerateBindings(dylibPath, swiftInterfacePath, outputDirectory, verbosity); + GenerateBindings(dylibPath, swiftInterfacePath, outputDirectory, verbose); } } @@ -65,7 +65,7 @@ public static void Main(string[] args) dylibOption, swiftinterfaceOption, outputDirectoryOption, - verbosityOption, + verboseOption, helpOption ); @@ -95,7 +95,7 @@ private static bool ValidateOptions(IEnumerable dylibPaths, IEnumerable< return true; } - public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory, int verbositry = 0) + public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory, int verbose = 0) { BindingsCompiler bindingsCompiler = new BindingsCompiler(); var errors = new ErrorHandling (); From a3526963b8211527b1a2b67bded275f7370e9c4a Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 18:45:42 +0100 Subject: [PATCH 13/37] Update src/SwiftBindings/tests/CMakeLists.txt Co-authored-by: Jeremy Koritzinsky --- src/SwiftBindings/tests/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index ad95d4b52694..54874c422d04 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests) +project(SmokeTests Swift) set(SOURCE SmokeTests) From 91dd9fdb81d1323a923dd4dfc1f3a020b0cc6ee3 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 18:51:27 +0100 Subject: [PATCH 14/37] Use ninja generator for cmake --- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index e9bedd90a5dc..d862a01349b1 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make + cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja From 0b3f817672db895083452150c5b8a853b58d03ef Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 19:05:57 +0100 Subject: [PATCH 15/37] Fix lint formatting --- src/SwiftBindings/src/Program.cs | 20 +- src/SwiftBindings/tests/TestsHelper.cs | 2 +- src/SwiftReflector/BindingsCompiler.cs | 505 +- src/SwiftReflector/CSKeywords.cs | 69 +- .../Demangling/ContextAttribute.cs | 10 +- src/SwiftReflector/Demangling/Decomposer.cs | 2401 ++++--- src/SwiftReflector/Demangling/Enums.cs | 719 +- src/SwiftReflector/Demangling/MatchRule.cs | 158 +- src/SwiftReflector/Demangling/Node.cs | 489 +- src/SwiftReflector/Demangling/RuleRunner.cs | 28 +- .../Demangling/Swift5Demangler.cs | 6159 +++++++++-------- .../Demangling/Swift5NodeToTLDefinition.cs | 4175 +++++------ src/SwiftReflector/Demangling/TLDefinition.cs | 542 +- src/SwiftReflector/Enums.cs | 369 +- src/SwiftReflector/ErrorHandling.cs | 199 +- .../ExceptionTools/ErrorHelper.cs | 352 +- .../ExceptionTools/RuntimeException.cs | 106 +- src/SwiftReflector/Extensions.cs | 456 +- src/SwiftReflector/IOUtils/ExecAndCollect.cs | 224 +- src/SwiftReflector/IOUtils/IFileProvider.cs | 12 +- .../IOUtils/IXElementConvertible.cs | 10 +- src/SwiftReflector/IOUtils/OffsetStream.cs | 311 +- src/SwiftReflector/Inventory/ClassContents.cs | 598 +- .../Inventory/ClassInventory.cs | 109 +- .../Inventory/FunctionInventory.cs | 182 +- src/SwiftReflector/Inventory/Inventory.cs | 70 +- .../Inventory/ModuleContents.cs | 184 +- .../Inventory/ModuleInventory.cs | 326 +- .../Inventory/OverloadInventory.cs | 58 +- .../Inventory/PropertyContents.cs | 386 +- .../Inventory/PropertyInventory.cs | 88 +- .../Inventory/ProtocolContents.cs | 143 +- .../Inventory/ProtocolInventory.cs | 46 +- .../Inventory/VariableContents.cs | 30 +- .../Inventory/VariableInventory.cs | 80 +- .../Inventory/WitnessInventory.cs | 98 +- src/SwiftReflector/MachOHawley.cs | 2353 ++++--- src/SwiftReflector/MarshalEngine.cs | 559 +- src/SwiftReflector/PunyCode.cs | 314 +- src/SwiftReflector/ReflectorError.cs | 105 +- src/SwiftReflector/StringSlice.cs | 429 +- src/SwiftReflector/SwiftClassName.cs | 167 +- .../SwiftInterfaceReflector/IModuleLoader.cs | 37 +- .../ObjCSelectorFactory.cs | 640 +- .../SwiftInterfaceReflector/ParseException.cs | 30 +- .../SwiftInterfaceReflector.cs | 4758 ++++++------- .../SyntaxDesugaringParser.cs | 196 +- src/SwiftReflector/SwiftName.cs | 76 +- src/SwiftReflector/SwiftType.cs | 2304 +++--- .../AssociatedTypeDeclaration.cs | 109 +- .../AttributeDeclaration.cs | 290 +- .../SwiftXmlReflection/BaseConstraint.cs | 390 +- .../SwiftXmlReflection/BaseDeclaration.cs | 1159 ++-- .../SwiftXmlReflection/ClassDeclaration.cs | 40 +- .../SwiftXmlReflection/EnumDeclaration.cs | 228 +- .../SwiftXmlReflection/EnumElement.cs | 95 +- .../SwiftXmlReflection/Enums.cs | 149 +- .../ExtensionDeclaration.cs | 151 +- .../SwiftXmlReflection/ExtensionMethods.cs | 74 +- .../SwiftXmlReflection/FunctionDeclaration.cs | 984 +-- .../SwiftXmlReflection/GenericDeclaration.cs | 226 +- .../GenericDeclarationCollection.cs | 68 +- .../GenericReferenceAssociatedTypeProtocol.cs | 12 +- .../SwiftXmlReflection/Inheritance.cs | 129 +- .../SwiftXmlReflection/Member.cs | 83 +- .../SwiftXmlReflection/ModuleDeclaration.cs | 382 +- .../SwiftXmlReflection/OperatorDeclaration.cs | 77 +- .../SwiftXmlReflection/ParameterItem.cs | 424 +- .../SwiftXmlReflection/PropertyDeclaration.cs | 346 +- .../SwiftXmlReflection/ProtocolDeclaration.cs | 110 +- .../SwiftXmlReflection/Reflector.cs | 220 +- .../SwiftXmlReflection/ShamDeclaration.cs | 73 +- .../SwiftXmlReflection/StructDeclaration.cs | 24 +- .../SubscriptDeclaration.cs | 30 +- .../TypeAliasDeclaration.cs | 170 +- .../SwiftXmlReflection/TypeAliasFolder.cs | 487 +- .../SwiftXmlReflection/TypeDeclaration.cs | 1091 +-- .../SwiftXmlReflection/TypeSpec.cs | 1672 ++--- .../SwiftXmlReflection/TypeSpecParser.cs | 624 +- .../SwiftXmlReflection/TypeSpecToken.cs | 106 +- .../SwiftXmlReflection/TypeSpecTokenizer.cs | 381 +- .../TopLevelFunctionCompiler.cs | 682 +- src/SwiftReflector/TypeMapping/Entity.cs | 132 +- .../TypeMapping/ModuleDatabase.cs | 22 +- src/SwiftReflector/TypeMapping/NetParam.cs | 22 +- .../TypeMapping/NetTypeBundle.cs | 429 +- .../TypeMapping/TypeDatabase.cs | 958 +-- src/SwiftReflector/TypeMapping/TypeMapper.cs | 2361 ++++--- src/SwiftReflector/UnicodeMapper.cs | 197 +- src/SwiftReflector/ValueWitnessTable.cs | 229 +- src/SwiftReflector/XmlToTLFunctionMapper.cs | 1011 +-- src/SwiftRuntimeLibrary/Exceptions.cs | 36 +- src/SwiftRuntimeLibrary/ISwiftObject.cs | 10 +- src/SyntaxDynamo/CodeElementCollection.cs | 78 +- src/SyntaxDynamo/CodeWriter.cs | 288 +- .../CommaListElementCollection.cs | 156 +- .../DecoratedCodeElementCollection.cs | 130 +- .../DelegatedCommaListElementCollection.cs | 105 +- src/SyntaxDynamo/DelegatedSimpleElement.cs | 95 +- src/SyntaxDynamo/Exceptions.cs | 31 +- src/SyntaxDynamo/Extensions.cs | 118 +- src/SyntaxDynamo/ICodeElement.cs | 32 +- src/SyntaxDynamo/ICodeElementSet.cs | 10 +- src/SyntaxDynamo/ICodeWriter.cs | 24 +- .../LabeledCodeElementCollection.cs | 116 +- src/SyntaxDynamo/LineCodeElementCollection.cs | 95 +- src/SyntaxDynamo/SimpleElement.cs | 106 +- src/SyntaxDynamo/SimpleLineElement.cs | 92 +- .../SyntaxDynamo.CSLang/CSArgument.cs | 53 +- .../SyntaxDynamo.CSLang/CSArray1D.cs | 212 +- .../SyntaxDynamo.CSLang/CSAssignment.cs | 129 +- .../SyntaxDynamo.CSLang/CSAttribute.cs | 145 +- .../SyntaxDynamo.CSLang/CSBaseExpression.cs | 172 +- .../SyntaxDynamo.CSLang/CSBinaryExpression.cs | 141 +- .../SyntaxDynamo.CSLang/CSBinding.cs | 121 +- .../SyntaxDynamo.CSLang/CSClass.cs | 403 +- .../SyntaxDynamo.CSLang/CSCodeBlock.cs | 91 +- .../SyntaxDynamo.CSLang/CSComment.cs | 100 +- .../CSConditionalCompilation.cs | 55 +- .../SyntaxDynamo.CSLang/CSConstant.cs | 116 +- .../SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs | 66 +- .../SyntaxDynamo.CSLang/CSEnum.cs | 190 +- .../SyntaxDynamo.CSLang/CSFieldDeclaration.cs | 199 +- .../SyntaxDynamo.CSLang/CSFile.cs | 126 +- .../SyntaxDynamo.CSLang/CSFileBasic.cs | 120 +- .../SyntaxDynamo.CSLang/CSFixed.cs | 52 +- .../SyntaxDynamo.CSLang/CSForEach.cs | 116 +- .../SyntaxDynamo.CSLang/CSFunctionCall.cs | 250 +- .../CSGenericConstraint.cs | 129 +- .../CSGenericTypeDeclaration.cs | 118 +- .../SyntaxDynamo.CSLang/CSIdentifier.cs | 64 +- .../SyntaxDynamo.CSLang/CSIfElse.cs | 104 +- .../SyntaxDynamo.CSLang/CSIndexExpression.cs | 74 +- .../SyntaxDynamo.CSLang/CSInheritance.cs | 36 +- .../SyntaxDynamo.CSLang/CSInitializer.cs | 81 +- .../SyntaxDynamo.CSLang/CSInject.cs | 30 +- .../SyntaxDynamo.CSLang/CSInterface.cs | 227 +- .../SyntaxDynamo.CSLang/CSLambda.cs | 118 +- .../SyntaxDynamo.CSLang/CSLine.cs | 42 +- .../SyntaxDynamo.CSLang/CSMethod.cs | 452 +- .../SyntaxDynamo.CSLang/CSNamespace.cs | 85 +- .../SyntaxDynamo.CSLang/CSParameter.cs | 180 +- .../CSParenthesisExpression.cs | 83 +- .../SyntaxDynamo.CSLang/CSProperty.cs | 369 +- .../SyntaxDynamo.CSLang/CSReturn.cs | 38 +- .../SyntaxDynamo.CSLang/CSShortCircuit.cs | 52 +- .../SyntaxDynamo.CSLang/CSTernary.cs | 64 +- .../SyntaxDynamo.CSLang/CSThrow.cs | 80 +- .../SyntaxDynamo.CSLang/CSTryCatch.cs | 131 +- .../SyntaxDynamo.CSLang/CSType.cs | 508 +- .../SyntaxDynamo.CSLang/CSUnaryExpression.cs | 188 +- .../SyntaxDynamo.CSLang/CSUsing.cs | 105 +- src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs | 172 +- .../SyntaxDynamo.CSLang/ICSExpression.cs | 13 +- .../SyntaxDynamo.CSLang/ICSLineable.cs | 8 +- .../SyntaxDynamo.CSLang/ICSStatement.cs | 8 +- .../ICSTopLevelDeclaration.cs | 23 +- src/SyntaxDynamo/WriteEventArgs.cs | 22 +- 158 files changed, 29340 insertions(+), 26772 deletions(-) diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs index e64846a10638..cfd6a7eea70c 100644 --- a/src/SwiftBindings/src/Program.cs +++ b/src/SwiftBindings/src/Program.cs @@ -12,11 +12,11 @@ public class BindingsTool { public static void Main(string[] args) { - Option> dylibOption = new(aliases: new [] {"-d", "--dylib"}, description: "Path to the dynamic library.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; - Option> swiftinterfaceOption = new(aliases: new [] {"-s", "--swiftinterface"}, "Path to the Swift interface file.") {AllowMultipleArgumentsPerToken = true, IsRequired = true}; - Option outputDirectoryOption = new(aliases: new [] {"-o", "--output"}, "Output directory for generated bindings.") {IsRequired = true}; - Option verboseOption = new(aliases: new [] {"-v", "--verbose"}, "Prints information about work in process."); - Option helpOption = new(aliases: new [] {"-h", "--help"}, "Display a help message."); + Option> dylibOption = new(aliases: new[] { "-d", "--dylib" }, description: "Path to the dynamic library.") { AllowMultipleArgumentsPerToken = true, IsRequired = true }; + Option> swiftinterfaceOption = new(aliases: new[] { "-s", "--swiftinterface" }, "Path to the Swift interface file.") { AllowMultipleArgumentsPerToken = true, IsRequired = true }; + Option outputDirectoryOption = new(aliases: new[] { "-o", "--output" }, "Output directory for generated bindings.") { IsRequired = true }; + Option verboseOption = new(aliases: new[] { "-v", "--verbose" }, "Prints information about work in process."); + Option helpOption = new(aliases: new[] { "-h", "--help" }, "Display a help message."); RootCommand rootCommand = new(description: "Swift bindings generator.") { @@ -37,7 +37,7 @@ public static void Main(string[] args) Console.WriteLine(" -v, --verbose Information about work in process."); return; } - + if (ValidateOptions(dylibPaths, swiftinterfacePaths, outputDirectory)) { for (int i = 0; i < dylibPaths.Count(); i++) @@ -98,10 +98,10 @@ private static bool ValidateOptions(IEnumerable dylibPaths, IEnumerable< public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory, int verbose = 0) { BindingsCompiler bindingsCompiler = new BindingsCompiler(); - var errors = new ErrorHandling (); - var moduleInventory = bindingsCompiler.GetModuleInventory(dylibPath, errors); - var moduleDeclarations = bindingsCompiler.GetModuleDeclarations(swiftInterfacePath); - bindingsCompiler.CompileModules(moduleDeclarations, moduleInventory, dylibPath, outputDirectory, errors); + var errors = new ErrorHandling(); + var moduleInventory = bindingsCompiler.GetModuleInventory(dylibPath, errors); + var moduleDeclarations = bindingsCompiler.GetModuleDeclarations(swiftInterfacePath); + bindingsCompiler.CompileModules(moduleDeclarations, moduleInventory, dylibPath, outputDirectory, errors); } } } diff --git a/src/SwiftBindings/tests/TestsHelper.cs b/src/SwiftBindings/tests/TestsHelper.cs index ad2fde361a82..1ca9e84f43d8 100644 --- a/src/SwiftBindings/tests/TestsHelper.cs +++ b/src/SwiftBindings/tests/TestsHelper.cs @@ -54,7 +54,7 @@ private static int CompileAndExecute(string[] sourceCodes) } Assembly compiledAssembly = Assembly.LoadFile(assemblyPath); - + MethodInfo entryPoint = compiledAssembly.EntryPoint; object[] args = entryPoint.GetParameters().Length == 0 ? null : new object[] { new string[0] }; int result = (int)entryPoint.Invoke(null, args); diff --git a/src/SwiftReflector/BindingsCompiler.cs b/src/SwiftReflector/BindingsCompiler.cs index c29dfcfa85fa..380cedcd4a63 100644 --- a/src/SwiftReflector/BindingsCompiler.cs +++ b/src/SwiftReflector/BindingsCompiler.cs @@ -24,247 +24,266 @@ using SwiftReflector.ExceptionTools; using SwiftReflector.SwiftInterfaceReflector; -namespace SwiftReflector { - public class BindingsCompiler { - UnicodeMapper UnicodeMapper; - TypeMapper TypeMapper; - TopLevelFunctionCompiler TLFCompiler; - SwiftInterfaceReflector.SwiftInterfaceReflector Reflector; - - public BindingsCompiler () - { - UnicodeMapper = new UnicodeMapper (); - TypeMapper = new TypeMapper (null, UnicodeMapper); - - TLFCompiler = new TopLevelFunctionCompiler (TypeMapper); - Reflector = new SwiftInterfaceReflector.SwiftInterfaceReflector (null, null); - } - - public ModuleInventory GetModuleInventory (string dylibPath, ErrorHandling errors) { - var moduleInventory = ModuleInventory.FromFile (dylibPath, errors); - return moduleInventory; - } - - public List GetModuleDeclarations (string swiftinterfacePath) { - var xdoc = Reflector.Reflect (swiftinterfacePath); - - var outputFile = System.IO.Path.GetTempPath() + Path.GetFileName(swiftinterfacePath) + ".xml"; - xdoc.Save (outputFile); - var moduleDeclarations = SwiftXmlReflection.Reflector.FromXmlFile (outputFile, null); - return moduleDeclarations; - } - - public void CompileModules (List moduleDeclarations, ModuleInventory moduleInventory, - string swiftLibPath, string outputDirectory, - ErrorHandling errors) - { - foreach (ModuleDeclaration module in moduleDeclarations) { - bool successfulOutput = false; - successfulOutput |= CompileTopLevelEntities (module, moduleInventory, swiftLibPath, outputDirectory, errors); - // successfulOutput |= CompileProtocols (module.Protocols, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileClasses (module.Classes, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileStructs (module.Structs, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileEnums (module.Enums, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileExtensions (module.Extensions, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - if (!successfulOutput) - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 16, "binding-tools-for-swift could not generate any output. Check the logs and consider using '--verbose' for more information."); - } - } - - bool CompileTopLevelEntities (ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors) - { - var use = new CSUsingPackages ("System", "System.Runtime.InteropServices"); - - var picl = new CSClass (CSVisibility.Internal, PIClassName (module.Name + "." + "TopLevelEntities")); - var usedPinvokes = new List (); - - var cl = CompileTLFuncs (module.TopLevelFunctions, module, moduleInventory, - swiftLibPath, outputDirectory, errors, use, null, picl, usedPinvokes); - - cl = CompileTLProps (module.TopLevelProperties, module, moduleInventory, - swiftLibPath, outputDirectory, errors, use, cl, picl, usedPinvokes); - - - if (cl != null) { - string nameSpace = TypeMapper.MapModuleToNamespace (module.Name); - var nm = new CSNamespace (nameSpace); - - var csfile = new CSFile (use, new CSNamespace [] { nm }); - nm.Block.Add (cl); - nm.Block.Add (picl); - string csOutputFileName = string.Format ("{1}{0}.cs", nameSpace, cl.Name.Name); - string csOutputPath = Path.Combine (outputDirectory, csOutputFileName); - - CodeWriter.WriteToFile (csOutputPath, csfile); - - } else { - Console.WriteLine ("No top-level entities"); - return false; - } - return true; - } - - CSClass CompileTLFuncs (IEnumerable funcs, - ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors, - CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokeNames) - { - var methods = new List (); - - foreach (FunctionDeclaration func in funcs) { - try { - if (func.IsProperty) - continue; - - if (func.IsDeprecated || func.IsUnavailable) - continue; - - var tlf = XmlToTLFunctionMapper.ToTLFunction (func, moduleInventory, TypeMapper); - CompileToDirectFunction (func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames); - } catch (Exception e) { - errors.Add (e); - } - } - - if (methods.Count > 0) { - cl = cl ?? new CSClass (CSVisibility.Public, "TopLevelEntities"); - cl.Methods.AddRange (methods); - } - return cl; - } - - void CompileToDirectFunction (FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context, - CSUsingPackages use, string swiftLibPath, List methods, CSClass picl, - List usedPinvokeNames) - { - // FIXME - need to do operators - if (tlf.Operator != OperatorType.None) - return; - - var baseName = TypeMapper.SanitizeIdentifier (tlf.Name.Name); - var pinvokeMethodName = PIFuncName (baseName + homonymSuffix); - pinvokeMethodName = Uniqueify (pinvokeMethodName, usedPinvokeNames); - usedPinvokeNames.Add (pinvokeMethodName); - - var pinvokeMethodRef = PIClassName ($"{func.Module.Name}.TopLevelEntities") + "." + pinvokeMethodName; - - var piMethod = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath), - tlf.MangledName, pinvokeMethodName, true, true, false); - picl.Methods.Add (piMethod); - - var publicMethodOrig = TLFCompiler.CompileMethod (func, use, PInvokeName (swiftLibPath), - tlf.MangledName, null, false, false, false); - - CSIdentifier wrapperName = GetMethodWrapperName (func, publicMethodOrig, homonymSuffix); - CSVisibility visibility = GetMethodWrapperVisibility (func, publicMethodOrig); - - // rebuild the method as static - var publicMethod = new CSMethod (visibility, CSMethodKind.Static, publicMethodOrig.Type, - wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body); - publicMethod.GenericParameters.AddRange (publicMethodOrig.GenericParameters); - publicMethod.GenericConstraints.AddRange (publicMethodOrig.GenericConstraints); - - var localIdents = new List { - publicMethod.Name.Name, pinvokeMethodName - }; - localIdents.AddRange (publicMethod.Parameters.Select (p => p.Name.Name)); - - var marshaler = new MarshalEngine (use, localIdents, TypeMapper, null); - var lines = marshaler.MarshalFunctionCall (func, false, pinvokeMethodRef, publicMethod.Parameters, - func, func.ReturnTypeSpec, publicMethod.Type, null, null, false, func, - false, -1, func.HasThrows); - publicMethod.Body.AddRange (lines); - methods.Add (publicMethod); - } - - CSClass CompileTLProps (IEnumerable props, - ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors, - CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokes) - { - var properties = new List (); - - foreach (PropertyDeclaration prop in props) { - if (prop.IsDeprecated || prop.IsUnavailable) - continue; - try { - cl = cl ?? new CSClass (CSVisibility.Public, "TopLevelEntities"); - - // Calculated properties have a matching __method - string backingMethodName = ("__" + prop.Name); - CSMethod backingMethod = cl.Methods.FirstOrDefault (x => x.Name.Name == backingMethodName); - } catch (Exception e) { - errors.Add (e); - } - } - - if (properties.Count > 0) { - cl.Properties.AddRange (properties); - } - return cl; - } - - string PIClassName (string fullClassName) - { - if (!fullClassName.Contains ('.')) - throw new ArgumentOutOfRangeException (nameof (fullClassName), String.Format ("Class name {0} should be a full class name.", fullClassName)); - fullClassName = fullClassName.Substring (fullClassName.IndexOf ('.') + 1).Replace ('.', '_'); - return "NativeMethodsFor" + fullClassName; - } - - string PIClassName (DotNetName fullClassName) - { - return PIClassName (fullClassName.Namespace + "." + fullClassName.TypeName); - } - - string PIClassName (SwiftClassName name) - { - return PIClassName (TypeMapper.GetDotNetNameForSwiftClassName (name)); - } - - string PIFuncName (SwiftName functionName) - { - return String.Format ("PIfunc_{0}", functionName.Name); - } - - string PIFuncName (string functionName) - { - return $"PIfunc_{functionName}"; - } - - CSIdentifier GetMethodWrapperName (FunctionDeclaration func, CSMethod method, string homonymSuffix) - { - string prefix = func.IsProperty ? "__" : ""; - return new CSIdentifier (prefix + method.Name.Name + homonymSuffix); - } - - - CSVisibility GetMethodWrapperVisibility (FunctionDeclaration func, CSMethod method) - { - return func.IsProperty ? CSVisibility.Private: method.Visibility; - } - - static string PInvokeName (string libFullPath, string originalLibrary = null) - { - return LibOrFrameworkFromPath (libFullPath); - } - - static string LibOrFrameworkFromPath (string libFullPath) - { - string directory = Path.GetDirectoryName (libFullPath); - string file = Path.GetFileName (libFullPath); - return file; - } - - public static string Uniqueify (string name, IEnumerable names) - { - int thisTime = 0; - var sb = new StringBuilder (name); - while (names.Contains (sb.ToString ())) { - sb.Clear ().Append (name).Append (thisTime++); - } - return sb.ToString (); - } - } +namespace SwiftReflector +{ + public class BindingsCompiler + { + UnicodeMapper UnicodeMapper; + TypeMapper TypeMapper; + TopLevelFunctionCompiler TLFCompiler; + SwiftInterfaceReflector.SwiftInterfaceReflector Reflector; + + public BindingsCompiler() + { + UnicodeMapper = new UnicodeMapper(); + TypeMapper = new TypeMapper(null, UnicodeMapper); + + TLFCompiler = new TopLevelFunctionCompiler(TypeMapper); + Reflector = new SwiftInterfaceReflector.SwiftInterfaceReflector(null, null); + } + + public ModuleInventory GetModuleInventory(string dylibPath, ErrorHandling errors) + { + var moduleInventory = ModuleInventory.FromFile(dylibPath, errors); + return moduleInventory; + } + + public List GetModuleDeclarations(string swiftinterfacePath) + { + var xdoc = Reflector.Reflect(swiftinterfacePath); + + var outputFile = System.IO.Path.GetTempPath() + Path.GetFileName(swiftinterfacePath) + ".xml"; + xdoc.Save(outputFile); + var moduleDeclarations = SwiftXmlReflection.Reflector.FromXmlFile(outputFile, null); + return moduleDeclarations; + } + + public void CompileModules(List moduleDeclarations, ModuleInventory moduleInventory, + string swiftLibPath, string outputDirectory, + ErrorHandling errors) + { + foreach (ModuleDeclaration module in moduleDeclarations) + { + bool successfulOutput = false; + successfulOutput |= CompileTopLevelEntities(module, moduleInventory, swiftLibPath, outputDirectory, errors); + // successfulOutput |= CompileProtocols (module.Protocols, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileClasses (module.Classes, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileStructs (module.Structs, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileEnums (module.Enums, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + // successfulOutput |= CompileExtensions (module.Extensions, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); + if (!successfulOutput) + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 16, "binding-tools-for-swift could not generate any output. Check the logs and consider using '--verbose' for more information."); + } + } + + bool CompileTopLevelEntities(ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors) + { + var use = new CSUsingPackages("System", "System.Runtime.InteropServices"); + + var picl = new CSClass(CSVisibility.Internal, PIClassName(module.Name + "." + "TopLevelEntities")); + var usedPinvokes = new List(); + + var cl = CompileTLFuncs(module.TopLevelFunctions, module, moduleInventory, + swiftLibPath, outputDirectory, errors, use, null, picl, usedPinvokes); + + cl = CompileTLProps(module.TopLevelProperties, module, moduleInventory, + swiftLibPath, outputDirectory, errors, use, cl, picl, usedPinvokes); + + + if (cl != null) + { + string nameSpace = TypeMapper.MapModuleToNamespace(module.Name); + var nm = new CSNamespace(nameSpace); + + var csfile = new CSFile(use, new CSNamespace[] { nm }); + nm.Block.Add(cl); + nm.Block.Add(picl); + string csOutputFileName = string.Format("{1}{0}.cs", nameSpace, cl.Name.Name); + string csOutputPath = Path.Combine(outputDirectory, csOutputFileName); + + CodeWriter.WriteToFile(csOutputPath, csfile); + + } + else + { + Console.WriteLine("No top-level entities"); + return false; + } + return true; + } + + CSClass CompileTLFuncs(IEnumerable funcs, + ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors, + CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokeNames) + { + var methods = new List(); + + foreach (FunctionDeclaration func in funcs) + { + try + { + if (func.IsProperty) + continue; + + if (func.IsDeprecated || func.IsUnavailable) + continue; + + var tlf = XmlToTLFunctionMapper.ToTLFunction(func, moduleInventory, TypeMapper); + CompileToDirectFunction(func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames); + } + catch (Exception e) + { + errors.Add(e); + } + } + + if (methods.Count > 0) + { + cl = cl ?? new CSClass(CSVisibility.Public, "TopLevelEntities"); + cl.Methods.AddRange(methods); + } + return cl; + } + + void CompileToDirectFunction(FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context, + CSUsingPackages use, string swiftLibPath, List methods, CSClass picl, + List usedPinvokeNames) + { + // FIXME - need to do operators + if (tlf.Operator != OperatorType.None) + return; + + var baseName = TypeMapper.SanitizeIdentifier(tlf.Name.Name); + var pinvokeMethodName = PIFuncName(baseName + homonymSuffix); + pinvokeMethodName = Uniqueify(pinvokeMethodName, usedPinvokeNames); + usedPinvokeNames.Add(pinvokeMethodName); + + var pinvokeMethodRef = PIClassName($"{func.Module.Name}.TopLevelEntities") + "." + pinvokeMethodName; + + var piMethod = TLFCompiler.CompileMethod(func, use, PInvokeName(swiftLibPath), + tlf.MangledName, pinvokeMethodName, true, true, false); + picl.Methods.Add(piMethod); + + var publicMethodOrig = TLFCompiler.CompileMethod(func, use, PInvokeName(swiftLibPath), + tlf.MangledName, null, false, false, false); + + CSIdentifier wrapperName = GetMethodWrapperName(func, publicMethodOrig, homonymSuffix); + CSVisibility visibility = GetMethodWrapperVisibility(func, publicMethodOrig); + + // rebuild the method as static + var publicMethod = new CSMethod(visibility, CSMethodKind.Static, publicMethodOrig.Type, + wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body); + publicMethod.GenericParameters.AddRange(publicMethodOrig.GenericParameters); + publicMethod.GenericConstraints.AddRange(publicMethodOrig.GenericConstraints); + + var localIdents = new List { + publicMethod.Name.Name, pinvokeMethodName + }; + localIdents.AddRange(publicMethod.Parameters.Select(p => p.Name.Name)); + + var marshaler = new MarshalEngine(use, localIdents, TypeMapper, null); + var lines = marshaler.MarshalFunctionCall(func, false, pinvokeMethodRef, publicMethod.Parameters, + func, func.ReturnTypeSpec, publicMethod.Type, null, null, false, func, + false, -1, func.HasThrows); + publicMethod.Body.AddRange(lines); + methods.Add(publicMethod); + } + + CSClass CompileTLProps(IEnumerable props, + ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, + string outputDirectory, ErrorHandling errors, + CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokes) + { + var properties = new List(); + + foreach (PropertyDeclaration prop in props) + { + if (prop.IsDeprecated || prop.IsUnavailable) + continue; + try + { + cl = cl ?? new CSClass(CSVisibility.Public, "TopLevelEntities"); + + // Calculated properties have a matching __method + string backingMethodName = ("__" + prop.Name); + CSMethod backingMethod = cl.Methods.FirstOrDefault(x => x.Name.Name == backingMethodName); + } + catch (Exception e) + { + errors.Add(e); + } + } + + if (properties.Count > 0) + { + cl.Properties.AddRange(properties); + } + return cl; + } + + string PIClassName(string fullClassName) + { + if (!fullClassName.Contains('.')) + throw new ArgumentOutOfRangeException(nameof(fullClassName), String.Format("Class name {0} should be a full class name.", fullClassName)); + fullClassName = fullClassName.Substring(fullClassName.IndexOf('.') + 1).Replace('.', '_'); + return "NativeMethodsFor" + fullClassName; + } + + string PIClassName(DotNetName fullClassName) + { + return PIClassName(fullClassName.Namespace + "." + fullClassName.TypeName); + } + + string PIClassName(SwiftClassName name) + { + return PIClassName(TypeMapper.GetDotNetNameForSwiftClassName(name)); + } + + string PIFuncName(SwiftName functionName) + { + return String.Format("PIfunc_{0}", functionName.Name); + } + + string PIFuncName(string functionName) + { + return $"PIfunc_{functionName}"; + } + + CSIdentifier GetMethodWrapperName(FunctionDeclaration func, CSMethod method, string homonymSuffix) + { + string prefix = func.IsProperty ? "__" : ""; + return new CSIdentifier(prefix + method.Name.Name + homonymSuffix); + } + + + CSVisibility GetMethodWrapperVisibility(FunctionDeclaration func, CSMethod method) + { + return func.IsProperty ? CSVisibility.Private : method.Visibility; + } + + static string PInvokeName(string libFullPath, string originalLibrary = null) + { + return LibOrFrameworkFromPath(libFullPath); + } + + static string LibOrFrameworkFromPath(string libFullPath) + { + string directory = Path.GetDirectoryName(libFullPath); + string file = Path.GetFileName(libFullPath); + return file; + } + + public static string Uniqueify(string name, IEnumerable names) + { + int thisTime = 0; + var sb = new StringBuilder(name); + while (names.Contains(sb.ToString())) + { + sb.Clear().Append(name).Append(thisTime++); + } + return sb.ToString(); + } + } } diff --git a/src/SwiftReflector/CSKeywords.cs b/src/SwiftReflector/CSKeywords.cs index 320fd467b1a7..1fb7dd374c4e 100644 --- a/src/SwiftReflector/CSKeywords.cs +++ b/src/SwiftReflector/CSKeywords.cs @@ -6,39 +6,42 @@ using System.Linq; using SwiftRuntimeLibrary; -namespace SwiftReflector { - public class CSKeywords { - static HashSet keyWords; - static string [] keyArr = new string [] { - "abstract", "as", "base", "bool", "break", "byte", - "case", "catch", "char", "checked", "class", "const", - "continue", "decimal", "default", "delegate", "do", - "double", "else", "enum", "event", "explicit", "extern", - "false", "finally", "fixed", "float", "for", "foreach", - "goto", "if", "implicit", "in", "int", "interface", "internal", - "is", "lock", "long", "namespace", "new", "null", "object", - "operator", "out", "override", "params", "private", "protected", - "public", "readonly", "ref", "return", "sbyte", "sealed", "short", - "sizeof", "stackalloc", "static", "string", "struct", "switch", - "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", - "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", - "add", "alias", "ascending", "async", "await", "descending", "dynamic", - "from", "get", "global", "group", "into", "join", "let", "orderby", - "partial", "remove", "select", "set", "value", "var", "where", "yield" - }; - static CSKeywords () - { - keyWords = new HashSet (); - foreach (string s in keyArr) { - keyWords.Add (s); - } - } +namespace SwiftReflector +{ + public class CSKeywords + { + static HashSet keyWords; + static string[] keyArr = new string[] { + "abstract", "as", "base", "bool", "break", "byte", + "case", "catch", "char", "checked", "class", "const", + "continue", "decimal", "default", "delegate", "do", + "double", "else", "enum", "event", "explicit", "extern", + "false", "finally", "fixed", "float", "for", "foreach", + "goto", "if", "implicit", "in", "int", "interface", "internal", + "is", "lock", "long", "namespace", "new", "null", "object", + "operator", "out", "override", "params", "private", "protected", + "public", "readonly", "ref", "return", "sbyte", "sealed", "short", + "sizeof", "stackalloc", "static", "string", "struct", "switch", + "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", + "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", + "add", "alias", "ascending", "async", "await", "descending", "dynamic", + "from", "get", "global", "group", "into", "join", "let", "orderby", + "partial", "remove", "select", "set", "value", "var", "where", "yield" + }; + static CSKeywords() + { + keyWords = new HashSet(); + foreach (string s in keyArr) + { + keyWords.Add(s); + } + } - public static bool IsKeyword (string s) - { - Exceptions.ThrowOnNull (s, "s"); - return keyWords.Contains (s); - } - } + public static bool IsKeyword(string s) + { + Exceptions.ThrowOnNull(s, "s"); + return keyWords.Contains(s); + } + } } diff --git a/src/SwiftReflector/Demangling/ContextAttribute.cs b/src/SwiftReflector/Demangling/ContextAttribute.cs index fd3154e615eb..1cda5d13a059 100644 --- a/src/SwiftReflector/Demangling/ContextAttribute.cs +++ b/src/SwiftReflector/Demangling/ContextAttribute.cs @@ -2,8 +2,10 @@ // Licensed under the MIT License. using System; -namespace SwiftReflector.Demangling { - [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] - public class ContextAttribute : Attribute { - } +namespace SwiftReflector.Demangling +{ + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + public class ContextAttribute : Attribute + { + } } diff --git a/src/SwiftReflector/Demangling/Decomposer.cs b/src/SwiftReflector/Demangling/Decomposer.cs index 6bf75b159253..8cbb9750c46b 100644 --- a/src/SwiftReflector/Demangling/Decomposer.cs +++ b/src/SwiftReflector/Demangling/Decomposer.cs @@ -7,1155 +7,1256 @@ using SwiftReflector.ExceptionTools; using System.Text; -namespace SwiftReflector.Demangling { - public class Decomposer { - const string kSwiftID = "__T"; - public const string kSwift4xID = "_$s"; - public const string kSwift5ID = "_$S"; - public static SwiftName kSwiftAllocatingConstructorName = new SwiftName (".ctor", false); - public static SwiftName kSwiftNonAllocatingConstructorName = new SwiftName (".nctor", false); - public static SwiftName kSwiftClassConstructorName = new SwiftName (".cctor", false); - public static SwiftName kSwiftDeallocatingDestructorName = new SwiftName (".dtor", false); - public static SwiftName kSwiftNonDeallocatingDestructorName = new SwiftName (".ndtor", false); - public static SwiftName kSwiftWitnessTableName = new SwiftName (".wtable", false); - public static SwiftName kSwiftValueWitnessTableName = new SwiftName (".vwtable", false); - public static SwiftName kSwiftProtocolWitnessTableName = new SwiftName (".pwtable", false); - public static SwiftName kSwiftProtocolWitnessTableAccessorName = new SwiftName (".pwtablea", false); - - List subs = new List (); - - List classes = new List (); - int position; - StringSlice slice; - string originalID; - SwiftName thisModule; - bool isOldVersion; - ulong offset; - - - Decomposer (string swiftIdentifier, bool isOldVersion, ulong offset) - { - if (swiftIdentifier == null) - throw new ArgumentNullException (nameof(swiftIdentifier)); - if (swiftIdentifier.Length == 0) - throw new ArgumentException ("swiftname is empty", nameof(swiftIdentifier)); - originalID = swiftIdentifier; - this.isOldVersion = isOldVersion; - this.offset = offset; - } - - int MarkOperatorPosition () - { - position = slice.Position; - return position; - } - - void Fail (string expected, string butGot = null) - { - if (butGot == null) { - butGot = slice.IsAtEnd ? "nothing at end of string" : slice.Current.ToString (); - } - var message = $"Error decomposing {slice.Original} at position {slice.Position}: expected {expected}, but got {butGot}"; - throw ErrorHelper.CreateError (ReflectorError.kDecomposeBase + 1, message); - } - - void Initialize () - { - thisModule = null; - classes.Clear (); - slice = new StringSlice (originalID); - MarkOperatorPosition (); - } - - public static TLDefinition Decompose (string swiftIdentifier, bool isOldVersion, ulong offset = 0) - { - if (swiftIdentifier.StartsWith (kSwift4xID, StringComparison.Ordinal)|| - swiftIdentifier.StartsWith (kSwift5ID, StringComparison.Ordinal)) { - var demangler5 = new Swift5Demangler (swiftIdentifier, offset); - return demangler5.Run (); - } else { - Decomposer decomp = new Decomposer (swiftIdentifier, isOldVersion, offset); - return decomp.Run (); - } - } - - public TLDefinition Run () - { - Initialize (); - - RemoveSwiftID (); - - char c = slice.Advance (); - switch (c) { - case 'Z': - if (slice.AdvanceIfEquals ('F')) { - return ToFunction (true, false); - } else if (slice.AdvanceIfEquals ('v')) { - return ToVariable (true); - } else { - Fail ("a static function (F)"); - } - break; - case 'F': - return ToFunction (false, false); - case 'M': - return ToMetadata (); - case 'W': - return ToWitnessTable (); - case 'v': - return ToVariable (false); - case 'T': - return ToThunk (); - case 'I': - return ToInitializer (); - default: - Fail ("one of Z, F, M, v, T, I or W", c.ToString ()); - break; - } - return null; - } - - void RemoveSwiftID () - { - if (!slice.StartsWith (kSwiftID)) - Fail ("Swift symbol (__T)", slice.Original.Substring (0, Math.Min (3, slice.Original.Length))); - slice.Advance (kSwiftID.Length); - } - - SwiftName GetModule () - { - return slice.ExtractSwiftName (); - } - - public static MemberNesting? ToMaybeMemberNesting (char c, bool throwOnFail) - { - switch (c) { - case 'C': - return MemberNesting.Class; - case 'V': - return MemberNesting.Struct; - case 'O': - return MemberNesting.Enum; - case 'P': - return MemberNesting.Protocol; - default: - if (throwOnFail) - throw new ArgumentOutOfRangeException (nameof(c)); - return null; - } - } - - MemberNesting ToMemberNesting (char c) - { - MemberNesting? nesting = ToMaybeMemberNesting (c, false); - if (!nesting.HasValue) { - Fail ("either a struct, class, enum, or protocol nesting marker (C, V, O, or P)"); - } - return nesting.Value; - } - - MemberType ToMemberType (char c) - { - switch (c) { - case 'C': - return MemberType.Allocator; - case 'c': - return MemberType.Constructor; - case 'D': - return MemberType.Deallocator; - case 'd': - return MemberType.Destructor; - case 'f': - return MemberType.UncurriedFunction; - case 'F': - return MemberType.Function; - case 'g': - return MemberType.Getter; - case 's': - return MemberType.Setter; - default: - Fail ("a member type marker (one of C, c, D, d, F, f, g, or s"); - return MemberType.Allocator; // never hit, thanks C#, you're the best - } - } - - CoreBuiltInType ToCoreScalar (char c) - { - switch (c) { - case 'b': - return CoreBuiltInType.Bool; - case 'd': - return CoreBuiltInType.Double; - case 'f': - return CoreBuiltInType.Float; - case 'i': - return CoreBuiltInType.Int; - case 'u': - return CoreBuiltInType.UInt; - default: - Fail ("a core type marker (one of b, d, f, i, or u)"); - return CoreBuiltInType.Bool; // never hit, thanks C#, you're the best - } - } - - IList GetNesting () - { - Stack st = new Stack (); - while (!Char.IsDigit (slice.Current)) { - MarkOperatorPosition (); - st.Push (ToMemberNesting (slice.Advance ())); - } - return st.ToList (); - } - - IList GetNestingAlt () - { - Stack st = new Stack (); - while (!slice.StartsWith ('S') && !slice.StartsWith ('s') && !Char.IsDigit (slice.Current)) { - MarkOperatorPosition (); - st.Push (ToMemberNesting (slice.Advance ())); - } - return st.ToList (); - } - - IList GetNestingNames (int expected) - { - List names = new List (expected); - for (int i = 0; i < expected; i++) { - MarkOperatorPosition (); - SwiftName sw = slice.ExtractSwiftName (); - if (sw == null) - Fail (String.Format ("{0} nested class names", expected)); - names.Add (sw); - } - return names; - } - - SwiftClassName ReadProtocolName () - { - MarkOperatorPosition (); - // module? - IList nesting = new List { MemberNesting.Protocol }; - - SwiftType st = ReadContext (); - SwiftClassType ct = st as SwiftClassType; - if (ct == null) { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail ("SwiftModuleNameType", st.GetType ().Name); - ct = new SwiftClassType (new SwiftClassName (mod.Name, new List (), new List ()), false, null); - } - - - IList nestingNames = GetNestingNames (nesting.Count); - return new SwiftClassName (ct.ClassName.Module, nesting, nestingNames); - } - - SwiftClassName CombineContextAndName (SwiftType context, SwiftName terminus, MemberNesting nesting, OperatorType oper) - { - if (context is SwiftModuleNameType) { - return new SwiftClassName (context.Name, new List { nesting }, - new List { terminus }); - } - if (context is SwiftClassType) { - SwiftClassType ct = context as SwiftClassType; - List newnesting = new List (); - newnesting.AddRange (ct.ClassName.Nesting); - newnesting.Add (nesting); - List newnames = new List (); - newnames.AddRange (ct.ClassName.NestingNames); - newnames.Add (terminus); - return new SwiftClassName (ct.ClassName.Module, newnesting, newnames, oper); - } - Fail ("a SwiftModuleNameType or a SwiftClassType", context.GetType ().Name); - return null; // never reached - thanks C# - } - - SwiftClassName ReadClassStructEnumNameAlt () - { - if (!slice.StartsWith ('C') && !slice.StartsWith ('V') && !slice.StartsWith ('O')) - Fail ("class, struct, or enum markers (C, V, or O)"); - MarkOperatorPosition (); - - MemberNesting nesting = ToMemberNesting (slice.Advance ()); - SwiftType context = ReadContext (); - OperatorType oper = OperatorType.None; - SwiftName name = slice.ExtractSwiftNameMaybeOperator (out oper); - SwiftClassName className = CombineContextAndName (context, name, nesting, oper); - return className; - } - - public SwiftClassType ReadClassStructOrEnum (SwiftName name, bool isReference) - { - if (!slice.StartsWith ('C') && !slice.StartsWith ('V') && !slice.StartsWith ('O')) - Fail ("class, struct, or enum markers (C, V, or O)"); - MarkOperatorPosition (); - SwiftClassName cn = ReadClassStructEnumNameAlt (); - SwiftClassType ct = new SwiftClassType (cn, isReference, name); - subs.Add (ct); - return ct; - } - - - SwiftType ReadContext () - { - if (slice.Current == 'S') { - return DemangleSubstitution (null, false); - } - if (slice.AdvanceIfEquals ('s')) { - return new SwiftModuleNameType (new SwiftName ("Swift", false), false); - } - if (slice.StartsWith ('C') || slice.StartsWith ('V') || slice.StartsWith ('O')) { - return ReadClassStructOrEnum (null, false); - } - SwiftName module = GetModule (); - SwiftModuleNameType modName = new SwiftModuleNameType (module, false); - subs.Add (modName); - return modName; - } - - - TLDefinition ToMetadata () - { - MarkOperatorPosition (); - // current version doesn't use 'd', but is implicit - - - char c = (slice.Current == 'C' || slice.Current == 'V' || slice.Current == 'O') ? 'd' : slice.Advance (); - SwiftClassName className = c != 'p' ? ReadClassStructEnumNameAlt () : ReadProtocolName (); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType (className, false); - subs.Add (cl); - - switch (c) { - case 'a': - return new TLFunction (slice.Original, thisModule, kSwiftClassConstructorName, cl, - new SwiftClassConstructorType (new SwiftMetaClassType (cl, false), false), offset); - case 'L': - return new TLLazyCacheVariable (slice.Original, thisModule, cl, offset); - case 'd': - return new TLDirectMetadata (slice.Original, thisModule, cl, offset); - case 'm': - return new TLMetaclass (slice.Original, thisModule, cl, offset); - case 'n': - return new TLNominalTypeDescriptor (slice.Original, thisModule, cl, offset); - case 'p': - return new TLProtocolTypeDescriptor (slice.Original, thisModule, cl, offset); - case 'P': - return new TLGenericMetadataPattern (slice.Original, thisModule, cl, offset); - default: - Fail ("a metaclass descriptor (a, L, d, m, or n, p)", c.ToString ()); - return null; - } - } - - TLVariable ToVariable (bool isStatic) - { - MarkOperatorPosition (); - SwiftType st = ReadContext (); - SwiftClassType cl = st as SwiftClassType; - if (cl == null) { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail ("a SwiftModuleType", st.GetType ().Name); - cl = new SwiftClassType (new SwiftClassName (mod.Name, new List (), - new List ()), false); - } - SwiftName module = cl.ClassName.Module; - if (cl.ClassName.Nesting.Count == 0) - cl = null; - SwiftName varName = slice.ExtractSwiftName (); - SwiftType ofType = ReadType (false); - return new TLVariable (slice.Original, module, cl, varName, ofType, isStatic, offset); - } - - TLThunk ToThunk () - { - MarkOperatorPosition (); - ThunkType thunkType = ToThunkType (); - SwiftClassName className = ReadClassStructEnumNameAlt (); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType (className, false); - return new TLThunk (thunkType, slice.Original, thisModule, cl, offset); - } - - ThunkType ToThunkType () - { - char c = slice.Advance (); - switch (c) { - case 'R': - return ThunkType.ReabstractionHelper; - case 'r': - return ThunkType.Reabstraction; - case 'W': - return ThunkType.ProtocolWitness; - default: - Fail ("a thunk type marker, one of R, r, or W", c.ToString ()); - return ThunkType.ProtocolWitness; // can't happen - } - } - - TLDefinition ToInitializer () - { - MarkOperatorPosition (); - if (slice.AdvanceIfEquals ('v')) { - return ToInitializer (InitializerType.Variable); - } else { - Fail ("expected a variable initializer marker (v)"); - return null; // stupid compile - } - } - - TLDefinition ToInitializer (InitializerType type) - { - SwiftType readType = ReadContext (); - SwiftClassType owner = readType as SwiftClassType; - if (owner == null) - Fail ("SwiftClassType", readType.GetType ().Name); - thisModule = owner.ClassName.Module; - - SwiftName varName = slice.ExtractSwiftName (); - SwiftType varType = ReadType (false); - return new TLFunction (slice.Original, thisModule, - varName, owner, - new SwiftInitializerType (InitializerType.Variable, varType, owner, varName), - offset); - } - - - TLDefinition ToWitnessTable () - { - MarkOperatorPosition (); - if (slice.StartsWith ('v')) - return ToFieldOffset (); - if (slice.StartsWith ('V')) - return ToValueWitnessTable (); - if (slice.StartsWith ('P')) - return ToProtocolWitnessTable (); - if (slice.StartsWith ('a')) - return ToProtocolWitnessTableAccessor (); - if (!slice.AdvanceIfEquals ('o')) - Fail ("expected witness table offset marker (o)"); - if (!slice.AdvanceIfEquals ('F')) - Fail ("expected a function marker (F) after witness table offset"); - - SwiftClassName className = ReadClassStructEnumNameAlt (); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType (className, false); - subs.Add (cl); - - MarkOperatorPosition (); - - // A witness table is not strictly a function, but the overall structure of its descriptor - // matches an uncurried function closely enough that we can make it pass for one. - // The consuming code doesn't care and pulls it out as is. - SwiftWitnessTableType wit = new SwiftWitnessTableType (WitnessType.Class); - - TLFunction func = new TLFunction (slice.Original, thisModule, null, cl, wit, offset); - return func; - } - - TLDefinition ToValueWitnessTable () - { - return ToWitnessFoo ('V', "value witness table", WitnessType.Value); - } - - TLDefinition ToProtocolWitnessTable () - { - return ToWitnessFoo ('P', "protocol witness table", WitnessType.Protocol); - } - - TLDefinition ToProtocolWitnessTableAccessor () - { - return ToWitnessFoo ('a', "protocol witness table accessor", WitnessType.ProtocolAccessor); - } - - TLDefinition ToWitnessFoo (char marker, string descriptor, WitnessType witnessType) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals (marker)) - Fail (String.Format ("{0} marker ({1})", descriptor, marker)); - - SwiftClassName className = ReadClassStructEnumNameAlt (); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType (className, false); - subs.Add (cl); - - - SwiftClassName protoName = witnessType == WitnessType.Protocol ? ReadProtocolName () : null; - SwiftClassType proto = protoName != null ? new SwiftClassType (protoName, false) : null; - - MarkOperatorPosition (); - // this is likely wrong, but it's less wrong than it was - SwiftWitnessTableType witf = new SwiftWitnessTableType (witnessType, proto); - TLFunction func = new TLFunction (slice.Original, thisModule, null, cl, witf, offset); - return func; - } - - TLDefinition ToFieldOffset () - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('v')) - Fail ("a field offset marker (v)"); - if (!(slice.StartsWith ('d') || slice.StartsWith ('i'))) - Fail ("a direct or indirect marker (d, i)"); - bool direct = slice.StartsWith ('d'); - slice.Advance (); - - slice.Advance (); - - SwiftClassType cl = ReadType (false) as SwiftClassType; - if (cl == null) - Fail ("a class descriptor"); - thisModule = cl.ClassName.Module; - - SwiftName ident = slice.ExtractSwiftName (); - SwiftType type = ReadType (false); - - return new TLFieldOffset (slice.Original, thisModule, cl, direct, ident, type, offset); - } - - - TLFunction ToFunction (bool isStatic, bool isReference) - { - MarkOperatorPosition (); - if (slice.StartsWith ('F')) { - return ReadExplicitClosure (isReference); - } - - SwiftType st = ReadContext (); - SwiftClassType cl = st as SwiftClassType; - if (cl == null) { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail ("a SwiftModuleType", st.GetType ().Name); - cl = new SwiftClassType (new SwiftClassName (mod.Name, new List (), - new List ()), false); - } - - MarkOperatorPosition (); - OperatorType oper = OperatorType.None; - SwiftName functionName = slice.ExtractSwiftNameMaybeOperator (out oper); - - - SwiftBaseFunctionType baseFunc = null; - - switch (slice.Current) { - case 'C': - baseFunc = ReadAllocatorType (isReference); - break; - case 'c': - baseFunc = ReadConstructorType (isReference); - break; - case 'D': - baseFunc = new SwiftDestructorType (true, cl, isReference, false); - break; - case 'd': - baseFunc = new SwiftDestructorType (false, cl, isReference, false); - break; - case 'g': - baseFunc = ReadGetter (cl, isStatic, isReference); - break; - case 's': - baseFunc = ReadSetter (cl, isStatic, isReference); - break; - case 'm': - baseFunc = ReadMaterializer (cl, isStatic, isReference); - break; - case 'a': - baseFunc = ReadAddressorMutable (cl, isReference); - break; - case 'l': - baseFunc = ReadAddressor (cl, isReference); - break; - default: - baseFunc = ReadType (isReference) as SwiftBaseFunctionType; - if (isStatic && baseFunc is SwiftUncurriedFunctionType) { - SwiftUncurriedFunctionType ucf = baseFunc as SwiftUncurriedFunctionType; - baseFunc = new SwiftStaticFunctionType (ucf.Parameters, ucf.ReturnType, ucf.IsReference, ucf.CanThrow, ucf.UncurriedParameter as SwiftClassType, ucf.Name); - } - break; - } - - - if (baseFunc == null) - Fail ("a function"); - - functionName = functionName ?? baseFunc.Name; - - if (functionName == null) - throw new ArgumentNullException ("blah"); - - return new TLFunction (slice.Original, cl.ClassName.Module, functionName, cl, baseFunc, offset, oper); - } - - SwiftType ReadType (bool isReference, SwiftName name = null) - { - name = slice.IsNameNext ? slice.ExtractSwiftName () : name; - char t = slice.Current; - MarkOperatorPosition (); - switch (t) { - case 'f': - return ReadUncurriedFunctionType (name, isReference, subs.Last () as SwiftClassType); - - case 'F': - return ReadFunctionType (name, isReference); - case 'c': - return ReadCFunctionType (name, isReference); - case 'G': - return ReadBoundGenericType (name, isReference); - case 'S': - return DemangleSubstitution (name, isReference); - case 'V': - case 'C': - case 'O': - return ReadClassOrStructOrEnum (name, isReference); - case 'P': - return ReadProtocolList (name, isReference); - case 'M': - return ReadMetaClassType (name, isReference); - case 'R': - slice.Advance (); - return ReadType (true, name); - case 'T': - return ReadTupleType (name, isReference); - case 'u': - return ReadUnboundGenericType (name, isReference); - case 'x': - slice.Advance (); - return new SwiftGenericArgReferenceType (0, 0, isReference, name); - case 'q': - return ReadGenericReferenceType (name, isReference); - default: - Fail ("a type marker (one of F, G, S, V, C, O, M, R, T, u, x, or q)"); - return null; - } - } - - TLFunction ReadExplicitClosure (bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('F')) - Fail ("an explicit closure marker (F)"); - - SwiftClassType st = ReadType (isReference) as SwiftClassType; - if (st == null) - Fail ("a class type"); - return new TLFunction (slice.Original, st.ClassName.Module, st.Name, st, new SwiftExplicitClosureType (isReference), offset); - } - - SwiftUncurriedFunctionType ReadUncurriedFunctionType (SwiftName name, bool isReference, SwiftType implicitType) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('f')) - Fail ("an uncurried function type (f)"); - bool canThrow = slice.AdvanceIfEquals ('z'); - if (isOldVersion) { - SwiftType uncurriedParamType = ReadType (false); - SwiftFunctionType func = ReadFunctionType (null, false); - return new SwiftUncurriedFunctionType (uncurriedParamType, func.Parameters, func.ReturnType, isReference, canThrow, name); - } else { - SwiftType args = ReadType (false); - SwiftType ret = ReadType (false); - return new SwiftUncurriedFunctionType (implicitType, args, ret, isReference, canThrow, name); - } - } - - SwiftConstructorType ReadAllocOrCons (bool isAllocator, char advanceOn, string expected, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals (advanceOn)) - Fail (expected); - SwiftUncurriedFunctionType ucf = ReadUncurriedFunctionType (null, false, new SwiftMetaClassType (subs.Last () as SwiftClassType, false, null)); - return new SwiftConstructorType (isAllocator, ucf.UncurriedParameter, ucf.Parameters, ucf.ReturnType, isReference, ucf.CanThrow); - } - - SwiftAddressorType ReadAddressorMutable (SwiftClassType cl, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('a')) - Fail ("an addressor"); - AddressorType theType = AddressorType.UnsafeMutable; - char c = slice.Advance (); - switch (c) { - case 'O': - theType = AddressorType.OwningMutable; - break; - case 'o': - theType = AddressorType.NativeOwningMutable; - break; - case 'p': - theType = AddressorType.NativePinningMutable; - break; - case 'u': - theType = AddressorType.UnsafeMutable; - break; - default: - Fail ("one of O, o, p, or u", c.ToString ()); - break; - } - if (!slice.IsNameNext) - Fail ("a swift name"); - SwiftName addressorName = slice.ExtractSwiftName (); - SwiftType ofType = ReadType (true); // addressors return the address of the entity - return new SwiftAddressorType (theType, ofType, isReference, addressorName); - } - - SwiftAddressorType ReadAddressor (SwiftClassType cl, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('l')) - Fail ("an addressor"); - AddressorType theType = AddressorType.UnsafeMutable; - char c = slice.Advance (); - switch (c) { - case 'O': - theType = AddressorType.Owning; - break; - case 'o': - theType = AddressorType.NativeOwning; - break; - case 'p': - theType = AddressorType.NativePinning; - break; - case 'u': - theType = AddressorType.Unsafe; - break; - default: - Fail ("one of O, o, p, or u", c.ToString ()); - break; - } - if (!slice.IsNameNext) - Fail ("a swift name"); - SwiftName addressorName = slice.ExtractSwiftName (); - SwiftType ofType = ReadType (true); // addressors return the address of the entity - return new SwiftAddressorType (theType, ofType, isReference, addressorName); - } - - SwiftPropertyType ReadGetter (SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('g')) - Fail ("a property getter (g)"); - return ReadProperty (cl, PropertyType.Getter, isStatic, isReference); - } - - SwiftPropertyType ReadSetter (SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('s')) - Fail ("a property setter"); - return ReadProperty (cl, PropertyType.Setter, isStatic, isReference); - } - - SwiftPropertyType ReadMaterializer (SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('m')) - Fail ("a property materializer"); - return ReadProperty (cl, PropertyType.Materializer, isStatic, isReference); - } - - SwiftPropertyType ReadProperty (SwiftClassType cl, PropertyType propType, bool isStatic, bool isReference) - { - SwiftName privateName = null; - MarkOperatorPosition (); - if (slice.AdvanceIfEquals ('P')) - privateName = slice.ExtractSwiftName (); - MarkOperatorPosition (); - if (!slice.IsNameNext) - Fail ("a swift name"); - SwiftName propName = slice.ExtractSwiftName (); - - if (IsSubscript (propName)) { - SwiftType subscriptType = ReadType (false); - SwiftBaseFunctionType subscriptFunc = subscriptType as SwiftBaseFunctionType; - if (subscriptFunc == null) - Fail ("a function type in an indexed property", subscriptType.GetType ().Name); - - if (propType == PropertyType.Setter && subscriptFunc.ReturnType != null && !subscriptFunc.ReturnType.IsEmptyTuple) { - // oh hooray! - // If I define an indexer in swift like this: - // public subscript(T index) -> U { - // get { return getSomeUValue(index); } - // set (someUValue) { setSomeUValue(index, someUValue); } - // } - // This signature of the function attached to both properties is: - // T -> U - // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but - // the setter is (T, U) -> void - // - // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect - // what's really happening. - - // need to change this so that the tail parameters get names? Maybe just the head? - - SwiftTupleType newParameters = subscriptFunc.ParameterCount == 1 ? - new SwiftTupleType (false, null, subscriptFunc.ReturnType, - subscriptFunc.Parameters.RenamedCloneOf (new SwiftName (subscriptFunc.ReturnType.Name == null || - subscriptFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) - : new SwiftTupleType (Enumerable.Concat (subscriptFunc.ReturnType.Yield (), subscriptFunc.EachParameter), - false, null); - subscriptFunc = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, subscriptFunc.CanThrow, subscriptFunc.Name); - } - return new SwiftPropertyType (cl, propType, propName, privateName, (SwiftFunctionType)subscriptFunc, isStatic, isReference); - - } else { - SwiftType ofType = ReadType (false); - - return new SwiftPropertyType (cl, propType, propName, privateName, ofType, isStatic, isReference); - } - } - - public static bool IsSubscript (SwiftName name) - { - return name.Name == "subscript"; - } - - SwiftConstructorType ReadAllocatorType (bool isReference) - { - return ReadAllocOrCons (true, 'C', "an allocating constructor (C)", isReference); - } - - SwiftConstructorType ReadConstructorType (bool isReference) - { - return ReadAllocOrCons (false, 'c', "a non-allocating constructor (c)", isReference); - } - - SwiftType ReadProtocolList (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('P')) - Fail ("A protocol list marker ('P')"); - if (slice.Current == 'M') { - return ReadExistentialMetatype (name, isReference); - } - List protocols = new List (); - while (slice.Current != '_') { - SwiftClassName className = ReadProtocolName (); - SwiftClassType theProtocol = new SwiftClassType (className, false, null); - subs.Add (theProtocol); - protocols.Add (theProtocol); - } - slice.Advance (); - return new SwiftProtocolListType (protocols, isReference, name); - } - - SwiftClassType ReadClassOrStructOrEnum (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - SwiftClassName className = ReadClassStructEnumNameAlt (); - SwiftClassType clType = new SwiftClassType (className, isReference, name); - subs.Add (clType); - return clType; - } - - SwiftMetaClassType ReadMetaClassType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('M')) - Fail ("a metaclass marker (M)"); - SwiftClassType cl = ReadType (false) as SwiftClassType; - if (cl == null) - Fail ("a class type"); - return new SwiftMetaClassType (cl, isReference, name); - } - - SwiftExistentialMetaType ReadExistentialMetatype (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('M')) - Fail ("a metaclass marker (M)"); - SwiftProtocolListType pl = ReadType (false) as SwiftProtocolListType; - if (pl == null) - Fail ("a protocol list type"); - return new SwiftExistentialMetaType (pl, isReference, name); - } - - - SwiftType ReadUnboundGenericType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('u')) - Fail ("an unbound generic type (u)"); - MarkOperatorPosition (); - List parms = ReadGenericArguments (); - SwiftType dependentType = ReadType (isReference, name); - SwiftBaseFunctionType bft = dependentType as SwiftBaseFunctionType; - if (bft != null) { - bft.GenericArguments.AddRange (parms); - return bft; - } - return new SwiftUnboundGenericType (dependentType, parms, isReference, dependentType.Name); - } - - - List ReadGenericArguments () - { - int count = 0; - while (slice.Current != 'R' && slice.Current != 'r') { - count = DemangleIndex (); - } - count += 1; - List args = new List (count); - for (int i = 0; i < count; i++) { - args.Add (new GenericArgument (0, i)); - } - if (slice.AdvanceIfEquals ('r')) - return args; - if (!slice.AdvanceIfEquals ('R')) - Fail ("A generic argument requirements marker (R)"); - while (!slice.AdvanceIfEquals ('r')) { - int depth = 0; - int index = 0; - if (slice.AdvanceIfEquals ('d')) { - depth = DemangleIndex (); - index = DemangleIndex (); - } else if (slice.AdvanceIfEquals ('x')) { - // no change - } else { - index = DemangleIndex () + 1; - } - if (slice.StartsWith ('C')) { - SwiftType constraintType = ReadType (false, null); - args [index].Constraints.Add (constraintType); - } else { - SwiftClassName className = ReadProtocolName (); - SwiftClassType theProtocol = new SwiftClassType (className, false, null); - args [index].Constraints.Add (theProtocol); - } - args [index].Depth = depth; - } - // currently swift name mangling is done incorrectly to get the actual - // depth. In the case where there is a 'where' clause, we can figure it out - // and correct it. - int maxDepth = 0; - foreach (GenericArgument gen in args) { - maxDepth = Math.Max (maxDepth, gen.Depth); - } - foreach (GenericArgument gen in args) { - gen.Depth = maxDepth; - } - return args; - } - - SwiftGenericArgReferenceType ReadGenericReferenceType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('q')) - Fail ("a generic argument reference"); - MarkOperatorPosition (); - int depth = 0; - int index = 0; - if (slice.AdvanceIfEquals ('d')) { - depth = DemangleIndex () + 1; - index = DemangleIndex () + 1; - } else { - index = DemangleIndex () + 1; - } - return new SwiftGenericArgReferenceType (depth, index, isReference, name); - } - - SwiftBoundGenericType ReadBoundGenericType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('G')) - Fail ("a bound generic type (G)"); - MarkOperatorPosition (); - SwiftType baseType = ReadType (false); - - List generics = new List (); - while (!slice.AdvanceIfEquals ('_')) { - MarkOperatorPosition (); - SwiftType t = ReadType (false); - if (t != null) - generics.Add (t); - } - return new SwiftBoundGenericType (baseType, generics, isReference, name); - } - - SwiftArrayType ReadArrayType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('S') || !slice.AdvanceIfEquals ('a')) - Fail ("an Array type (Sa)"); - return new SwiftArrayType (isReference, name); - } - - SwiftFunctionType ReadFunctionType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('F')) - Fail ("a function marker (F)"); - bool canThrow = slice.AdvanceIfEquals ('z'); - SwiftType parms = ReadType (false); - SwiftType ret = ReadType (false); - return new SwiftFunctionType (parms, ret, isReference, canThrow, name); - } - - SwiftCFunctionType ReadCFunctionType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('c')) - Fail ("a C function marker (c)"); - SwiftType parms = ReadType (false); - SwiftType ret = ReadType (false); - return new SwiftCFunctionType (parms, ret, isReference, name); - } - - SwiftType ReadScalarType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('S')) - Fail ("a core built in type marker (S)"); - if (slice.Current == 'S') { - slice.Advance (); - return ClassForBuiltInType (name, "String", MemberNesting.Struct, isReference); - } else if (slice.Current == 'q') { - slice.Advance (); - return ClassForBuiltInType (name, "Optional", MemberNesting.Enum, isReference); - } else if (slice.Current == 'Q') { - slice.Advance (); - return ClassForBuiltInType (name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); - } else if (slice.Current == 'P') { - slice.Advance (); - return ClassForBuiltInType (name, "UnsafePointer", MemberNesting.Struct, isReference); - } else if (slice.Current == 'p') { - slice.Advance (); - return ClassForBuiltInType (name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); - } else if (slice.Current == 'R') { - slice.Advance (); - return ClassForBuiltInType (name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); - } else if (slice.Current == 'r') { - slice.Advance (); - return ClassForBuiltInType (name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); - } else { - CoreBuiltInType scalarType = ToCoreScalar (slice.Advance ()); - return new SwiftBuiltInType (scalarType, isReference, name); - } - } - - SwiftTupleType ReadTupleType (SwiftName name, bool isReference) - { - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('T')) - Fail ("a tuple marker (T)"); - - List contents = new List (); - while (!slice.AdvanceIfEquals ('_')) { - MarkOperatorPosition (); - SwiftType ty = ReadType (false); - contents.Add (ty); - } - return new SwiftTupleType (contents, isReference, name); - } - - static SwiftClassType ClassForBuiltInType (SwiftName name, string className, MemberNesting nesting, bool isReference) - { - return new SwiftClassType (new SwiftClassName (new SwiftName ("Swift", false), - new List { nesting }, - new List { new SwiftName (className, false) }), isReference, name); - } - - SwiftType DemangleSubstitution (SwiftName name, bool isReference) - { - if (!slice.AdvanceIfEquals ('S')) - Fail ("a core built in type marker (S)"); - if (slice.AdvanceIfEquals ('a')) { - return ClassForBuiltInType (name, "Array", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('c')) { - return ClassForBuiltInType (name, "UnicodeScalar", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('S')) { - return ClassForBuiltInType (name, "String", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('q')) { - return ClassForBuiltInType (name, "Optional", MemberNesting.Enum, isReference); - } - if (slice.AdvanceIfEquals ('Q')) { - return ClassForBuiltInType (name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('P')) { - return ClassForBuiltInType (name, "UnsafePointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('p')) { - return ClassForBuiltInType (name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('R')) { - return ClassForBuiltInType (name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('r')) { - return ClassForBuiltInType (name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('V')) { - return ClassForBuiltInType (name, "UnsafeRawPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('v')) { - return ClassForBuiltInType (name, "UnsafeMutableRawPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals ('b')) { - return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); - } - if (slice.AdvanceIfEquals ('d')) { - return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); - } - if (slice.AdvanceIfEquals ('f')) { - return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); - } - if (slice.AdvanceIfEquals ('i')) { - return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); - } - if (slice.AdvanceIfEquals ('u')) { - return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); - } - if (slice.AdvanceIfEquals ('s')) { - return new SwiftModuleNameType (new SwiftName ("Swift", false), isReference); - } - int index = DemangleIndex (); - SwiftType st = subs [index]; - SwiftClassType sct = st as SwiftClassType; - if (sct == null) { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail ("a SwiftModuleNameType", st.GetType ().Name); - return mod; - } - return new SwiftClassType (sct.ClassName, isReference, name); - } - - int DemangleIndex () - { - if (slice.AdvanceIfEquals ('_')) { - return 0; - } - MarkOperatorPosition (); - if (!Char.IsDigit (slice.Current)) - Fail ("a number", slice.Current.ToString ()); - int index = ReadNumber (); - MarkOperatorPosition (); - if (!slice.AdvanceIfEquals ('_')) - Fail ("a macro terminator '-'", slice.Current.ToString ()); - return index + 1; - } - - int ReadNumber () - { - int number = 0; - while (Char.IsDigit (slice.Current)) { - number = 10 * number + slice.Current - '0'; - slice.Advance (); - } - return number; - } - } +namespace SwiftReflector.Demangling +{ + public class Decomposer + { + const string kSwiftID = "__T"; + public const string kSwift4xID = "_$s"; + public const string kSwift5ID = "_$S"; + public static SwiftName kSwiftAllocatingConstructorName = new SwiftName(".ctor", false); + public static SwiftName kSwiftNonAllocatingConstructorName = new SwiftName(".nctor", false); + public static SwiftName kSwiftClassConstructorName = new SwiftName(".cctor", false); + public static SwiftName kSwiftDeallocatingDestructorName = new SwiftName(".dtor", false); + public static SwiftName kSwiftNonDeallocatingDestructorName = new SwiftName(".ndtor", false); + public static SwiftName kSwiftWitnessTableName = new SwiftName(".wtable", false); + public static SwiftName kSwiftValueWitnessTableName = new SwiftName(".vwtable", false); + public static SwiftName kSwiftProtocolWitnessTableName = new SwiftName(".pwtable", false); + public static SwiftName kSwiftProtocolWitnessTableAccessorName = new SwiftName(".pwtablea", false); + + List subs = new List(); + + List classes = new List(); + int position; + StringSlice slice; + string originalID; + SwiftName thisModule; + bool isOldVersion; + ulong offset; + + + Decomposer(string swiftIdentifier, bool isOldVersion, ulong offset) + { + if (swiftIdentifier == null) + throw new ArgumentNullException(nameof(swiftIdentifier)); + if (swiftIdentifier.Length == 0) + throw new ArgumentException("swiftname is empty", nameof(swiftIdentifier)); + originalID = swiftIdentifier; + this.isOldVersion = isOldVersion; + this.offset = offset; + } + + int MarkOperatorPosition() + { + position = slice.Position; + return position; + } + + void Fail(string expected, string butGot = null) + { + if (butGot == null) + { + butGot = slice.IsAtEnd ? "nothing at end of string" : slice.Current.ToString(); + } + var message = $"Error decomposing {slice.Original} at position {slice.Position}: expected {expected}, but got {butGot}"; + throw ErrorHelper.CreateError(ReflectorError.kDecomposeBase + 1, message); + } + + void Initialize() + { + thisModule = null; + classes.Clear(); + slice = new StringSlice(originalID); + MarkOperatorPosition(); + } + + public static TLDefinition Decompose(string swiftIdentifier, bool isOldVersion, ulong offset = 0) + { + if (swiftIdentifier.StartsWith(kSwift4xID, StringComparison.Ordinal) || + swiftIdentifier.StartsWith(kSwift5ID, StringComparison.Ordinal)) + { + var demangler5 = new Swift5Demangler(swiftIdentifier, offset); + return demangler5.Run(); + } + else + { + Decomposer decomp = new Decomposer(swiftIdentifier, isOldVersion, offset); + return decomp.Run(); + } + } + + public TLDefinition Run() + { + Initialize(); + + RemoveSwiftID(); + + char c = slice.Advance(); + switch (c) + { + case 'Z': + if (slice.AdvanceIfEquals('F')) + { + return ToFunction(true, false); + } + else if (slice.AdvanceIfEquals('v')) + { + return ToVariable(true); + } + else + { + Fail("a static function (F)"); + } + break; + case 'F': + return ToFunction(false, false); + case 'M': + return ToMetadata(); + case 'W': + return ToWitnessTable(); + case 'v': + return ToVariable(false); + case 'T': + return ToThunk(); + case 'I': + return ToInitializer(); + default: + Fail("one of Z, F, M, v, T, I or W", c.ToString()); + break; + } + return null; + } + + void RemoveSwiftID() + { + if (!slice.StartsWith(kSwiftID)) + Fail("Swift symbol (__T)", slice.Original.Substring(0, Math.Min(3, slice.Original.Length))); + slice.Advance(kSwiftID.Length); + } + + SwiftName GetModule() + { + return slice.ExtractSwiftName(); + } + + public static MemberNesting? ToMaybeMemberNesting(char c, bool throwOnFail) + { + switch (c) + { + case 'C': + return MemberNesting.Class; + case 'V': + return MemberNesting.Struct; + case 'O': + return MemberNesting.Enum; + case 'P': + return MemberNesting.Protocol; + default: + if (throwOnFail) + throw new ArgumentOutOfRangeException(nameof(c)); + return null; + } + } + + MemberNesting ToMemberNesting(char c) + { + MemberNesting? nesting = ToMaybeMemberNesting(c, false); + if (!nesting.HasValue) + { + Fail("either a struct, class, enum, or protocol nesting marker (C, V, O, or P)"); + } + return nesting.Value; + } + + MemberType ToMemberType(char c) + { + switch (c) + { + case 'C': + return MemberType.Allocator; + case 'c': + return MemberType.Constructor; + case 'D': + return MemberType.Deallocator; + case 'd': + return MemberType.Destructor; + case 'f': + return MemberType.UncurriedFunction; + case 'F': + return MemberType.Function; + case 'g': + return MemberType.Getter; + case 's': + return MemberType.Setter; + default: + Fail("a member type marker (one of C, c, D, d, F, f, g, or s"); + return MemberType.Allocator; // never hit, thanks C#, you're the best + } + } + + CoreBuiltInType ToCoreScalar(char c) + { + switch (c) + { + case 'b': + return CoreBuiltInType.Bool; + case 'd': + return CoreBuiltInType.Double; + case 'f': + return CoreBuiltInType.Float; + case 'i': + return CoreBuiltInType.Int; + case 'u': + return CoreBuiltInType.UInt; + default: + Fail("a core type marker (one of b, d, f, i, or u)"); + return CoreBuiltInType.Bool; // never hit, thanks C#, you're the best + } + } + + IList GetNesting() + { + Stack st = new Stack(); + while (!Char.IsDigit(slice.Current)) + { + MarkOperatorPosition(); + st.Push(ToMemberNesting(slice.Advance())); + } + return st.ToList(); + } + + IList GetNestingAlt() + { + Stack st = new Stack(); + while (!slice.StartsWith('S') && !slice.StartsWith('s') && !Char.IsDigit(slice.Current)) + { + MarkOperatorPosition(); + st.Push(ToMemberNesting(slice.Advance())); + } + return st.ToList(); + } + + IList GetNestingNames(int expected) + { + List names = new List(expected); + for (int i = 0; i < expected; i++) + { + MarkOperatorPosition(); + SwiftName sw = slice.ExtractSwiftName(); + if (sw == null) + Fail(String.Format("{0} nested class names", expected)); + names.Add(sw); + } + return names; + } + + SwiftClassName ReadProtocolName() + { + MarkOperatorPosition(); + // module? + IList nesting = new List { MemberNesting.Protocol }; + + SwiftType st = ReadContext(); + SwiftClassType ct = st as SwiftClassType; + if (ct == null) + { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail("SwiftModuleNameType", st.GetType().Name); + ct = new SwiftClassType(new SwiftClassName(mod.Name, new List(), new List()), false, null); + } + + + IList nestingNames = GetNestingNames(nesting.Count); + return new SwiftClassName(ct.ClassName.Module, nesting, nestingNames); + } + + SwiftClassName CombineContextAndName(SwiftType context, SwiftName terminus, MemberNesting nesting, OperatorType oper) + { + if (context is SwiftModuleNameType) + { + return new SwiftClassName(context.Name, new List { nesting }, + new List { terminus }); + } + if (context is SwiftClassType) + { + SwiftClassType ct = context as SwiftClassType; + List newnesting = new List(); + newnesting.AddRange(ct.ClassName.Nesting); + newnesting.Add(nesting); + List newnames = new List(); + newnames.AddRange(ct.ClassName.NestingNames); + newnames.Add(terminus); + return new SwiftClassName(ct.ClassName.Module, newnesting, newnames, oper); + } + Fail("a SwiftModuleNameType or a SwiftClassType", context.GetType().Name); + return null; // never reached - thanks C# + } + + SwiftClassName ReadClassStructEnumNameAlt() + { + if (!slice.StartsWith('C') && !slice.StartsWith('V') && !slice.StartsWith('O')) + Fail("class, struct, or enum markers (C, V, or O)"); + MarkOperatorPosition(); + + MemberNesting nesting = ToMemberNesting(slice.Advance()); + SwiftType context = ReadContext(); + OperatorType oper = OperatorType.None; + SwiftName name = slice.ExtractSwiftNameMaybeOperator(out oper); + SwiftClassName className = CombineContextAndName(context, name, nesting, oper); + return className; + } + + public SwiftClassType ReadClassStructOrEnum(SwiftName name, bool isReference) + { + if (!slice.StartsWith('C') && !slice.StartsWith('V') && !slice.StartsWith('O')) + Fail("class, struct, or enum markers (C, V, or O)"); + MarkOperatorPosition(); + SwiftClassName cn = ReadClassStructEnumNameAlt(); + SwiftClassType ct = new SwiftClassType(cn, isReference, name); + subs.Add(ct); + return ct; + } + + + SwiftType ReadContext() + { + if (slice.Current == 'S') + { + return DemangleSubstitution(null, false); + } + if (slice.AdvanceIfEquals('s')) + { + return new SwiftModuleNameType(new SwiftName("Swift", false), false); + } + if (slice.StartsWith('C') || slice.StartsWith('V') || slice.StartsWith('O')) + { + return ReadClassStructOrEnum(null, false); + } + SwiftName module = GetModule(); + SwiftModuleNameType modName = new SwiftModuleNameType(module, false); + subs.Add(modName); + return modName; + } + + + TLDefinition ToMetadata() + { + MarkOperatorPosition(); + // current version doesn't use 'd', but is implicit + + + char c = (slice.Current == 'C' || slice.Current == 'V' || slice.Current == 'O') ? 'd' : slice.Advance(); + SwiftClassName className = c != 'p' ? ReadClassStructEnumNameAlt() : ReadProtocolName(); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType(className, false); + subs.Add(cl); + + switch (c) + { + case 'a': + return new TLFunction(slice.Original, thisModule, kSwiftClassConstructorName, cl, + new SwiftClassConstructorType(new SwiftMetaClassType(cl, false), false), offset); + case 'L': + return new TLLazyCacheVariable(slice.Original, thisModule, cl, offset); + case 'd': + return new TLDirectMetadata(slice.Original, thisModule, cl, offset); + case 'm': + return new TLMetaclass(slice.Original, thisModule, cl, offset); + case 'n': + return new TLNominalTypeDescriptor(slice.Original, thisModule, cl, offset); + case 'p': + return new TLProtocolTypeDescriptor(slice.Original, thisModule, cl, offset); + case 'P': + return new TLGenericMetadataPattern(slice.Original, thisModule, cl, offset); + default: + Fail("a metaclass descriptor (a, L, d, m, or n, p)", c.ToString()); + return null; + } + } + + TLVariable ToVariable(bool isStatic) + { + MarkOperatorPosition(); + SwiftType st = ReadContext(); + SwiftClassType cl = st as SwiftClassType; + if (cl == null) + { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail("a SwiftModuleType", st.GetType().Name); + cl = new SwiftClassType(new SwiftClassName(mod.Name, new List(), + new List()), false); + } + SwiftName module = cl.ClassName.Module; + if (cl.ClassName.Nesting.Count == 0) + cl = null; + SwiftName varName = slice.ExtractSwiftName(); + SwiftType ofType = ReadType(false); + return new TLVariable(slice.Original, module, cl, varName, ofType, isStatic, offset); + } + + TLThunk ToThunk() + { + MarkOperatorPosition(); + ThunkType thunkType = ToThunkType(); + SwiftClassName className = ReadClassStructEnumNameAlt(); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType(className, false); + return new TLThunk(thunkType, slice.Original, thisModule, cl, offset); + } + + ThunkType ToThunkType() + { + char c = slice.Advance(); + switch (c) + { + case 'R': + return ThunkType.ReabstractionHelper; + case 'r': + return ThunkType.Reabstraction; + case 'W': + return ThunkType.ProtocolWitness; + default: + Fail("a thunk type marker, one of R, r, or W", c.ToString()); + return ThunkType.ProtocolWitness; // can't happen + } + } + + TLDefinition ToInitializer() + { + MarkOperatorPosition(); + if (slice.AdvanceIfEquals('v')) + { + return ToInitializer(InitializerType.Variable); + } + else + { + Fail("expected a variable initializer marker (v)"); + return null; // stupid compile + } + } + + TLDefinition ToInitializer(InitializerType type) + { + SwiftType readType = ReadContext(); + SwiftClassType owner = readType as SwiftClassType; + if (owner == null) + Fail("SwiftClassType", readType.GetType().Name); + thisModule = owner.ClassName.Module; + + SwiftName varName = slice.ExtractSwiftName(); + SwiftType varType = ReadType(false); + return new TLFunction(slice.Original, thisModule, + varName, owner, + new SwiftInitializerType(InitializerType.Variable, varType, owner, varName), + offset); + } + + + TLDefinition ToWitnessTable() + { + MarkOperatorPosition(); + if (slice.StartsWith('v')) + return ToFieldOffset(); + if (slice.StartsWith('V')) + return ToValueWitnessTable(); + if (slice.StartsWith('P')) + return ToProtocolWitnessTable(); + if (slice.StartsWith('a')) + return ToProtocolWitnessTableAccessor(); + if (!slice.AdvanceIfEquals('o')) + Fail("expected witness table offset marker (o)"); + if (!slice.AdvanceIfEquals('F')) + Fail("expected a function marker (F) after witness table offset"); + + SwiftClassName className = ReadClassStructEnumNameAlt(); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType(className, false); + subs.Add(cl); + + MarkOperatorPosition(); + + // A witness table is not strictly a function, but the overall structure of its descriptor + // matches an uncurried function closely enough that we can make it pass for one. + // The consuming code doesn't care and pulls it out as is. + SwiftWitnessTableType wit = new SwiftWitnessTableType(WitnessType.Class); + + TLFunction func = new TLFunction(slice.Original, thisModule, null, cl, wit, offset); + return func; + } + + TLDefinition ToValueWitnessTable() + { + return ToWitnessFoo('V', "value witness table", WitnessType.Value); + } + + TLDefinition ToProtocolWitnessTable() + { + return ToWitnessFoo('P', "protocol witness table", WitnessType.Protocol); + } + + TLDefinition ToProtocolWitnessTableAccessor() + { + return ToWitnessFoo('a', "protocol witness table accessor", WitnessType.ProtocolAccessor); + } + + TLDefinition ToWitnessFoo(char marker, string descriptor, WitnessType witnessType) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals(marker)) + Fail(String.Format("{0} marker ({1})", descriptor, marker)); + + SwiftClassName className = ReadClassStructEnumNameAlt(); + if (className.Module != null && thisModule == null) + thisModule = className.Module; + + SwiftClassType cl = new SwiftClassType(className, false); + subs.Add(cl); + + + SwiftClassName protoName = witnessType == WitnessType.Protocol ? ReadProtocolName() : null; + SwiftClassType proto = protoName != null ? new SwiftClassType(protoName, false) : null; + + MarkOperatorPosition(); + // this is likely wrong, but it's less wrong than it was + SwiftWitnessTableType witf = new SwiftWitnessTableType(witnessType, proto); + TLFunction func = new TLFunction(slice.Original, thisModule, null, cl, witf, offset); + return func; + } + + TLDefinition ToFieldOffset() + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('v')) + Fail("a field offset marker (v)"); + if (!(slice.StartsWith('d') || slice.StartsWith('i'))) + Fail("a direct or indirect marker (d, i)"); + bool direct = slice.StartsWith('d'); + slice.Advance(); + + slice.Advance(); + + SwiftClassType cl = ReadType(false) as SwiftClassType; + if (cl == null) + Fail("a class descriptor"); + thisModule = cl.ClassName.Module; + + SwiftName ident = slice.ExtractSwiftName(); + SwiftType type = ReadType(false); + + return new TLFieldOffset(slice.Original, thisModule, cl, direct, ident, type, offset); + } + + + TLFunction ToFunction(bool isStatic, bool isReference) + { + MarkOperatorPosition(); + if (slice.StartsWith('F')) + { + return ReadExplicitClosure(isReference); + } + + SwiftType st = ReadContext(); + SwiftClassType cl = st as SwiftClassType; + if (cl == null) + { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail("a SwiftModuleType", st.GetType().Name); + cl = new SwiftClassType(new SwiftClassName(mod.Name, new List(), + new List()), false); + } + + MarkOperatorPosition(); + OperatorType oper = OperatorType.None; + SwiftName functionName = slice.ExtractSwiftNameMaybeOperator(out oper); + + + SwiftBaseFunctionType baseFunc = null; + + switch (slice.Current) + { + case 'C': + baseFunc = ReadAllocatorType(isReference); + break; + case 'c': + baseFunc = ReadConstructorType(isReference); + break; + case 'D': + baseFunc = new SwiftDestructorType(true, cl, isReference, false); + break; + case 'd': + baseFunc = new SwiftDestructorType(false, cl, isReference, false); + break; + case 'g': + baseFunc = ReadGetter(cl, isStatic, isReference); + break; + case 's': + baseFunc = ReadSetter(cl, isStatic, isReference); + break; + case 'm': + baseFunc = ReadMaterializer(cl, isStatic, isReference); + break; + case 'a': + baseFunc = ReadAddressorMutable(cl, isReference); + break; + case 'l': + baseFunc = ReadAddressor(cl, isReference); + break; + default: + baseFunc = ReadType(isReference) as SwiftBaseFunctionType; + if (isStatic && baseFunc is SwiftUncurriedFunctionType) + { + SwiftUncurriedFunctionType ucf = baseFunc as SwiftUncurriedFunctionType; + baseFunc = new SwiftStaticFunctionType(ucf.Parameters, ucf.ReturnType, ucf.IsReference, ucf.CanThrow, ucf.UncurriedParameter as SwiftClassType, ucf.Name); + } + break; + } + + + if (baseFunc == null) + Fail("a function"); + + functionName = functionName ?? baseFunc.Name; + + if (functionName == null) + throw new ArgumentNullException("blah"); + + return new TLFunction(slice.Original, cl.ClassName.Module, functionName, cl, baseFunc, offset, oper); + } + + SwiftType ReadType(bool isReference, SwiftName name = null) + { + name = slice.IsNameNext ? slice.ExtractSwiftName() : name; + char t = slice.Current; + MarkOperatorPosition(); + switch (t) + { + case 'f': + return ReadUncurriedFunctionType(name, isReference, subs.Last() as SwiftClassType); + + case 'F': + return ReadFunctionType(name, isReference); + case 'c': + return ReadCFunctionType(name, isReference); + case 'G': + return ReadBoundGenericType(name, isReference); + case 'S': + return DemangleSubstitution(name, isReference); + case 'V': + case 'C': + case 'O': + return ReadClassOrStructOrEnum(name, isReference); + case 'P': + return ReadProtocolList(name, isReference); + case 'M': + return ReadMetaClassType(name, isReference); + case 'R': + slice.Advance(); + return ReadType(true, name); + case 'T': + return ReadTupleType(name, isReference); + case 'u': + return ReadUnboundGenericType(name, isReference); + case 'x': + slice.Advance(); + return new SwiftGenericArgReferenceType(0, 0, isReference, name); + case 'q': + return ReadGenericReferenceType(name, isReference); + default: + Fail("a type marker (one of F, G, S, V, C, O, M, R, T, u, x, or q)"); + return null; + } + } + + TLFunction ReadExplicitClosure(bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('F')) + Fail("an explicit closure marker (F)"); + + SwiftClassType st = ReadType(isReference) as SwiftClassType; + if (st == null) + Fail("a class type"); + return new TLFunction(slice.Original, st.ClassName.Module, st.Name, st, new SwiftExplicitClosureType(isReference), offset); + } + + SwiftUncurriedFunctionType ReadUncurriedFunctionType(SwiftName name, bool isReference, SwiftType implicitType) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('f')) + Fail("an uncurried function type (f)"); + bool canThrow = slice.AdvanceIfEquals('z'); + if (isOldVersion) + { + SwiftType uncurriedParamType = ReadType(false); + SwiftFunctionType func = ReadFunctionType(null, false); + return new SwiftUncurriedFunctionType(uncurriedParamType, func.Parameters, func.ReturnType, isReference, canThrow, name); + } + else + { + SwiftType args = ReadType(false); + SwiftType ret = ReadType(false); + return new SwiftUncurriedFunctionType(implicitType, args, ret, isReference, canThrow, name); + } + } + + SwiftConstructorType ReadAllocOrCons(bool isAllocator, char advanceOn, string expected, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals(advanceOn)) + Fail(expected); + SwiftUncurriedFunctionType ucf = ReadUncurriedFunctionType(null, false, new SwiftMetaClassType(subs.Last() as SwiftClassType, false, null)); + return new SwiftConstructorType(isAllocator, ucf.UncurriedParameter, ucf.Parameters, ucf.ReturnType, isReference, ucf.CanThrow); + } + + SwiftAddressorType ReadAddressorMutable(SwiftClassType cl, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('a')) + Fail("an addressor"); + AddressorType theType = AddressorType.UnsafeMutable; + char c = slice.Advance(); + switch (c) + { + case 'O': + theType = AddressorType.OwningMutable; + break; + case 'o': + theType = AddressorType.NativeOwningMutable; + break; + case 'p': + theType = AddressorType.NativePinningMutable; + break; + case 'u': + theType = AddressorType.UnsafeMutable; + break; + default: + Fail("one of O, o, p, or u", c.ToString()); + break; + } + if (!slice.IsNameNext) + Fail("a swift name"); + SwiftName addressorName = slice.ExtractSwiftName(); + SwiftType ofType = ReadType(true); // addressors return the address of the entity + return new SwiftAddressorType(theType, ofType, isReference, addressorName); + } + + SwiftAddressorType ReadAddressor(SwiftClassType cl, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('l')) + Fail("an addressor"); + AddressorType theType = AddressorType.UnsafeMutable; + char c = slice.Advance(); + switch (c) + { + case 'O': + theType = AddressorType.Owning; + break; + case 'o': + theType = AddressorType.NativeOwning; + break; + case 'p': + theType = AddressorType.NativePinning; + break; + case 'u': + theType = AddressorType.Unsafe; + break; + default: + Fail("one of O, o, p, or u", c.ToString()); + break; + } + if (!slice.IsNameNext) + Fail("a swift name"); + SwiftName addressorName = slice.ExtractSwiftName(); + SwiftType ofType = ReadType(true); // addressors return the address of the entity + return new SwiftAddressorType(theType, ofType, isReference, addressorName); + } + + SwiftPropertyType ReadGetter(SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('g')) + Fail("a property getter (g)"); + return ReadProperty(cl, PropertyType.Getter, isStatic, isReference); + } + + SwiftPropertyType ReadSetter(SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('s')) + Fail("a property setter"); + return ReadProperty(cl, PropertyType.Setter, isStatic, isReference); + } + + SwiftPropertyType ReadMaterializer(SwiftClassType cl, bool isStatic, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('m')) + Fail("a property materializer"); + return ReadProperty(cl, PropertyType.Materializer, isStatic, isReference); + } + + SwiftPropertyType ReadProperty(SwiftClassType cl, PropertyType propType, bool isStatic, bool isReference) + { + SwiftName privateName = null; + MarkOperatorPosition(); + if (slice.AdvanceIfEquals('P')) + privateName = slice.ExtractSwiftName(); + MarkOperatorPosition(); + if (!slice.IsNameNext) + Fail("a swift name"); + SwiftName propName = slice.ExtractSwiftName(); + + if (IsSubscript(propName)) + { + SwiftType subscriptType = ReadType(false); + SwiftBaseFunctionType subscriptFunc = subscriptType as SwiftBaseFunctionType; + if (subscriptFunc == null) + Fail("a function type in an indexed property", subscriptType.GetType().Name); + + if (propType == PropertyType.Setter && subscriptFunc.ReturnType != null && !subscriptFunc.ReturnType.IsEmptyTuple) + { + // oh hooray! + // If I define an indexer in swift like this: + // public subscript(T index) -> U { + // get { return getSomeUValue(index); } + // set (someUValue) { setSomeUValue(index, someUValue); } + // } + // This signature of the function attached to both properties is: + // T -> U + // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but + // the setter is (T, U) -> void + // + // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect + // what's really happening. + + // need to change this so that the tail parameters get names? Maybe just the head? + + SwiftTupleType newParameters = subscriptFunc.ParameterCount == 1 ? + new SwiftTupleType(false, null, subscriptFunc.ReturnType, + subscriptFunc.Parameters.RenamedCloneOf(new SwiftName(subscriptFunc.ReturnType.Name == null || + subscriptFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) + : new SwiftTupleType(Enumerable.Concat(subscriptFunc.ReturnType.Yield(), subscriptFunc.EachParameter), + false, null); + subscriptFunc = new SwiftFunctionType(newParameters, SwiftTupleType.Empty, false, subscriptFunc.CanThrow, subscriptFunc.Name); + } + return new SwiftPropertyType(cl, propType, propName, privateName, (SwiftFunctionType)subscriptFunc, isStatic, isReference); + + } + else + { + SwiftType ofType = ReadType(false); + + return new SwiftPropertyType(cl, propType, propName, privateName, ofType, isStatic, isReference); + } + } + + public static bool IsSubscript(SwiftName name) + { + return name.Name == "subscript"; + } + + SwiftConstructorType ReadAllocatorType(bool isReference) + { + return ReadAllocOrCons(true, 'C', "an allocating constructor (C)", isReference); + } + + SwiftConstructorType ReadConstructorType(bool isReference) + { + return ReadAllocOrCons(false, 'c', "a non-allocating constructor (c)", isReference); + } + + SwiftType ReadProtocolList(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('P')) + Fail("A protocol list marker ('P')"); + if (slice.Current == 'M') + { + return ReadExistentialMetatype(name, isReference); + } + List protocols = new List(); + while (slice.Current != '_') + { + SwiftClassName className = ReadProtocolName(); + SwiftClassType theProtocol = new SwiftClassType(className, false, null); + subs.Add(theProtocol); + protocols.Add(theProtocol); + } + slice.Advance(); + return new SwiftProtocolListType(protocols, isReference, name); + } + + SwiftClassType ReadClassOrStructOrEnum(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + SwiftClassName className = ReadClassStructEnumNameAlt(); + SwiftClassType clType = new SwiftClassType(className, isReference, name); + subs.Add(clType); + return clType; + } + + SwiftMetaClassType ReadMetaClassType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('M')) + Fail("a metaclass marker (M)"); + SwiftClassType cl = ReadType(false) as SwiftClassType; + if (cl == null) + Fail("a class type"); + return new SwiftMetaClassType(cl, isReference, name); + } + + SwiftExistentialMetaType ReadExistentialMetatype(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('M')) + Fail("a metaclass marker (M)"); + SwiftProtocolListType pl = ReadType(false) as SwiftProtocolListType; + if (pl == null) + Fail("a protocol list type"); + return new SwiftExistentialMetaType(pl, isReference, name); + } + + + SwiftType ReadUnboundGenericType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('u')) + Fail("an unbound generic type (u)"); + MarkOperatorPosition(); + List parms = ReadGenericArguments(); + SwiftType dependentType = ReadType(isReference, name); + SwiftBaseFunctionType bft = dependentType as SwiftBaseFunctionType; + if (bft != null) + { + bft.GenericArguments.AddRange(parms); + return bft; + } + return new SwiftUnboundGenericType(dependentType, parms, isReference, dependentType.Name); + } + + + List ReadGenericArguments() + { + int count = 0; + while (slice.Current != 'R' && slice.Current != 'r') + { + count = DemangleIndex(); + } + count += 1; + List args = new List(count); + for (int i = 0; i < count; i++) + { + args.Add(new GenericArgument(0, i)); + } + if (slice.AdvanceIfEquals('r')) + return args; + if (!slice.AdvanceIfEquals('R')) + Fail("A generic argument requirements marker (R)"); + while (!slice.AdvanceIfEquals('r')) + { + int depth = 0; + int index = 0; + if (slice.AdvanceIfEquals('d')) + { + depth = DemangleIndex(); + index = DemangleIndex(); + } + else if (slice.AdvanceIfEquals('x')) + { + // no change + } + else + { + index = DemangleIndex() + 1; + } + if (slice.StartsWith('C')) + { + SwiftType constraintType = ReadType(false, null); + args[index].Constraints.Add(constraintType); + } + else + { + SwiftClassName className = ReadProtocolName(); + SwiftClassType theProtocol = new SwiftClassType(className, false, null); + args[index].Constraints.Add(theProtocol); + } + args[index].Depth = depth; + } + // currently swift name mangling is done incorrectly to get the actual + // depth. In the case where there is a 'where' clause, we can figure it out + // and correct it. + int maxDepth = 0; + foreach (GenericArgument gen in args) + { + maxDepth = Math.Max(maxDepth, gen.Depth); + } + foreach (GenericArgument gen in args) + { + gen.Depth = maxDepth; + } + return args; + } + + SwiftGenericArgReferenceType ReadGenericReferenceType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('q')) + Fail("a generic argument reference"); + MarkOperatorPosition(); + int depth = 0; + int index = 0; + if (slice.AdvanceIfEquals('d')) + { + depth = DemangleIndex() + 1; + index = DemangleIndex() + 1; + } + else + { + index = DemangleIndex() + 1; + } + return new SwiftGenericArgReferenceType(depth, index, isReference, name); + } + + SwiftBoundGenericType ReadBoundGenericType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('G')) + Fail("a bound generic type (G)"); + MarkOperatorPosition(); + SwiftType baseType = ReadType(false); + + List generics = new List(); + while (!slice.AdvanceIfEquals('_')) + { + MarkOperatorPosition(); + SwiftType t = ReadType(false); + if (t != null) + generics.Add(t); + } + return new SwiftBoundGenericType(baseType, generics, isReference, name); + } + + SwiftArrayType ReadArrayType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('S') || !slice.AdvanceIfEquals('a')) + Fail("an Array type (Sa)"); + return new SwiftArrayType(isReference, name); + } + + SwiftFunctionType ReadFunctionType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('F')) + Fail("a function marker (F)"); + bool canThrow = slice.AdvanceIfEquals('z'); + SwiftType parms = ReadType(false); + SwiftType ret = ReadType(false); + return new SwiftFunctionType(parms, ret, isReference, canThrow, name); + } + + SwiftCFunctionType ReadCFunctionType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('c')) + Fail("a C function marker (c)"); + SwiftType parms = ReadType(false); + SwiftType ret = ReadType(false); + return new SwiftCFunctionType(parms, ret, isReference, name); + } + + SwiftType ReadScalarType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('S')) + Fail("a core built in type marker (S)"); + if (slice.Current == 'S') + { + slice.Advance(); + return ClassForBuiltInType(name, "String", MemberNesting.Struct, isReference); + } + else if (slice.Current == 'q') + { + slice.Advance(); + return ClassForBuiltInType(name, "Optional", MemberNesting.Enum, isReference); + } + else if (slice.Current == 'Q') + { + slice.Advance(); + return ClassForBuiltInType(name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); + } + else if (slice.Current == 'P') + { + slice.Advance(); + return ClassForBuiltInType(name, "UnsafePointer", MemberNesting.Struct, isReference); + } + else if (slice.Current == 'p') + { + slice.Advance(); + return ClassForBuiltInType(name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); + } + else if (slice.Current == 'R') + { + slice.Advance(); + return ClassForBuiltInType(name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); + } + else if (slice.Current == 'r') + { + slice.Advance(); + return ClassForBuiltInType(name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); + } + else + { + CoreBuiltInType scalarType = ToCoreScalar(slice.Advance()); + return new SwiftBuiltInType(scalarType, isReference, name); + } + } + + SwiftTupleType ReadTupleType(SwiftName name, bool isReference) + { + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('T')) + Fail("a tuple marker (T)"); + + List contents = new List(); + while (!slice.AdvanceIfEquals('_')) + { + MarkOperatorPosition(); + SwiftType ty = ReadType(false); + contents.Add(ty); + } + return new SwiftTupleType(contents, isReference, name); + } + + static SwiftClassType ClassForBuiltInType(SwiftName name, string className, MemberNesting nesting, bool isReference) + { + return new SwiftClassType(new SwiftClassName(new SwiftName("Swift", false), + new List { nesting }, + new List { new SwiftName(className, false) }), isReference, name); + } + + SwiftType DemangleSubstitution(SwiftName name, bool isReference) + { + if (!slice.AdvanceIfEquals('S')) + Fail("a core built in type marker (S)"); + if (slice.AdvanceIfEquals('a')) + { + return ClassForBuiltInType(name, "Array", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('c')) + { + return ClassForBuiltInType(name, "UnicodeScalar", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('S')) + { + return ClassForBuiltInType(name, "String", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('q')) + { + return ClassForBuiltInType(name, "Optional", MemberNesting.Enum, isReference); + } + if (slice.AdvanceIfEquals('Q')) + { + return ClassForBuiltInType(name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('P')) + { + return ClassForBuiltInType(name, "UnsafePointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('p')) + { + return ClassForBuiltInType(name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('R')) + { + return ClassForBuiltInType(name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('r')) + { + return ClassForBuiltInType(name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('V')) + { + return ClassForBuiltInType(name, "UnsafeRawPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('v')) + { + return ClassForBuiltInType(name, "UnsafeMutableRawPointer", MemberNesting.Struct, isReference); + } + if (slice.AdvanceIfEquals('b')) + { + return new SwiftBuiltInType(CoreBuiltInType.Bool, isReference, name); + } + if (slice.AdvanceIfEquals('d')) + { + return new SwiftBuiltInType(CoreBuiltInType.Double, isReference, name); + } + if (slice.AdvanceIfEquals('f')) + { + return new SwiftBuiltInType(CoreBuiltInType.Float, isReference, name); + } + if (slice.AdvanceIfEquals('i')) + { + return new SwiftBuiltInType(CoreBuiltInType.Int, isReference, name); + } + if (slice.AdvanceIfEquals('u')) + { + return new SwiftBuiltInType(CoreBuiltInType.UInt, isReference, name); + } + if (slice.AdvanceIfEquals('s')) + { + return new SwiftModuleNameType(new SwiftName("Swift", false), isReference); + } + int index = DemangleIndex(); + SwiftType st = subs[index]; + SwiftClassType sct = st as SwiftClassType; + if (sct == null) + { + SwiftModuleNameType mod = st as SwiftModuleNameType; + if (mod == null) + Fail("a SwiftModuleNameType", st.GetType().Name); + return mod; + } + return new SwiftClassType(sct.ClassName, isReference, name); + } + + int DemangleIndex() + { + if (slice.AdvanceIfEquals('_')) + { + return 0; + } + MarkOperatorPosition(); + if (!Char.IsDigit(slice.Current)) + Fail("a number", slice.Current.ToString()); + int index = ReadNumber(); + MarkOperatorPosition(); + if (!slice.AdvanceIfEquals('_')) + Fail("a macro terminator '-'", slice.Current.ToString()); + return index + 1; + } + + int ReadNumber() + { + int number = 0; + while (Char.IsDigit(slice.Current)) + { + number = 10 * number + slice.Current - '0'; + slice.Advance(); + } + return number; + } + } } diff --git a/src/SwiftReflector/Demangling/Enums.cs b/src/SwiftReflector/Demangling/Enums.cs index f79773f0e226..f6a630b886b4 100644 --- a/src/SwiftReflector/Demangling/Enums.cs +++ b/src/SwiftReflector/Demangling/Enums.cs @@ -2,369 +2,380 @@ // Licensed under the MIT License. using System; -namespace SwiftReflector.Demangling { - public enum NodeKind { - [Context] - Allocator, - [Context] - AnonymousContext, - AnyProtocolConformanceList, - ArgumentTuple, - AssociatedType, - AssociatedTypeRef, - AssociatedTypeMetadataAccessor, - DefaultAssociatedTypeMetadataAccessor, - AssociatedTypeWitnessTableAccessor, - BaseWitnessTableAccessor, - AutoClosureType, - BoundGenericClass, - BoundGenericEnum, - BoundGenericStructure, - BoundGenericProtocol, - BoundGenericOtherNominalType, - BoundGenericTypeAlias, - BoundGenericFunction, - BuiltinTypeName, - CFunctionPointer, - [Context] - Class, - ClassMetadataBaseOffset, - ConcreteProtocolConformance, - [Context] - Constructor, - CoroutineContinuationPrototype, - [Context] - Deallocator, - DeclContext, - [Context] - DefaultArgumentInitializer, - DependentAssociatedConformance, - DependentAssociatedTypeRef, - DependentGenericConformanceRequirement, - DependentGenericParamCount, - DependentGenericParamType, - DependentGenericSameTypeRequirement, - DependentGenericLayoutRequirement, - DependentGenericSignature, - DependentGenericType, - DependentMemberType, - DependentPseudogenericSignature, - DependentProtocolConformanceRoot, - DependentProtocolConformanceInherited, - DependentProtocolConformanceAssociated, - [Context] - Destructor, - [Context] - DidSet, - Directness, - DynamicAttribute, - DirectMethodReferenceAttribute, - DynamicSelf, - DynamicallyReplaceableFunctionImpl, - DynamicallyReplaceableFunctionKey, - DynamicallyReplaceableFunctionVar, - [Context] - Enum, - EnumCase, - ErrorType, - EscapingAutoClosureType, - NoEscapeFunctionType, - ExistentialMetatype, - [Context] - ExplicitClosure, - [Context] - Extension, - FieldOffset, - FullTypeMetadata, - [Context] - Function, - FunctionSignatureSpecialization, - FunctionSignatureSpecializationParam, - FunctionSignatureSpecializationParamKind, - FunctionSignatureSpecializationParamPayload, - FunctionType, - GenericPartialSpecialization, - GenericPartialSpecializationNotReAbstracted, - GenericProtocolWitnessTable, - GenericProtocolWitnessTableInstantiationFunction, - ResilientProtocolWitnessTable, - GenericSpecialization, - GenericSpecializationNotReAbstracted, - GenericSpecializationParam, - InlinedGenericFunction, - GenericTypeMetadataPattern, - [Context] - Getter, - Global, - [Context] - GlobalGetter, - Identifier, - Index, - [Context] - IVarInitializer, - [Context] - IVarDestroyer, - ImplEscaping, - ImplConvention, - ImplFunctionAttribute, - ImplFunctionType, - [Context] - ImplicitClosure, - ImplParameter, - ImplResult, - ImplErrorResult, - InOut, - InfixOperator, - [Context] - Initializer, - KeyPathGetterThunkHelper, - KeyPathSetterThunkHelper, - KeyPathEqualsThunkHelper, - KeyPathHashThunkHelper, - LazyProtocolWitnessTableAccessor, - LazyProtocolWitnessTableCacheVariable, - LocalDeclName, - [Context] - MaterializeForSet, - MergedFunction, - Metatype, - MetatypeRepresentation, - Metaclass, - MethodLookupFunction, - ObjCMetadataUpdateFunction, - [Context] - ModifyAccessor, - [Context] - Module, - [Context] - NativeOwningAddressor, - [Context] - NativeOwningMutableAddressor, - [Context] - NativePinningAddressor, - [Context] - NativePinningMutableAddressor, - NominalTypeDescriptor, - NonObjCAttribute, - Number, - ObjCAttribute, - ObjCBlock, - [Context] - OtherNominalType, - [Context] - OwningAddressor, - [Context] - OwningMutableAddressor, - PartialApplyForwarder, - PartialApplyObjCForwarder, - PostfixOperator, - PrefixOperator, - PrivateDeclName, - PropertyDescriptor, - [Context] - Protocol, - [Context] - ProtocolSymbolicReference, - ProtocolConformance, - ProtocolConformanceRefInTypeModule, - ProtocolConformanceRefInProtocolModule, - ProtocolConformanceRefInOtherModule, - ProtocolDescriptor, - ProtocolConformanceDescriptor, - ProtocolList, - ProtocolListWithClass, - ProtocolListWithAnyObject, - ProtocolSelfConformanceDescriptor, - ProtocolSelfConformanceWitness, - ProtocolSelfConformanceWitnessTable, - ProtocolWitness, - ProtocolWitnessTable, - ProtocolWitnessTableAccessor, - ProtocolWitnessTablePattern, - ReabstractionThunk, - ReabstractionThunkHelper, - [Context] - ReadAccessor, - RelatedEntityDeclName, - RetroactiveConformance, - ReturnType, - Shared, - Owned, - SILBoxType, - SILBoxTypeWithLayout, - SILBoxLayout, - SILBoxMutableField, - SILBoxImmutableField, - [Context] - Setter, - SpecializationPassID, - SpecializationIsFragile, - [Context] - Static, - [Context] - Structure, - [Context] - Subscript, - Suffix, - ThinFunctionType, - Tuple, - TupleElement, - TupleElementName, - Type, - [Context] - TypeSymbolicReference, - [Context] - TypeAlias, - TypeList, - TypeMangling, - TypeMetadata, - TypeMetadataAccessFunction, - TypeMetadataCompletionFunction, - TypeMetadataInstantiationCache, - TypeMetadataInstantiationFunction, - TypeMetadataSingletonInitializationCache, - TypeMetadataLazyCache, - Unowned, - UncurriedFunctionType, - Weak, +namespace SwiftReflector.Demangling +{ + public enum NodeKind + { + [Context] + Allocator, + [Context] + AnonymousContext, + AnyProtocolConformanceList, + ArgumentTuple, + AssociatedType, + AssociatedTypeRef, + AssociatedTypeMetadataAccessor, + DefaultAssociatedTypeMetadataAccessor, + AssociatedTypeWitnessTableAccessor, + BaseWitnessTableAccessor, + AutoClosureType, + BoundGenericClass, + BoundGenericEnum, + BoundGenericStructure, + BoundGenericProtocol, + BoundGenericOtherNominalType, + BoundGenericTypeAlias, + BoundGenericFunction, + BuiltinTypeName, + CFunctionPointer, + [Context] + Class, + ClassMetadataBaseOffset, + ConcreteProtocolConformance, + [Context] + Constructor, + CoroutineContinuationPrototype, + [Context] + Deallocator, + DeclContext, + [Context] + DefaultArgumentInitializer, + DependentAssociatedConformance, + DependentAssociatedTypeRef, + DependentGenericConformanceRequirement, + DependentGenericParamCount, + DependentGenericParamType, + DependentGenericSameTypeRequirement, + DependentGenericLayoutRequirement, + DependentGenericSignature, + DependentGenericType, + DependentMemberType, + DependentPseudogenericSignature, + DependentProtocolConformanceRoot, + DependentProtocolConformanceInherited, + DependentProtocolConformanceAssociated, + [Context] + Destructor, + [Context] + DidSet, + Directness, + DynamicAttribute, + DirectMethodReferenceAttribute, + DynamicSelf, + DynamicallyReplaceableFunctionImpl, + DynamicallyReplaceableFunctionKey, + DynamicallyReplaceableFunctionVar, + [Context] + Enum, + EnumCase, + ErrorType, + EscapingAutoClosureType, + NoEscapeFunctionType, + ExistentialMetatype, + [Context] + ExplicitClosure, + [Context] + Extension, + FieldOffset, + FullTypeMetadata, + [Context] + Function, + FunctionSignatureSpecialization, + FunctionSignatureSpecializationParam, + FunctionSignatureSpecializationParamKind, + FunctionSignatureSpecializationParamPayload, + FunctionType, + GenericPartialSpecialization, + GenericPartialSpecializationNotReAbstracted, + GenericProtocolWitnessTable, + GenericProtocolWitnessTableInstantiationFunction, + ResilientProtocolWitnessTable, + GenericSpecialization, + GenericSpecializationNotReAbstracted, + GenericSpecializationParam, + InlinedGenericFunction, + GenericTypeMetadataPattern, + [Context] + Getter, + Global, + [Context] + GlobalGetter, + Identifier, + Index, + [Context] + IVarInitializer, + [Context] + IVarDestroyer, + ImplEscaping, + ImplConvention, + ImplFunctionAttribute, + ImplFunctionType, + [Context] + ImplicitClosure, + ImplParameter, + ImplResult, + ImplErrorResult, + InOut, + InfixOperator, + [Context] + Initializer, + KeyPathGetterThunkHelper, + KeyPathSetterThunkHelper, + KeyPathEqualsThunkHelper, + KeyPathHashThunkHelper, + LazyProtocolWitnessTableAccessor, + LazyProtocolWitnessTableCacheVariable, + LocalDeclName, + [Context] + MaterializeForSet, + MergedFunction, + Metatype, + MetatypeRepresentation, + Metaclass, + MethodLookupFunction, + ObjCMetadataUpdateFunction, + [Context] + ModifyAccessor, + [Context] + Module, + [Context] + NativeOwningAddressor, + [Context] + NativeOwningMutableAddressor, + [Context] + NativePinningAddressor, + [Context] + NativePinningMutableAddressor, + NominalTypeDescriptor, + NonObjCAttribute, + Number, + ObjCAttribute, + ObjCBlock, + [Context] + OtherNominalType, + [Context] + OwningAddressor, + [Context] + OwningMutableAddressor, + PartialApplyForwarder, + PartialApplyObjCForwarder, + PostfixOperator, + PrefixOperator, + PrivateDeclName, + PropertyDescriptor, + [Context] + Protocol, + [Context] + ProtocolSymbolicReference, + ProtocolConformance, + ProtocolConformanceRefInTypeModule, + ProtocolConformanceRefInProtocolModule, + ProtocolConformanceRefInOtherModule, + ProtocolDescriptor, + ProtocolConformanceDescriptor, + ProtocolList, + ProtocolListWithClass, + ProtocolListWithAnyObject, + ProtocolSelfConformanceDescriptor, + ProtocolSelfConformanceWitness, + ProtocolSelfConformanceWitnessTable, + ProtocolWitness, + ProtocolWitnessTable, + ProtocolWitnessTableAccessor, + ProtocolWitnessTablePattern, + ReabstractionThunk, + ReabstractionThunkHelper, + [Context] + ReadAccessor, + RelatedEntityDeclName, + RetroactiveConformance, + ReturnType, + Shared, + Owned, + SILBoxType, + SILBoxTypeWithLayout, + SILBoxLayout, + SILBoxMutableField, + SILBoxImmutableField, + [Context] + Setter, + SpecializationPassID, + SpecializationIsFragile, + [Context] + Static, + [Context] + Structure, + [Context] + Subscript, + Suffix, + ThinFunctionType, + Tuple, + TupleElement, + TupleElementName, + Type, + [Context] + TypeSymbolicReference, + [Context] + TypeAlias, + TypeList, + TypeMangling, + TypeMetadata, + TypeMetadataAccessFunction, + TypeMetadataCompletionFunction, + TypeMetadataInstantiationCache, + TypeMetadataInstantiationFunction, + TypeMetadataSingletonInitializationCache, + TypeMetadataLazyCache, + Unowned, + UncurriedFunctionType, + Weak, - Unmanaged, - [Context] - UnsafeAddressor, - [Context] - UnsafeMutableAddressor, - ValueWitness, - ValueWitnessTable, - [Context] - Variable, - VTableThunk, - VTableAttribute, // note: old mangling only - [Context] - WillSet, - ReflectionMetadataBuiltinDescriptor, - ReflectionMetadataFieldDescriptor, - ReflectionMetadataAssocTypeDescriptor, - ReflectionMetadataSuperclassDescriptor, - GenericTypeParamDecl, - CurryThunk, - DispatchThunk, - MethodDescriptor, - ProtocolRequirementsBaseDescriptor, - AssociatedConformanceDescriptor, - DefaultAssociatedConformanceAccessor, - BaseConformanceDescriptor, - AssociatedTypeDescriptor, - ThrowsAnnotation, - EmptyList, - FirstElementMarker, - VariadicMarker, - OutlinedBridgedMethod, - OutlinedCopy, - OutlinedConsume, - OutlinedRetain, - OutlinedRelease, - OutlinedInitializeWithTake, - OutlinedInitializeWithCopy, - OutlinedAssignWithTake, - OutlinedAssignWithCopy, - OutlinedDestroy, - OutlinedVariable, - AssocTypePath, - LabelList, - ModuleDescriptor, - ExtensionDescriptor, - AnonymousDescriptor, - AssociatedTypeGenericParamRef, - } + Unmanaged, + [Context] + UnsafeAddressor, + [Context] + UnsafeMutableAddressor, + ValueWitness, + ValueWitnessTable, + [Context] + Variable, + VTableThunk, + VTableAttribute, // note: old mangling only + [Context] + WillSet, + ReflectionMetadataBuiltinDescriptor, + ReflectionMetadataFieldDescriptor, + ReflectionMetadataAssocTypeDescriptor, + ReflectionMetadataSuperclassDescriptor, + GenericTypeParamDecl, + CurryThunk, + DispatchThunk, + MethodDescriptor, + ProtocolRequirementsBaseDescriptor, + AssociatedConformanceDescriptor, + DefaultAssociatedConformanceAccessor, + BaseConformanceDescriptor, + AssociatedTypeDescriptor, + ThrowsAnnotation, + EmptyList, + FirstElementMarker, + VariadicMarker, + OutlinedBridgedMethod, + OutlinedCopy, + OutlinedConsume, + OutlinedRetain, + OutlinedRelease, + OutlinedInitializeWithTake, + OutlinedInitializeWithCopy, + OutlinedAssignWithTake, + OutlinedAssignWithCopy, + OutlinedDestroy, + OutlinedVariable, + AssocTypePath, + LabelList, + ModuleDescriptor, + ExtensionDescriptor, + AnonymousDescriptor, + AssociatedTypeGenericParamRef, + } - public enum PayloadKind { - None, - Text, - Index, - } + public enum PayloadKind + { + None, + Text, + Index, + } - public enum GenericTypeKind { - Generic, - Assoc, - CompoundAssoc, - Substitution, - } + public enum GenericTypeKind + { + Generic, + Assoc, + CompoundAssoc, + Substitution, + } - public enum GenericConstraintKind { - Protocol, - BaseClass, - SameType, - Layout, - } + public enum GenericConstraintKind + { + Protocol, + BaseClass, + SameType, + Layout, + } - public enum FunctionSigSpecializationParamKind : uint { - ConstantPropFunction = 0, - ConstantPropGlobal = 1, - ConstantPropInteger = 2, - ConstantPropFloat = 3, - ConstantPropString = 4, - ClosureProp = 5, - BoxToValue = 6, - BoxToStack = 7, + public enum FunctionSigSpecializationParamKind : uint + { + ConstantPropFunction = 0, + ConstantPropGlobal = 1, + ConstantPropInteger = 2, + ConstantPropFloat = 3, + ConstantPropString = 4, + ClosureProp = 5, + BoxToValue = 6, + BoxToStack = 7, - // Option Set Flags use bits 6-31. This gives us 26 bits to use for option - // flags. - Dead = 1 << 6, - OwnedToGuaranteed = 1 << 7, - SROA = 1 << 8, - GuaranteedToOwned = 1 << 9, - ExistentialToGeneric = 1 << 10, - } + // Option Set Flags use bits 6-31. This gives us 26 bits to use for option + // flags. + Dead = 1 << 6, + OwnedToGuaranteed = 1 << 7, + SROA = 1 << 8, + GuaranteedToOwned = 1 << 9, + ExistentialToGeneric = 1 << 10, + } - public enum Directness { - Direct, - Indirect, - } + public enum Directness + { + Direct, + Indirect, + } - public enum FunctionEntityArgs { - None, - Type, - TypeAndName, - TypeAndMaybePrivateName, - TypeAndIndex, - Index, - } + public enum FunctionEntityArgs + { + None, + Type, + TypeAndName, + TypeAndMaybePrivateName, + TypeAndIndex, + Index, + } - public enum ValueWitnessKind { - AllocateBuffer, - AssignWithCopy, - AssignWithTake, - DeallocateBuffer, - Destroy, - DestroyBuffer, - DestroyArray, - InitializeBufferWithCopyOfBuffer, - InitializeBufferWithCopy, - InitializeWithCopy, - InitializeBufferWithTake, - InitializeWithTake, - ProjectBuffer, - InitializeBufferWithTakeOfBuffer, - InitializeArrayWithCopy, - InitializeArrayWithTakeFrontToBack, - InitializeArrayWithTakeBackToFront, - StoreExtraInhabitant, - GetExtraInhabitantIndex, - GetEnumTag, - DestructiveProjectEnumData, - DestructiveInjectEnumTag, - GetEnumTagSinglePayload, - StoreEnumTagSinglePayload - } + public enum ValueWitnessKind + { + AllocateBuffer, + AssignWithCopy, + AssignWithTake, + DeallocateBuffer, + Destroy, + DestroyBuffer, + DestroyArray, + InitializeBufferWithCopyOfBuffer, + InitializeBufferWithCopy, + InitializeWithCopy, + InitializeBufferWithTake, + InitializeWithTake, + ProjectBuffer, + InitializeBufferWithTakeOfBuffer, + InitializeArrayWithCopy, + InitializeArrayWithTakeFrontToBack, + InitializeArrayWithTakeBackToFront, + StoreExtraInhabitant, + GetExtraInhabitantIndex, + GetEnumTag, + DestructiveProjectEnumData, + DestructiveInjectEnumTag, + GetEnumTagSinglePayload, + StoreEnumTagSinglePayload + } - public enum MatchNodeContentType { - None, - Index, - Text, - AlwaysMatch, - } + public enum MatchNodeContentType + { + None, + Index, + Text, + AlwaysMatch, + } - public enum SymbolicReferenceKind { - Context, - } + public enum SymbolicReferenceKind + { + Context, + } } diff --git a/src/SwiftReflector/Demangling/MatchRule.cs b/src/SwiftReflector/Demangling/MatchRule.cs index 7838a49541bd..97c862791795 100644 --- a/src/SwiftReflector/Demangling/MatchRule.cs +++ b/src/SwiftReflector/Demangling/MatchRule.cs @@ -6,88 +6,94 @@ using System.Linq; using SwiftRuntimeLibrary; -namespace SwiftReflector.Demangling { - public class MatchRule { - public MatchRule () - { - Name = ""; - NodeKind = NodeKind.Type; // arbitrary - MatchContent = MatchNodeContentType.AlwaysMatch; - ChildRules = new List (); - MatchChildCount = false; - Reducer = (n, b, name) => null; - } +namespace SwiftReflector.Demangling +{ + public class MatchRule + { + public MatchRule() + { + Name = ""; + NodeKind = NodeKind.Type; // arbitrary + MatchContent = MatchNodeContentType.AlwaysMatch; + ChildRules = new List(); + MatchChildCount = false; + Reducer = (n, b, name) => null; + } - public string Name { get; set; } - public NodeKind NodeKind { - get { - if (NodeKindList.Count != 1) - throw new InvalidOperationException ($"NodeKind is invalid when NodeKindList has {NodeKindList.Count} entries."); - return NodeKindList [0]; - } - set { - NodeKindList = new List { value }; - } - } - public List NodeKindList { get; set; } - public MatchNodeContentType MatchContent { get; set; } - public List ChildRules { get; set; } - public bool MatchChildCount { get; set; } - public Func Reducer { get; set; } + public string Name { get; set; } + public NodeKind NodeKind + { + get + { + if (NodeKindList.Count != 1) + throw new InvalidOperationException($"NodeKind is invalid when NodeKindList has {NodeKindList.Count} entries."); + return NodeKindList[0]; + } + set + { + NodeKindList = new List { value }; + } + } + public List NodeKindList { get; set; } + public MatchNodeContentType MatchContent { get; set; } + public List ChildRules { get; set; } + public bool MatchChildCount { get; set; } + public Func Reducer { get; set; } - public bool Matches(Node n) - { - Exceptions.ThrowOnNull (n, nameof (n)); - // 3 match criteria: NodeKind, Content type, children - return NodeKindMatches (n) && ContentMatches (n) && - ChildrenMatches (n); - } + public bool Matches(Node n) + { + Exceptions.ThrowOnNull(n, nameof(n)); + // 3 match criteria: NodeKind, Content type, children + return NodeKindMatches(n) && ContentMatches(n) && + ChildrenMatches(n); + } - bool NodeKindMatches(Node n) - { - return NodeKindList.Contains (n.Kind); - } + bool NodeKindMatches(Node n) + { + return NodeKindList.Contains(n.Kind); + } - bool ContentMatches(Node n) - { - // Only care about the content type not its value - switch (MatchContent) - { - case MatchNodeContentType.AlwaysMatch: - return true; - case MatchNodeContentType.Index: - return n.HasIndex; - case MatchNodeContentType.Text: - return n.HasText; - case MatchNodeContentType.None: - return !n.HasIndex && !n.HasText; - default: - throw new InvalidOperationException ($"Unknown match instruction {MatchContent} in match rule."); - } - } + bool ContentMatches(Node n) + { + // Only care about the content type not its value + switch (MatchContent) + { + case MatchNodeContentType.AlwaysMatch: + return true; + case MatchNodeContentType.Index: + return n.HasIndex; + case MatchNodeContentType.Text: + return n.HasText; + case MatchNodeContentType.None: + return !n.HasIndex && !n.HasText; + default: + throw new InvalidOperationException($"Unknown match instruction {MatchContent} in match rule."); + } + } - bool ChildrenMatches (Node n) - { - // if the rule says the child count matters, apply - if (MatchChildCount && n.Children.Count != ChildRules.Count) - return false; + bool ChildrenMatches(Node n) + { + // if the rule says the child count matters, apply + if (MatchChildCount && n.Children.Count != ChildRules.Count) + return false; - // match up to the minimum of each list - // if MatchChileCount is true, min is the size of both lists - int minimumChildCount = Math.Min (n.Children.Count, ChildRules.Count); - for (var i = 0; i < minimumChildCount; i++) { - var childRule = ChildRules [i]; - // recurse - if (!childRule.Matches (n.Children [i])) - return false; - } - return true; - } + // match up to the minimum of each list + // if MatchChileCount is true, min is the size of both lists + int minimumChildCount = Math.Min(n.Children.Count, ChildRules.Count); + for (var i = 0; i < minimumChildCount; i++) + { + var childRule = ChildRules[i]; + // recurse + if (!childRule.Matches(n.Children[i])) + return false; + } + return true; + } - public override string ToString() - { - return Name; - } - } + public override string ToString() + { + return Name; + } + } } diff --git a/src/SwiftReflector/Demangling/Node.cs b/src/SwiftReflector/Demangling/Node.cs index 8e1a030a84d1..30a330587d64 100644 --- a/src/SwiftReflector/Demangling/Node.cs +++ b/src/SwiftReflector/Demangling/Node.cs @@ -6,240 +6,257 @@ using System.Linq; using System.Text; -namespace SwiftReflector.Demangling { - public class Node { - Node (NodeKind kind, PayloadKind payload) - { - Kind = kind; - PayloadKind = payload; - Children = new List (); - } - - public Node (NodeKind kind) - : this (kind, PayloadKind.None) - { - } - - public Node (NodeKind kind, string text) - : this (kind, PayloadKind.Text) - { - stringPayload = text; - } - - public Node (NodeKind kind, long index) - : this (kind, PayloadKind.Index) - { - indexPayload = index; - } - - string stringPayload = null; - long indexPayload = 0; - - public List Children { get; private set; } - - public NodeKind Kind { get; private set; } - public PayloadKind PayloadKind { get; private set; } - - public bool HasText { get { return PayloadKind == PayloadKind.Text; } } - public string Text { - get { - if (!HasText) - throw new InvalidOperationException ($"Expected a text payload, but this has a {PayloadKind} payload"); - return stringPayload; - } - } - - public bool HasIndex { get { return PayloadKind == PayloadKind.Index; } } - public long Index { - get { - if (!HasIndex) - throw new InvalidOperationException ($"Expected an index payload, but this has a {PayloadKind} payload"); - return indexPayload; - } - } - - public void AddChild (Node child) - { - Children.Add (child); - } - - public void RemoveChildAt(int pos) - { - Children.RemoveAt (pos); - } - - public void ReverseChildren (int startingAt = 0) - { - var last = Children.Count - 1; - if (startingAt < 0 || startingAt > Children.Count) - throw new ArgumentOutOfRangeException (nameof (startingAt)); - while (startingAt < last) { - Node temp = Children [startingAt]; - Children [startingAt] = Children [last]; - Children [last] = temp; - startingAt++; - last--; - } - } - - - public static bool IsDeclName (NodeKind kind) - { - switch (kind) { - case NodeKind.Identifier: - case NodeKind.LocalDeclName: - case NodeKind.PrivateDeclName: - case NodeKind.RelatedEntityDeclName: - case NodeKind.PrefixOperator: - case NodeKind.PostfixOperator: - case NodeKind.InfixOperator: - case NodeKind.TypeSymbolicReference: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - public static bool IsContext (NodeKind kind) - { - var type = typeof (NodeKind); - var memberInfo = type.GetMember (kind.ToString ()); - var attrs = memberInfo [0].GetCustomAttributes (typeof (ContextAttribute), false); - return attrs != null && attrs.Length == 1; - } - - public static bool IsAnyGeneric (NodeKind kind) - { - switch (kind) { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - case NodeKind.OtherNominalType: - case NodeKind.TypeAlias: - case NodeKind.TypeSymbolicReference: - return true; - default: - return false; - } - } - - public static bool IsNominal (NodeKind kind) - { - switch (kind) { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - return true; - default: - return false; - } - } - - public static bool IsEntity (NodeKind kind) - { - if (kind == NodeKind.Type) - return true; - return IsContext (kind); - } - - public static bool IsRequirement (NodeKind kind) - { - switch (kind) { - case NodeKind.DependentGenericSameTypeRequirement: - case NodeKind.DependentGenericLayoutRequirement: - case NodeKind.DependentGenericConformanceRequirement: - return true; - default: - return false; - } - } - - public static bool IsFunctionAttribute (NodeKind kind) - { - switch (kind) { - case NodeKind.FunctionSignatureSpecialization: - case NodeKind.GenericSpecialization: - case NodeKind.InlinedGenericFunction: - case NodeKind.GenericSpecializationNotReAbstracted: - case NodeKind.GenericPartialSpecialization: - case NodeKind.GenericPartialSpecializationNotReAbstracted: - case NodeKind.ObjCAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.DirectMethodReferenceAttribute: - case NodeKind.VTableAttribute: - case NodeKind.PartialApplyForwarder: - case NodeKind.PartialApplyObjCForwarder: - case NodeKind.OutlinedVariable: - case NodeKind.OutlinedBridgedMethod: - case NodeKind.MergedFunction: - case NodeKind.DynamicallyReplaceableFunctionImpl: - case NodeKind.DynamicallyReplaceableFunctionKey: - case NodeKind.DynamicallyReplaceableFunctionVar: - return true; - default: - return false; - } - } - - public override string ToString () - { - var sb = new StringBuilder (); - ToString (0, sb); - return sb.ToString (); - } - - void ToString (int indent, StringBuilder sb) - { - for (int i = 0; i < indent; i++) { - sb.Append (' '); - } - sb.Append ("->").Append (Kind.ToString ()); - switch (PayloadKind) { - case PayloadKind.None: - sb.Append (Environment.NewLine); - break; - case PayloadKind.Index: - sb.Append ($" ({Index})\n"); - break; - case PayloadKind.Text: - sb.Append ($" (\"{Text}\")\n"); - break; - } - foreach (var node in Children) { - node.ToString (indent + 2, sb); - } - } - - public bool IsAttribute () - { - switch (Kind) { - case NodeKind.ObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.ImplFunctionAttribute: - case NodeKind.DirectMethodReferenceAttribute: - return true; - default: - return false; - } - } - - public SwiftTypeAttribute ExtractAttribute () - { - switch (Kind) { - case NodeKind.ObjCAttribute: return SwiftTypeAttribute.ObjC; - case NodeKind.DynamicAttribute: return SwiftTypeAttribute.Dynamic; - case NodeKind.NonObjCAttribute: return SwiftTypeAttribute.NonObjC; - case NodeKind.ImplFunctionAttribute: return SwiftTypeAttribute.ImplFunction; - case NodeKind.DirectMethodReferenceAttribute: return SwiftTypeAttribute.DirectMethodReference; - default: - throw new NotSupportedException ($"{Kind} is not an attribute"); - } - } - } +namespace SwiftReflector.Demangling +{ + public class Node + { + Node(NodeKind kind, PayloadKind payload) + { + Kind = kind; + PayloadKind = payload; + Children = new List(); + } + + public Node(NodeKind kind) + : this(kind, PayloadKind.None) + { + } + + public Node(NodeKind kind, string text) + : this(kind, PayloadKind.Text) + { + stringPayload = text; + } + + public Node(NodeKind kind, long index) + : this(kind, PayloadKind.Index) + { + indexPayload = index; + } + + string stringPayload = null; + long indexPayload = 0; + + public List Children { get; private set; } + + public NodeKind Kind { get; private set; } + public PayloadKind PayloadKind { get; private set; } + + public bool HasText { get { return PayloadKind == PayloadKind.Text; } } + public string Text + { + get + { + if (!HasText) + throw new InvalidOperationException($"Expected a text payload, but this has a {PayloadKind} payload"); + return stringPayload; + } + } + + public bool HasIndex { get { return PayloadKind == PayloadKind.Index; } } + public long Index + { + get + { + if (!HasIndex) + throw new InvalidOperationException($"Expected an index payload, but this has a {PayloadKind} payload"); + return indexPayload; + } + } + + public void AddChild(Node child) + { + Children.Add(child); + } + + public void RemoveChildAt(int pos) + { + Children.RemoveAt(pos); + } + + public void ReverseChildren(int startingAt = 0) + { + var last = Children.Count - 1; + if (startingAt < 0 || startingAt > Children.Count) + throw new ArgumentOutOfRangeException(nameof(startingAt)); + while (startingAt < last) + { + Node temp = Children[startingAt]; + Children[startingAt] = Children[last]; + Children[last] = temp; + startingAt++; + last--; + } + } + + + public static bool IsDeclName(NodeKind kind) + { + switch (kind) + { + case NodeKind.Identifier: + case NodeKind.LocalDeclName: + case NodeKind.PrivateDeclName: + case NodeKind.RelatedEntityDeclName: + case NodeKind.PrefixOperator: + case NodeKind.PostfixOperator: + case NodeKind.InfixOperator: + case NodeKind.TypeSymbolicReference: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + public static bool IsContext(NodeKind kind) + { + var type = typeof(NodeKind); + var memberInfo = type.GetMember(kind.ToString()); + var attrs = memberInfo[0].GetCustomAttributes(typeof(ContextAttribute), false); + return attrs != null && attrs.Length == 1; + } + + public static bool IsAnyGeneric(NodeKind kind) + { + switch (kind) + { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + case NodeKind.OtherNominalType: + case NodeKind.TypeAlias: + case NodeKind.TypeSymbolicReference: + return true; + default: + return false; + } + } + + public static bool IsNominal(NodeKind kind) + { + switch (kind) + { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + return true; + default: + return false; + } + } + + public static bool IsEntity(NodeKind kind) + { + if (kind == NodeKind.Type) + return true; + return IsContext(kind); + } + + public static bool IsRequirement(NodeKind kind) + { + switch (kind) + { + case NodeKind.DependentGenericSameTypeRequirement: + case NodeKind.DependentGenericLayoutRequirement: + case NodeKind.DependentGenericConformanceRequirement: + return true; + default: + return false; + } + } + + public static bool IsFunctionAttribute(NodeKind kind) + { + switch (kind) + { + case NodeKind.FunctionSignatureSpecialization: + case NodeKind.GenericSpecialization: + case NodeKind.InlinedGenericFunction: + case NodeKind.GenericSpecializationNotReAbstracted: + case NodeKind.GenericPartialSpecialization: + case NodeKind.GenericPartialSpecializationNotReAbstracted: + case NodeKind.ObjCAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.DirectMethodReferenceAttribute: + case NodeKind.VTableAttribute: + case NodeKind.PartialApplyForwarder: + case NodeKind.PartialApplyObjCForwarder: + case NodeKind.OutlinedVariable: + case NodeKind.OutlinedBridgedMethod: + case NodeKind.MergedFunction: + case NodeKind.DynamicallyReplaceableFunctionImpl: + case NodeKind.DynamicallyReplaceableFunctionKey: + case NodeKind.DynamicallyReplaceableFunctionVar: + return true; + default: + return false; + } + } + + public override string ToString() + { + var sb = new StringBuilder(); + ToString(0, sb); + return sb.ToString(); + } + + void ToString(int indent, StringBuilder sb) + { + for (int i = 0; i < indent; i++) + { + sb.Append(' '); + } + sb.Append("->").Append(Kind.ToString()); + switch (PayloadKind) + { + case PayloadKind.None: + sb.Append(Environment.NewLine); + break; + case PayloadKind.Index: + sb.Append($" ({Index})\n"); + break; + case PayloadKind.Text: + sb.Append($" (\"{Text}\")\n"); + break; + } + foreach (var node in Children) + { + node.ToString(indent + 2, sb); + } + } + + public bool IsAttribute() + { + switch (Kind) + { + case NodeKind.ObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.ImplFunctionAttribute: + case NodeKind.DirectMethodReferenceAttribute: + return true; + default: + return false; + } + } + + public SwiftTypeAttribute ExtractAttribute() + { + switch (Kind) + { + case NodeKind.ObjCAttribute: return SwiftTypeAttribute.ObjC; + case NodeKind.DynamicAttribute: return SwiftTypeAttribute.Dynamic; + case NodeKind.NonObjCAttribute: return SwiftTypeAttribute.NonObjC; + case NodeKind.ImplFunctionAttribute: return SwiftTypeAttribute.ImplFunction; + case NodeKind.DirectMethodReferenceAttribute: return SwiftTypeAttribute.DirectMethodReference; + default: + throw new NotSupportedException($"{Kind} is not an attribute"); + } + } + } } diff --git a/src/SwiftReflector/Demangling/RuleRunner.cs b/src/SwiftReflector/Demangling/RuleRunner.cs index 380d1c3dfe26..717102fe3e37 100644 --- a/src/SwiftReflector/Demangling/RuleRunner.cs +++ b/src/SwiftReflector/Demangling/RuleRunner.cs @@ -5,19 +5,21 @@ using System.Collections.Generic; using System.Linq; -namespace SwiftReflector.Demangling { - public class RuleRunner { - List rules = new List (); - public RuleRunner (IEnumerable rules) - { - this.rules.AddRange (rules); - } +namespace SwiftReflector.Demangling +{ + public class RuleRunner + { + List rules = new List(); + public RuleRunner(IEnumerable rules) + { + this.rules.AddRange(rules); + } - public SwiftType RunRules(Node node, bool isReference, SwiftName name) - { - var rule = rules.FirstOrDefault (r => r.Matches (node)); + public SwiftType RunRules(Node node, bool isReference, SwiftName name) + { + var rule = rules.FirstOrDefault(r => r.Matches(node)); - return rule != null ? rule.Reducer (node, isReference, name) : null; - } - } + return rule != null ? rule.Reducer(node, isReference, name) : null; + } + } } diff --git a/src/SwiftReflector/Demangling/Swift5Demangler.cs b/src/SwiftReflector/Demangling/Swift5Demangler.cs index 364025118398..a9e4a47ef17a 100644 --- a/src/SwiftReflector/Demangling/Swift5Demangler.cs +++ b/src/SwiftReflector/Demangling/Swift5Demangler.cs @@ -8,2949 +8,3224 @@ // This is a port of the Apple Swift 5 demangler -namespace SwiftReflector.Demangling { - public class Swift5Demangler { - ulong offset; - string originalIdentifier; - Stack nodeStack = new Stack (); - List substitutions = new List (); - string text; - List words = new List (); - StringSlice slice; - bool isOldFunctionTypeMangling = false; - - public Func SymbolicReferenceResolver { get; set; } - - static string [] prefixes = { +namespace SwiftReflector.Demangling +{ + public class Swift5Demangler + { + ulong offset; + string originalIdentifier; + Stack nodeStack = new Stack(); + List substitutions = new List(); + string text; + List words = new List(); + StringSlice slice; + bool isOldFunctionTypeMangling = false; + + public Func SymbolicReferenceResolver { get; set; } + + static string[] prefixes = { /*Swift 4*/ "_T0", /*Swift 4.x*/ "$S", "_$S", /*Swift 5+*/ "$s", "_$s" - }; - - Swift5Demangler () - { - } - - - public Swift5Demangler (string mangledName, ulong offset = 0) - { - originalIdentifier = mangledName; - this.offset = offset; - slice = new StringSlice (originalIdentifier); - slice.Advance (GetManglingPrefixLength (originalIdentifier)); - } - - public TLDefinition Run () - { - Node topLevelNode = DemangleType (null); - if (topLevelNode != null && topLevelNode.IsAttribute () && nodeStack.Count >= 1) { - var attribute = topLevelNode.ExtractAttribute (); - var tld = Run (); - if (tld != null && tld is TLFunction tlf) { - tlf.Signature.Attributes.Add (attribute); - } - return tld; - } else { - Swift5NodeToTLDefinition converter = new Swift5NodeToTLDefinition (originalIdentifier, offset); - return converter.Convert (topLevelNode); - } - } - - bool NextIf (string str) - { - if (slice.StartsWith (str)) { - slice.Advance (str.Length); - return true; - } - return false; - - } - - char PeekChar () - { - if (slice.IsAtEnd) - return (char)0; - return slice.Current; - } - - char NextChar () - { - return slice.Advance (); - } - - bool NextIf (char c) - { - return slice.AdvanceIfEquals (c); - } - - void PushBack () - { - slice.Rewind (); - } - - string ConsumeAll () - { - return slice.ConsumeRemaining (); - } - - void PushNode (Node node) - { - nodeStack.Push (node); - } - - Node PopNode () - { - if (nodeStack.Count == 0) - return null; - return nodeStack.Pop (); - } - - Node PopNode (NodeKind kind) - { - if (nodeStack.Count == 0) - return null; - if (kind != nodeStack.Peek ().Kind) - return null; - return PopNode (); - } - - Node PopNode (Predicate pred) - { - if (nodeStack.Count == 0) - return null; - if (!pred (nodeStack.Peek ().Kind)) - return null; - return PopNode (); - } - - void AddSubstitution (Node nd) - { - if (nd != null) - substitutions.Add (nd); - } - - Node CreateWithPoppedType (NodeKind kind) - { - return CreateWithChild (kind, PopNode (NodeKind.Type)); - } - - - // beginning of swift 5 demangler port - - static bool IsDeclName (NodeKind kind) - { - switch (kind) { - case NodeKind.Identifier: - case NodeKind.LocalDeclName: - case NodeKind.PrivateDeclName: - case NodeKind.RelatedEntityDeclName: - case NodeKind.PrefixOperator: - case NodeKind.PostfixOperator: - case NodeKind.InfixOperator: - case NodeKind.TypeSymbolicReference: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsContext (NodeKind node) - { - var type = typeof (NodeKind); - var memInfo = type.GetMember (node.ToString ()); - return memInfo [0].GetCustomAttributes (typeof (ContextAttribute), false).Length > 0; - } - - static bool IsAnyGeneric (NodeKind kind) - { - switch (kind) { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - case NodeKind.OtherNominalType: - case NodeKind.TypeAlias: - case NodeKind.TypeSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsEntity (NodeKind kind) - { - if (kind == NodeKind.Type) - return true; - return IsContext (kind); - } - - static bool IsRequirement (NodeKind kind) - { - switch (kind) { - case NodeKind.DependentGenericSameTypeRequirement: - case NodeKind.DependentGenericLayoutRequirement: - case NodeKind.DependentGenericConformanceRequirement: - return true; - default: - return false; - } - } - - static bool IsFunctionAttr (NodeKind kind) - { - switch (kind) { - case NodeKind.FunctionSignatureSpecialization: - case NodeKind.GenericSpecialization: - case NodeKind.InlinedGenericFunction: - case NodeKind.GenericSpecializationNotReAbstracted: - case NodeKind.GenericPartialSpecialization: - case NodeKind.GenericPartialSpecializationNotReAbstracted: - case NodeKind.ObjCAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.DirectMethodReferenceAttribute: - case NodeKind.VTableAttribute: - case NodeKind.PartialApplyForwarder: - case NodeKind.PartialApplyObjCForwarder: - case NodeKind.OutlinedVariable: - case NodeKind.OutlinedBridgedMethod: - case NodeKind.MergedFunction: - case NodeKind.DynamicallyReplaceableFunctionImpl: - case NodeKind.DynamicallyReplaceableFunctionKey: - case NodeKind.DynamicallyReplaceableFunctionVar: - return true; - default: - return false; - } - } - - int GetManglingPrefixLength (string mangledName) - { - if (string.IsNullOrEmpty (mangledName)) - return 0; - foreach (var prefix in prefixes) { - mangledName.StartsWith (prefix, StringComparison.Ordinal); - return prefix.Length; - } - return 0; - } - - bool IsSwiftSymbol (string mangledName) - { - if (IsOldFunctionTypeMangling (mangledName)) - return true; - return GetManglingPrefixLength (mangledName) != 0; - } - - bool IsObjCSymbol (string mangledName) - { - var nameWithoutPrefix = DropSwiftManglingPrefix (mangledName); - return nameWithoutPrefix.StartsWith ("So", StringComparison.Ordinal) || nameWithoutPrefix.StartsWith ("Sc", StringComparison.Ordinal); - } - - bool IsOldFunctionTypeMangling (string mangledName) - { - return mangledName.StartsWith ("_T", StringComparison.Ordinal); - } - - string DropSwiftManglingPrefix (string mangledName) - { - return mangledName.Substring (GetManglingPrefixLength (mangledName)); - } - - static bool IsAliasNode (Node node) - { - switch (node.Kind) { - case NodeKind.Type: - return IsAliasNode (node.Children [0]); - case NodeKind.TypeAlias: - return true; - default: - return false; - } - } - - static bool IsAlias (string mangledName) - { - return IsAliasNode (new Swift5Demangler ().DemangleType (mangledName)); - } - - static bool IsClassNode (Node node) - { - switch (node.Kind) { - case NodeKind.Type: - return IsClassNode (node.Children [0]); - case NodeKind.Class: - case NodeKind.BoundGenericClass: - return true; - default: - return false; - } - } - - static bool IsClass (string mangledName) - { - return IsClassNode (new Swift5Demangler ().DemangleType (mangledName)); - } - - static bool IsEnumNode (Node node) - { - switch (node.Kind) { - case NodeKind.Type: - return IsEnumNode (node.Children [0]); - case NodeKind.Enum: - case NodeKind.BoundGenericEnum: - return true; - default: - return false; - } - } - - static bool IsEnum (string mangledName) - { - return IsEnumNode (new Swift5Demangler ().DemangleType (mangledName)); - } - - static bool IsProtocolNode (Node node) - { - switch (node.Kind) { - case NodeKind.Type: - return IsProtocolNode (node.Children [0]); - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsProtocol (string mangledName) - { - return IsProtocolNode (new Swift5Demangler ().DemangleType (mangledName)); - } - - static bool IsStructNode (Node node) - { - switch (node.Kind) { - case NodeKind.Type: - return IsStructNode (node.Children [0]); - case NodeKind.Structure: - case NodeKind.BoundGenericStructure: - return true; - default: - return false; - } - } - - static bool IsStruct (string mangledName) - { - return IsStructNode (new Swift5Demangler ().DemangleType (mangledName)); - } - - - - - void Clear () - { - nodeStack.Clear (); - substitutions.Clear (); - } - - void Init (string mangledName) - { - nodeStack = new Stack (); - substitutions = new List (); - words = new List (); - if (mangledName != null) { - text = mangledName; - slice = new StringSlice (mangledName); - } - } - - public Node DemangleSymbol (string mangledName) - { - Init (mangledName); - - if (NextIf ("_Tt")) - return DemangleObjCTypeName (); - - var prefixLength = GetManglingPrefixLength (mangledName); - if (prefixLength == 0) - return null; - isOldFunctionTypeMangling = IsOldFunctionTypeMangling (mangledName); - slice.Advance (prefixLength); - - if (!ParseAndPushNodes ()) - return null; - - var topLevel = new Node (NodeKind.Global); - var parent = topLevel; - Node funcAttr = null; - while ((funcAttr = PopNode (IsFunctionAttr)) != null) { - parent.AddChild (funcAttr); - if (funcAttr.Kind == NodeKind.PartialApplyForwarder || funcAttr.Kind == NodeKind.PartialApplyObjCForwarder) - parent = funcAttr; - foreach (var nd in nodeStack) { - switch (nd.Kind) { - case NodeKind.Type: - parent.AddChild (nd.Children [0]); - break; - default: - parent.AddChild (nd); - break; - } - } - } - if (topLevel.Children.Count == 0) - return null; - - return topLevel; - } - - Node DemangleType (string mangledName) - { - Init (mangledName); - - ParseAndPushNodes (); - - var result = PopNode (); - if (result != null) - return result; - - return new Node (NodeKind.Suffix, text); - } - - bool ParseAndPushNodes () - { - var idx = 0; - while (!slice.IsAtEnd) { - var node = DemangleOperator (); - if (node == null) - return false; - PushNode (node); - idx++; - } - return true; - } - - Node AddChild (Node parent, Node child) - { - if (parent == null || child == null) - return null; - parent.Children.Add (child); - return parent; - } - - Node CreateWithChild (NodeKind kind, Node child) - { - if (child == null) - return null; - var node = new Node (kind); - node.Children.Add (child); - return node; - } - - Node CreateType (Node child) - { - return CreateWithChild (NodeKind.Type, child); - } - - Node CreateWithChildren (NodeKind kind, params Node [] children) - { - foreach (var nd in children) - if (nd == null) - throw new ArgumentOutOfRangeException (nameof (children)); - var node = new Node (kind); - node.Children.AddRange (children); - return node; - } - - Node ChangeKind (Node node, NodeKind newKind) - { - Node newNode = null; - if (node.HasText) { - newNode = new Node (newKind, node.Text); - } else if (node.HasIndex) { - newNode = new Node (newKind, node.Index); - } else { - newNode = new Node (newKind); - } - newNode.Children.AddRange (node.Children); - return newNode; - } - - Node DemangleTypeMangling () - { - var type = PopNode (NodeKind.Type); - var labelList = PopFunctionParamLabels (type); - var typeMangling = new Node (NodeKind.TypeMangling); - - AddChild (typeMangling, labelList); - typeMangling = AddChild (typeMangling, type); - return typeMangling; - } - - Node DemangleSymbolicReference (int rawKind) - { - var data = new byte [4]; - for (int i = 0; i < 4; i++) { - data [i] = (byte)NextChar (); - } - var value = BitConverter.ToInt32 (data, 0); - - SymbolicReferenceKind kind; - Directness direct; - switch (rawKind) { - case 1: - kind = SymbolicReferenceKind.Context; - direct = Directness.Direct; - break; - case 2: - kind = SymbolicReferenceKind.Context; - direct = Directness.Indirect; - break; - default: - return null; - } - - Node resolved = null; - if (SymbolicReferenceResolver != null) { - resolved = SymbolicReferenceResolver (kind, direct, value, data); - } - if (resolved == null) - return null; - - if (kind == SymbolicReferenceKind.Context) - AddSubstitution (resolved); - return resolved; - } - - Node DemangleOperator () - { - var c = NextChar (); - switch (c) { - case '\x01': - case '\x02': - case '\x03': - case '\x04': - return DemangleSymbolicReference (c); - case 'A': return DemangleMultiSubstitutions (); - case 'B': return DemangleBuiltinType (); - case 'C': return DemangleAnyGenericType (NodeKind.Class); - case 'D': return DemangleTypeMangling (); - case 'E': return DemangleExtensionContext (); - case 'F': return DemanglePlainFunction (); - case 'G': return DemangleBoundGenericType (); - case 'H': - var c2 = NextChar (); - switch (c2) { - case 'A': return DemangleDependentProtocolConformanceAssociated (); - case 'C': return DemangleConcreteProtocolConformance (); - case 'D': return DemangleDependentProtocolConformanceRoot (); - case 'I': return DemangleDependentProtocolConformanceInherited (); - case 'P': - return CreateWithChild (NodeKind.ProtocolConformanceRefInTypeModule, PopProtocol ()); - case 'p': - return CreateWithChild (NodeKind.ProtocolConformanceRefInProtocolModule, PopProtocol ()); - default: - PushBack (); - PushBack (); - return DemangleIdentifier (); - } - case 'I': return DemangleImplFunctionType (); - case 'K': return new Node (NodeKind.ThrowsAnnotation); - case 'L': return DemangleLocalIdentifier (); - case 'M': return DemangleMetatype (); - case 'N': return CreateWithChild (NodeKind.TypeMetadata, PopNode (NodeKind.Type)); - case 'O': return DemangleAnyGenericType (NodeKind.Enum); - case 'P': return DemangleAnyGenericType (NodeKind.Protocol); - case 'Q': return DemangleArchetype (); - case 'R': return DemangleGenericRequirement (); - case 'S': return DemangleStandardSubstitution (); - case 'T': return DemangleThunkOrSpecialization (); - case 'V': return DemangleAnyGenericType (NodeKind.Structure); - case 'W': return DemangleWitness (); - case 'X': return DemangleSpecialType (); - case 'Z': return CreateWithChild (NodeKind.Static, PopNode (IsEntity)); - case 'a': return DemangleAnyGenericType (NodeKind.TypeAlias); - case 'c': return PopFunctionType (NodeKind.FunctionType); - case 'd': return new Node (NodeKind.VariadicMarker); - case 'f': return DemangleFunctionEntity (); - case 'g': return DemangleRetroactiveConformance (); - case 'h': return CreateType (CreateWithChild (NodeKind.Shared, PopTypeAndGetChild ())); - case 'i': return DemangleSubscript (); - case 'l': return DemangleGenericSignature (false); - case 'm': return CreateType (CreateWithChild (NodeKind.Metatype, PopNode (NodeKind.Type))); - case 'n': return CreateType (CreateWithChild (NodeKind.Owned, PopTypeAndGetChild ())); - case 'o': return DemangleOperatorIdentifier (); - case 'p': return DemangleProtocolListType (); - case 'q': return CreateType (DemangleGenericParamIndex ()); - case 'r': return DemangleGenericSignature (true); - case 's': return new Node (NodeKind.Module, "Swift"); - case 't': return PopTuple (); - case 'u': return DemangleGenericType (); - case 'v': return DemangleVariable (); - case 'w': return DemangleValueWitness (); - case 'x': return CreateType (GetDependentGenericParamType (0, 0)); - case 'y': return new Node (NodeKind.EmptyList); - case 'z': return CreateType (CreateWithChild (NodeKind.InOut, PopTypeAndGetChild ())); - case '_': return new Node (NodeKind.FirstElementMarker); - case '.': - PushBack (); - return new Node (NodeKind.Suffix, slice.ConsumeRemaining ()); - default: - PushBack (); - return DemangleIdentifier (); - } - } - - int DemangleNatural () - { - if (!Char.IsDigit (slice.Current)) - return -1000; - var num = 0; - while (true) { - var c = slice.Current; - if (!Char.IsDigit (c)) - return num; - var newNum = (10 * num) + (c - '0'); - if (newNum < num) - return -1000; - num = newNum; - NextChar (); - } - } - - int DemangleIndex () - { - if (NextIf ('_')) - return 0; - var num = DemangleNatural (); - if (num >= 0 && NextIf ('_')) - return num + 1; - return -1000; - } - - - Node DemangleIndexAsNode () - { - var idx = DemangleIndex (); - if (idx >= 0) - return new Node (NodeKind.Number, idx); - return null; - } - - Node DemangleMultiSubstitutions () - { - var repeatCount = 1; - while (true) { - if (slice.IsAtEnd) - return null; - var c = NextChar (); - if (Char.IsLower (c)) { - var nd = PushMultiSubstitutions (repeatCount, c - 'a'); - if (nd == null) - return null; - PushNode (nd); - repeatCount = -1; - continue; - } - if (Char.IsUpper (c)) { - return PushMultiSubstitutions (repeatCount, c - 'A'); - } - if (c == '_') { - var idx = repeatCount + 27; - if (idx >= substitutions.Count) - return null; - return substitutions [idx]; - } - PushBack (); - repeatCount = DemangleNatural (); - if (repeatCount < 0) - return null; - } - } - - Node PushMultiSubstitutions (int repeatCount, int substIdx) - { - if (substIdx >= substitutions.Count) - return null; - var nd = substitutions [substIdx]; - while (repeatCount-- > 1) { - PushNode (nd); - } - return nd; - } - - Node CreateSwiftType (NodeKind typeKind, string name) - { - return CreateType (CreateWithChildren (typeKind, new Node (NodeKind.Module, "Swift"), new Node (NodeKind.Identifier, name))); - } - - Node DemangleStandardSubstitution () - { - var c = NextChar (); - switch (c) { - case 'o': - return new Node (NodeKind.Module, "__C"); - case 'C': - return new Node (NodeKind.Module, "__C_Synthesized"); - case 'g': { - var optionalTy = CreateType (CreateWithChildren (NodeKind.BoundGenericEnum, - CreateSwiftType (NodeKind.Enum, "Optional"), - CreateWithChild (NodeKind.TypeList, PopNode (NodeKind.Type)))); - AddSubstitution (optionalTy); - return optionalTy; - } - default: - PushBack (); - Node nd; - var repeatCount = DemangleNatural (); - if ((nd = CreateStandardSubstitution (NextChar ())) != null) { - while (repeatCount-- > 1) { - PushNode (nd); - } - return nd; - } - return null; - } - } - - Node CreateStandardSubstitution (char subst) - { - var kind = NodeKind.Structure; - string name = null; - switch (subst) { - case 'A': name = "AutoreleasingUnsafeMutablePointer"; break; - case 'a': name = "Array"; break; - case 'b': name = "Bool"; break; - case 'c': name = "UnicodeScalar"; break; - case 'D': name = "Dictionary"; break; - case 'd': name = "Double"; break; - case 'f': name = "Float"; break; - case 'h': name = "Set"; break; - case 'I': name = "DefaultIndicies"; break; - case 'i': name = "Int"; break; - case 'J': name = "Character"; break; - case 'N': name = "ClosedRange"; break; - case 'n': name = "Range"; break; - case 'O': name = "ObjectIdentifier"; break; - case 'P': name = "UnsafePointer"; break; - case 'p': name = "UnsafeMutablePointer"; break; - case 'R': name = "UnsafeBufferPointer"; break; - case 'r': name = "UnsafeMutableBufferPointer"; break; - case 'S': name = "String"; break; - case 's': name = "Substring"; break; - case 'u': name = "UInt"; break; - case 'V': name = "UnsafeRawPointer"; break; - case 'v': name = "UnsafeMutableRawPointer"; break; - case 'W': name = "UnsafeRawBufferPointer"; break; - case 'w': name = "UnsafeMutableRawBufferPointer"; break; - - case 'q': name = "Optional"; kind = NodeKind.Enum; break; - - case 'B': name = "BinaryFloatingPoint"; kind = NodeKind.Protocol; break; - case 'E': name = "Encodable"; kind = NodeKind.Protocol; break; - case 'e': name = "Decodable"; kind = NodeKind.Protocol; break; - case 'F': name = "FloatingPoint"; kind = NodeKind.Protocol; break; - case 'G': name = "RandomNumberGenerator"; kind = NodeKind.Protocol; break; - case 'H': name = "Hashable"; kind = NodeKind.Protocol; break; - case 'j': name = "Numeric"; kind = NodeKind.Protocol; break; - case 'K': name = "BidirectionalCollection"; kind = NodeKind.Protocol; break; - case 'k': name = "RandomAccessCollection"; kind = NodeKind.Protocol; break; - case 'L': name = "Comparable"; kind = NodeKind.Protocol; break; - case 'l': name = "Collection"; kind = NodeKind.Protocol; break; - case 'M': name = "MutableCollection"; kind = NodeKind.Protocol; break; - case 'm': name = "RangeReplaceableCollection"; kind = NodeKind.Protocol; break; - case 'Q': name = "Equatable"; kind = NodeKind.Protocol; break; - case 'T': name = "Sequence"; kind = NodeKind.Protocol; break; - case 't': name = "IteratorProtocol"; kind = NodeKind.Protocol; break; - case 'U': name = "UnsignedInteger"; kind = NodeKind.Protocol; break; - case 'X': name = "RangeExpression"; kind = NodeKind.Protocol; break; - case 'x': name = "Strideable"; kind = NodeKind.Protocol; break; - case 'Y': name = "RawRepresentable"; kind = NodeKind.Protocol; break; - case 'y': name = "StringProtocol"; kind = NodeKind.Protocol; break; - case 'Z': name = "SignedInteger"; kind = NodeKind.Protocol; break; - case 'z': name = "BinaryInteger"; kind = NodeKind.Protocol; break; - default: - return null; - } - - return CreateSwiftType (kind, name); - } - - Node DemangleIdentifier () - { - var hasWordSubsts = false; - var isPunycoded = false; - var c = PeekChar (); - if (!Char.IsDigit (c)) - return null; - if (c == '0') { - NextChar (); - if (PeekChar () == '0') { - NextChar (); - isPunycoded = true; - } else { - hasWordSubsts = true; - } - } - var identifier = new StringBuilder (); - do { - while (hasWordSubsts && Char.IsLetter (PeekChar ())) { - var cc = NextChar (); - var wordIdx = 0; - if (Char.IsLower (cc)) { - wordIdx = cc - 'a'; - } else { - wordIdx = cc - 'A'; - hasWordSubsts = false; - } - if (wordIdx >= words.Count) - return null; - string piece0 = words [wordIdx]; - identifier.Append (piece0); - } - if (NextIf ('0')) - break; - var numChars = DemangleNatural (); - if (numChars <= 0) - return null; - if (isPunycoded) - NextIf ('_'); - if (numChars > slice.Length) - return null; - string piece = slice.Substring (slice.Position, numChars); - if (isPunycoded) { - PunyCode puny = new PunyCode (); - string punyCodedString = puny.Decode (piece); - identifier.Append (punyCodedString); - } else { - identifier.Append (piece); - var wordStartPos = -1; - for (int idx = 0; idx <= piece.Length; idx++) { - char ccc = idx < piece.Length ? piece [idx] : (char)0; - if (wordStartPos >= 0 && IsWordEnd (ccc, piece [idx - 1])) { - if (idx - wordStartPos >= 2 && words.Count < 26) { - var word = piece.Substring (wordStartPos, idx - wordStartPos); - words.Add (word); - } - wordStartPos = -1; - } - if (wordStartPos < 0 && IsWordStart (ccc)) { - wordStartPos = idx; - } - } - } - slice.Advance (numChars); - } while (hasWordSubsts); - if (identifier.Length == 0) - return null; - var ident = new Node (NodeKind.Identifier, identifier.ToString ()); - AddSubstitution (ident); - return ident; - } - - bool IsWordStart (char ch) - { - return !Char.IsDigit (ch) && ch != '_' && ch != (char)0; - } - - bool IsWordEnd (char ch, char prevCh) - { - if (ch == '_' || ch == (char)0) - return true; - if (!Char.IsUpper (prevCh) && Char.IsUpper (ch)) - return true; - return false; - } - - - Node DemangleOperatorIdentifier () - { - var ident = PopNode (NodeKind.Identifier); - if (ident == null) - return null; - var op_char_table = "& @/= > <*!|+?%-~ ^ ."; - StringBuilder opStr = new StringBuilder (); - foreach (var c in ident.Text) { - if (c > 0x7f) { - opStr.Append (c); - continue; - } - if (!Char.IsLower (c)) - return null; - char o = op_char_table [c - 'a']; - if (o == ' ') - return null; - opStr.Append (o); - } - switch (NextChar ()) { - case 'i': return new Node (NodeKind.InfixOperator, opStr.ToString ()); - case 'p': return new Node (NodeKind.PrefixOperator, opStr.ToString ()); - case 'P': return new Node (NodeKind.PostfixOperator, opStr.ToString ()); - default: return null; - } - } - - - Node DemangleLocalIdentifier () - { - if (NextIf ('L')) { - var discriminator = PopNode (NodeKind.Identifier); - var name = PopNode (IsDeclName); - return CreateWithChildren (NodeKind.PrivateDeclName, discriminator, name); - } - if (NextIf ('l')) { - var discriminator = PopNode (NodeKind.Identifier); - return CreateWithChild (NodeKind.PrivateDeclName, discriminator); - } - if ((PeekChar () >= 'a' && PeekChar () <= 'j') || - (PeekChar () >= 'A' && PeekChar () <= 'J')) { - var relatedEntityKind = NextChar (); - var name = PopNode (); - var result = new Node (NodeKind.RelatedEntityDeclName, relatedEntityKind.ToString ()); - return AddChild (result, name); - } - var discriminatorx = DemangleIndexAsNode (); - var namex = PopNode (IsDeclName); - return CreateWithChildren (NodeKind.LocalDeclName, discriminatorx, namex); - } - - Node PopModule () - { - var ident = PopNode (NodeKind.Identifier); - if (ident != null) - return ChangeKind (ident, NodeKind.Module); - return PopNode (NodeKind.Module); - } - - Node PopContext () - { - var mod = PopModule (); - if (mod != null) - return mod; - - var ty = PopNode (NodeKind.Type); - if (ty != null) { - if (ty.Children.Count != 1) - return null; - var child = ty.Children [0]; - if (!IsContext (child.Kind)) - return null; - return child; - } - return PopNode (IsContext); - } - - Node PopTypeAndGetChild () - { - var ty = PopNode (NodeKind.Type); - if (ty == null || ty.Children.Count != 1) - return null; - return ty.Children [0]; - } - - - Node PopTypeAndGetAnyGeneric () - { - var child = PopTypeAndGetChild (); - if (child != null && IsAnyGeneric (child.Kind)) - return child; - return null; - } - - Node DemangleBuiltinType () - { - Node ty = null; - const int maxTypeSize = 4096; - switch (NextChar ()) { - case 'b': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); - break; - case 'B': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); - break; - case 'f': { - var size = DemangleIndex () - 1; - if (size <= 0 || size > maxTypeSize) - return null; - var floatName = $"Builtin.FPIEEE{size}"; - ty = new Node (NodeKind.BuiltinTypeName, floatName); - break; - } - case 'i': { - var size = DemangleIndex () - 1; - if (size < 0 || size > maxTypeSize) - return null; - var intName = $"Builtin.Int{size}"; - ty = new Node (NodeKind.BuiltinTypeName, intName); - break; - } - case 'I': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.IntLiteral"); - break; - case 'v': - var elts = DemangleIndex () - 1; - if (elts <= 0 || elts > maxTypeSize) - return null; - var eltType = PopTypeAndGetChild (); - if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || - !eltType.Text.StartsWith ("Builtin.", StringComparison.Ordinal)) - return null; - var name = $"Builtin.Vec{elts}x{eltType.Text.Substring ("Builtin.".Length)}"; - ty = new Node (NodeKind.BuiltinTypeName, name); - break; - case 'O': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); - break; - case 'o': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.NativeObject"); - break; - case 'p': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.RawPointer"); - break; - case 't': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.SILToken"); - break; - case 'w': - ty = new Node (NodeKind.BuiltinTypeName, "Builtin.Word"); - break; - default: - return null; - } - return CreateType (ty); - } - - Node DemangleAnyGenericType (NodeKind kind) - { - var name = PopNode (IsDeclName); - var ctx = PopContext (); - var nty = CreateType (CreateWithChildren (kind, ctx, name)); - AddSubstitution (nty); - return nty; - } - - Node DemangleExtensionContext () - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var module = PopModule (); - var type = PopTypeAndGetAnyGeneric (); - var ext = CreateWithChildren (NodeKind.Extension, module, type); - if (genSig != null) - ext = AddChild (ext, genSig); - return ext; - } - - Node DemanglePlainFunction () - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var type = PopFunctionType (NodeKind.FunctionType); - var labelList = PopFunctionParamLabels (type); - - if (genSig != null) { - type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); - } - - var name = PopNode (IsDeclName); - var ctx = PopContext (); - - if (labelList != null) - return CreateWithChildren (NodeKind.Function, ctx, name, labelList, type); - return CreateWithChildren (NodeKind.Function, ctx, name, type); - } - - - Node PopFunctionType (NodeKind kind) - { - var funcType = new Node (kind); - AddChild (funcType, PopNode (NodeKind.ThrowsAnnotation)); - funcType = AddChild (funcType, PopFunctionParams (NodeKind.ArgumentTuple)); - funcType = AddChild (funcType, PopFunctionParams (NodeKind.ReturnType)); - return CreateType (funcType); - } - - Node PopFunctionParams (NodeKind kind) - { - Node paramsType = null; - if (PopNode (NodeKind.EmptyList) != null) { - paramsType = CreateType (new Node (NodeKind.Tuple)); - } else { - paramsType = PopNode (NodeKind.Type); - } - Node node = null; - - if (paramsType != null && kind == NodeKind.ArgumentTuple) { - var @params = paramsType.Children [0]; - var numParams = @params.Kind == NodeKind.Tuple ? @params.Children.Count : 1; - node = new Node (kind, numParams); - } else { - node = new Node (kind); - } - - return AddChild (node, paramsType); - } - - Node PopFunctionParamLabels (Node type) - { - if (!isOldFunctionTypeMangling && PopNode (NodeKind.EmptyList) != null) - return new Node (NodeKind.LabelList); - - if (type == null || type.Kind != NodeKind.Type) - return null; - - var funcType = type.Children [0]; - if (funcType.Kind == NodeKind.DependentGenericType) - funcType = funcType.Children [1].Children [0]; - - if (funcType.Kind != NodeKind.FunctionType && funcType.Kind != NodeKind.NoEscapeFunctionType) - return null; - - var parameterType = funcType.Children [0]; - if (parameterType.Kind == NodeKind.ThrowsAnnotation) - parameterType = funcType.Children [1]; - - - if (parameterType.Index == 0) - return null; - - Func> getChildIf = (node, filterBy) => { - for (int i = 0, n = node.Children.Count; i != n; ++i) { - var child = node.Children [i]; - if (child.Kind == filterBy) - return new KeyValuePair (child, i); - } - return new KeyValuePair (null, 0); - }; - - Func getLabel = (@params, idx) => { - if (isOldFunctionTypeMangling) { - var param = @params.Children [idx]; - var label = getChildIf (param, NodeKind.TupleElementName); - - if (label.Key != null) { - param.RemoveChildAt (label.Value); - return new Node (NodeKind.Identifier, label.Key.Text); - } - return new Node (NodeKind.FirstElementMarker); - } - return PopNode (); - }; - - var labelList = new Node (NodeKind.LabelList); - var tuple = parameterType.Children [0].Children [0]; - - if (isOldFunctionTypeMangling && (tuple != null || tuple.Kind != NodeKind.Tuple)) - return labelList; - - var hasLabels = false; - for (int i = 0; i != parameterType.Index; ++i) { - var label = getLabel (tuple, i); - if (label == null) - return null; - - if (label.Kind != NodeKind.Identifier && label.Kind != NodeKind.FirstElementMarker) - return null; - - labelList.AddChild (label); - hasLabels |= label.Kind != NodeKind.FirstElementMarker; - } - - if (!hasLabels) - return new Node (NodeKind.LabelList); - - if (!isOldFunctionTypeMangling) - labelList.ReverseChildren (); - - return labelList; - } - - Node PopTuple () - { - var root = new Node (NodeKind.Tuple); - - if (PopNode (NodeKind.EmptyList) == null) { - var firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker)) != null; - var tupleElmt = new Node (NodeKind.TupleElement); - AddChild (tupleElmt, PopNode (NodeKind.VariadicMarker)); - Node ident; - if ((ident = PopNode (NodeKind.Identifier)) != null) { - tupleElmt.AddChild (new Node (NodeKind.TupleElementName, ident.Text)); - } - var ty = PopNode (NodeKind.Type); - if (ty == null) - return null; - tupleElmt.AddChild (ty); - root.AddChild (tupleElmt); - } while (!firstElem); - - root.ReverseChildren (); - } - return CreateType (root); - } - - Node PopTypeList () - { - var root = new Node (NodeKind.TypeList); - - if (PopNode (NodeKind.EmptyList) == null) { - var firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker) != null); - var ty = PopNode (NodeKind.Type); - if (ty == null) - return ty; - root.AddChild (ty); - } while (!firstElem); - root.ReverseChildren (); - } - return root; - } - - Node PopProtocol () - { - Node type; - if ((type = PopNode (NodeKind.Type)) != null) { - if (type.Children.Count < 1) - return null; - - if (!IsProtocolNode (type)) - return null; - return type; - } - - Node symbolicRef; - if ((symbolicRef = PopNode (NodeKind.ProtocolSymbolicReference)) != null) { - return symbolicRef; - } - - var name = PopNode (IsDeclName); - var ctx = PopContext (); - var proto = CreateWithChildren (NodeKind.Protocol, ctx, name); - return CreateType (proto); - } - - Node PopAnyProtocolConformanceList () - { - var conformanceList = new Node (NodeKind.AnyProtocolConformanceList); - if (PopNode (NodeKind.EmptyList) == null) { - var firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker) != null); - var anyConformance = PopAnyProtocolConformance (); - if (anyConformance == null) - return null; - conformanceList.AddChild (anyConformance); - } while (!firstElem); - conformanceList.ReverseChildren (); - } - return conformanceList; - } - - Node PopAnyProtocolConformance () - { - return PopNode ((kind) => { - switch (kind) { - case NodeKind.ConcreteProtocolConformance: - case NodeKind.DependentProtocolConformanceRoot: - case NodeKind.DependentProtocolConformanceInherited: - case NodeKind.DependentProtocolConformanceAssociated: - return true; - default: - return false; - } - }); - } - - Node DemangleRetroactiveProtocolConformanceRef () - { - var module = PopModule (); - var proto = PopProtocol (); - var protocolConformanceRef = CreateWithChildren (NodeKind.ProtocolConformanceRefInOtherModule, proto, module); - return protocolConformanceRef; - } - - Node DemangleConcreteProtocolConformance () - { - var conditionalConformanceList = PopAnyProtocolConformanceList (); - - var conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInTypeModule); - if (conformanceRef == null) { - conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInProtocolModule); - } - if (conformanceRef == null) - conformanceRef = DemangleRetroactiveProtocolConformanceRef (); - - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.ConcreteProtocolConformance, - type, conformanceRef, conditionalConformanceList); - } - - - Node DemangleProtocolConformance () - { - var conditionalConformanceList = PopAnyProtocolConformanceList (); - - var conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInTypeModule); - if (conformanceRef == null) { - conformanceRef = PopNode (NodeKind.ProtocolConformanceRefInProtocolModule); - } - - if (conformanceRef == null) - conformanceRef = DemangleRetroactiveProtocolConformanceRef (); - - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.ConcreteProtocolConformance, type, conformanceRef, conditionalConformanceList); - } - - Node PopDependentProtocolConformance () - { - return PopNode ((kind) => { - switch (kind) { - case NodeKind.DependentProtocolConformanceRoot: - case NodeKind.DependentProtocolConformanceInherited: - case NodeKind.DependentProtocolConformanceAssociated: - return true; - default: - return false; - } - }); - } - - Node DemangleDependentProtocolConformanceRoot () - { - var index = DemangleIndex (); - var conformance = - index > 0 ? new Node (NodeKind.DependentProtocolConformanceRoot, index - 1) - : new Node (NodeKind.DependentProtocolConformanceRoot); - Node protocol = null; - if ((protocol = PopProtocol ()) != null) - conformance.AddChild (protocol); - else - return null; - - Node dependentType; - if ((dependentType = PopNode (NodeKind.Type)) != null) - conformance.AddChild (dependentType); - else - return null; - - return conformance; - } - - Node DemangleDependentProtocolConformanceInherited () - { - var index = DemangleIndex (); - var conformance = - index > 0 ? new Node (NodeKind.DependentProtocolConformanceInherited, index - 1) - : new Node (NodeKind.DependentProtocolConformanceInherited); - Node protocol; - if ((protocol = PopProtocol ()) != null) - conformance.AddChild (protocol); - else - return null; - - Node nested; - - if ((nested = PopDependentProtocolConformance ()) != null) - conformance.AddChild (nested); - else - return null; - - conformance.ReverseChildren (); - return conformance; - } - - Node PopDependentAssociatedConformance () - { - var protocol = PopProtocol (); - var dependentType = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.DependentAssociatedConformance, dependentType, protocol); - } - - Node DemangleDependentProtocolConformanceAssociated () - { - var index = DemangleIndex (); - var conformance = index > 0 ? new Node (NodeKind.DependentProtocolConformanceRoot, index - 1) - : new Node (NodeKind.DependentProtocolConformanceRoot); - - Node associatedConformance; - if ((associatedConformance = PopDependentAssociatedConformance ()) != null) - conformance.AddChild (associatedConformance); - else - return null; - - Node nested; - if ((nested = PopDependentProtocolConformance ()) != null) - conformance.AddChild (nested); - else - return null; - - conformance.ReverseChildren (); - - return conformance; - } - - Node DemangleRetroactiveConformance () - { - var index = DemangleIndex (); - if (index < 0) - return null; - - var conformance = PopAnyProtocolConformance (); - if (conformance == null) - return null; - - var retroactiveConformance = new Node (NodeKind.RetroactiveConformance, index); - retroactiveConformance.AddChild (conformance); - return retroactiveConformance; - } - - Node DemangleBoundGenericType () - { - Node retroactiveConformances = null; - Node retroactiveConformance; - while ((retroactiveConformance = PopNode (NodeKind.RetroactiveConformance)) != null) { - if (retroactiveConformances == null) - retroactiveConformances = new Node (NodeKind.TypeList); - retroactiveConformances.AddChild (retroactiveConformance); - } - if (retroactiveConformances != null) - retroactiveConformances.ReverseChildren (); - - var typeListList = new List (); - for (; ; ) { - var tlist = new Node (NodeKind.TypeList); - typeListList.Add (tlist); - Node ty; - while ((ty = PopNode (NodeKind.Type)) != null) { - tlist.AddChild (ty); - } - tlist.ReverseChildren (); - if (PopNode (NodeKind.EmptyList) != null) - break; - if (PopNode (NodeKind.FirstElementMarker) == null) - return null; - } - var nominal = PopTypeAndGetAnyGeneric (); - var boundNode = DemangleBoundGenericArgs (nominal, typeListList, 0); - AddChild (boundNode, retroactiveConformances); - var nty = CreateType (boundNode); - AddSubstitution (nty); - return nty; - } - - Node DemangleBoundGenericArgs (Node nominal, List typeLists, int typeListIdx) - { - if (nominal == null) - return null; - - if (typeListIdx >= typeLists.Count) - return null; - - if (nominal.Kind == NodeKind.TypeSymbolicReference || nominal.Kind == NodeKind.ProtocolSymbolicReference) { - var remainingTypeList = new Node (NodeKind.TypeList); - for (int i = typeLists.Count - 1; i >= typeListIdx && i < typeLists.Count; --i) { - var list = typeLists [i]; - foreach (var child in list.Children) { - remainingTypeList.AddChild (child); - } - } - return CreateWithChildren (NodeKind.BoundGenericOtherNominalType, CreateType (nominal), remainingTypeList); - } - - if (nominal.Children.Count == 0) - return null; - var context = nominal.Children [0]; - - var consumesGenericArgs = true; - switch (nominal.Kind) { - case NodeKind.Variable: - case NodeKind.ExplicitClosure: - case NodeKind.Subscript: - consumesGenericArgs = false; - break; - default: - break; - } - - var args = typeLists [typeListIdx]; - if (consumesGenericArgs) - ++typeListIdx; - - if (typeListIdx < typeLists.Count) { - Node boundParent = null; - if (context.Kind == NodeKind.Extension) { - boundParent = DemangleBoundGenericArgs (context.Children [1], typeLists, typeListIdx); - boundParent = CreateWithChildren (NodeKind.Extension, context.Children [0], boundParent); - if (context.Children.Count == 3) { - AddChild (boundParent, context.Children [2]); - } - } else { - boundParent = DemangleBoundGenericArgs (context, typeLists, typeListIdx); - } - - var newNominal = CreateWithChild (nominal.Kind, boundParent); - if (newNominal == null) - return null; - - for (int idx = 1; idx < nominal.Children.Count; ++idx) { - AddChild (newNominal, nominal.Children [idx]); - } - nominal = newNominal; - } - if (!consumesGenericArgs) - return nominal; - - if (args.Children.Count == 0) - return nominal; - - NodeKind kind; - switch (nominal.Kind) { - case NodeKind.Class: - kind = NodeKind.BoundGenericClass; - break; - case NodeKind.Structure: - kind = NodeKind.BoundGenericStructure; - break; - case NodeKind.Enum: - kind = NodeKind.BoundGenericEnum; - break; - case NodeKind.Protocol: - kind = NodeKind.BoundGenericProtocol; - break; - case NodeKind.OtherNominalType: - kind = NodeKind.BoundGenericOtherNominalType; - break; - case NodeKind.TypeAlias: - kind = NodeKind.BoundGenericTypeAlias; - break; - case NodeKind.Function: - case NodeKind.Constructor: - return CreateWithChildren (NodeKind.BoundGenericFunction, nominal, args); - default: - return null; - } - return CreateWithChildren (kind, CreateType (nominal), args); - } - - Node DemangleImpleParamConvention () - { - string attr = null; - switch (NextChar ()) { - case 'i': attr = "@in"; break; - case 'c': attr = "@in_constant"; break; - case 'l': attr = "@inout"; break; - case 'b': attr = "@inout_aliasable"; break; - case 'n': attr = "@in_guaranteed"; break; - case 'x': attr = "@owned"; break; - case 'g': attr = "@guaranteed"; break; - case 'e': attr = "@deallocating"; break; - case 'y': attr = "@unowned"; break; - default: - PushBack (); - return null; - } - return CreateWithChild (NodeKind.ImplParameter, new Node (NodeKind.ImplConvention, attr)); - } - - Node DemangleImplResultConvention (NodeKind convKind) - { - string attr = null; - switch (NextChar ()) { - case 'r': attr = "@out"; break; - case 'o': attr = "@owned"; break; - case 'd': attr = "@unowned"; break; - case 'u': attr = "@unowned_inner_pointer"; break; - case 'a': attr = "@autoreleased"; break; - default: - PushBack (); - return null; - } - return CreateWithChild (convKind, new Node (NodeKind.ImplConvention, attr)); - } - - Node DemangleImplFunctionType () - { - var type = new Node (NodeKind.ImplFunctionType); - - var genSig = PopNode (NodeKind.DependentGenericSignature); - if (genSig != null && NextIf ('P')) - genSig = ChangeKind (genSig, NodeKind.DependentPseudogenericSignature); - - if (NextIf ('e')) - type.AddChild (new Node (NodeKind.ImplEscaping)); - - string cattr = null; - switch (NextChar ()) { - case 'y': cattr = "@callee_unowned"; break; - case 'g': cattr = "@callee_guaranteed"; break; - case 'x': cattr = "@callee_owned"; break; - case 't': cattr = "@convention(thin)"; break; - default: - return null; - } - type.AddChild (new Node (NodeKind.ImplConvention, cattr)); - - string fattr = null; - switch (NextChar ()) { - case 'B': fattr = "@convention(block)"; break; - case 'C': fattr = "@convention(c)"; break; - case 'M': fattr = "@convention(method)"; break; - case 'O': fattr = "@convention(objc_method)"; break; - case 'K': fattr = "@convention(closure)"; break; - case 'W': fattr = "@convention(witness_method)"; break; - default: - PushBack (); - break; - } - if (fattr != null) - type.AddChild (new Node (NodeKind.ImplFunctionAttribute, fattr)); - - AddChild (type, genSig); - - var numTypesToAdd = 0; - Node param; - while ((param = DemangleImpleParamConvention ()) != null) { - type = AddChild (type, param); - numTypesToAdd++; - } - Node result; - while ((result = DemangleImplResultConvention (NodeKind.ImplResult)) != null) { - type = AddChild (type, result); - numTypesToAdd++; - } - if (NextIf ('z')) { - var errorResult = DemangleImplResultConvention (NodeKind.ImplErrorResult); - if (errorResult == null) - return null; - type = AddChild (type, errorResult); - numTypesToAdd++; - } - if (!NextIf ('_')) - return null; - - for (int idx = 0; idx < numTypesToAdd; ++idx) { - var convTy = PopNode (NodeKind.Type); - if (convTy == null) - return null; - type.Children [type.Children.Count - idx - 1].AddChild (convTy); - } - - return CreateType (type); - } - - Node DemangleMetatype () - { - switch (NextChar ()) { - case 'c': - return CreateWithChild (NodeKind.ProtocolConformanceDescriptor, PopProtocolConformance ()); - case 'f': - return CreateWithPoppedType (NodeKind.FullTypeMetadata); - case 'P': - return CreateWithPoppedType (NodeKind.GenericTypeMetadataPattern); - case 'a': - return CreateWithPoppedType (NodeKind.TypeMetadataAccessFunction); - case 'I': - return CreateWithPoppedType (NodeKind.TypeMetadataInstantiationCache); - case 'i': - return CreateWithPoppedType (NodeKind.TypeMetadataInstantiationFunction); - case 'r': - return CreateWithPoppedType (NodeKind.TypeMetadataCompletionFunction); - case 'l': - return CreateWithPoppedType ( - NodeKind.TypeMetadataSingletonInitializationCache); - case 'L': - return CreateWithPoppedType (NodeKind.TypeMetadataLazyCache); - case 'm': - return CreateWithPoppedType (NodeKind.Metaclass); - case 'n': - return CreateWithPoppedType (NodeKind.NominalTypeDescriptor); - case 'o': - return CreateWithPoppedType (NodeKind.ClassMetadataBaseOffset); - case 'p': - return CreateWithChild (NodeKind.ProtocolDescriptor, PopProtocol ()); - case 'S': - return CreateWithChild (NodeKind.ProtocolSelfConformanceDescriptor, - PopProtocol ()); - case 'u': - return CreateWithPoppedType (NodeKind.MethodLookupFunction); - case 'U': - return CreateWithPoppedType (NodeKind.ObjCMetadataUpdateFunction); - case 'B': - return CreateWithChild (NodeKind.ReflectionMetadataBuiltinDescriptor, - PopNode (NodeKind.Type)); - case 'F': - return CreateWithChild (NodeKind.ReflectionMetadataFieldDescriptor, - PopNode (NodeKind.Type)); - case 'A': - return CreateWithChild (NodeKind.ReflectionMetadataAssocTypeDescriptor, - PopProtocolConformance ()); - case 'C': { - Node Ty = PopNode (NodeKind.Type); - if (Ty == null || !IsAnyGeneric (Ty.Children [0].Kind)) - return null; - return CreateWithChild (NodeKind.ReflectionMetadataSuperclassDescriptor, - Ty.Children [0]); - } - case 'V': - return CreateWithChild (NodeKind.PropertyDescriptor, - PopNode (IsEntity)); - case 'X': - return DemanglePrivateContextDescriptor (); - default: - return null; - } - } - - Node DemanglePrivateContextDescriptor () - { - switch (NextChar ()) { - case 'E': { - var extension = PopContext (); - if (extension == null) - return null; - return CreateWithChild (NodeKind.ExtensionDescriptor, extension); - } - case 'M': { - var module = PopModule (); - if (module == null) - return null; - return CreateWithChild (NodeKind.ModuleDescriptor, module); - } - case 'Y': { - var discriminator = PopNode (); - if (discriminator == null) - return null; - var context = PopContext (); - if (context == null) - return null; - - var node = new Node (NodeKind.AnonymousDescriptor); - node.AddChild (context); - node.AddChild (discriminator); - return node; - } - case 'X': { - var context = PopContext (); - if (context == null) - return null; - return CreateWithChild (NodeKind.AnonymousDescriptor, context); - } - case 'A': { - var path = PopAssocTypePath (); - if (path == null) - return null; - var @base = PopNode (NodeKind.Type); - if (@base == null) - return null; - return CreateWithChildren (NodeKind.AssociatedTypeGenericParamRef, - @base, path); - } - default: - return null; - } - } - - Node DemangleArchetype () - { - switch (NextChar ()) { - case 'a': { - var ident = PopNode (NodeKind.Identifier); - var archeTy = PopTypeAndGetChild (); - var assocTy = CreateType (CreateWithChildren (NodeKind.AssociatedTypeRef, archeTy, ident)); - AddSubstitution (assocTy); - return assocTy; - } - case 'y': { - var t = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); - AddSubstitution (t); - return t; - } - case 'z': { - var t = DemangleAssociatedTypeSimple (GetDependentGenericParamType (0, 0)); - AddSubstitution (t); - return t; - } - case 'Y': { - var t = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); - AddSubstitution (t); - return t; - } - case 'Z': { - var t = DemangleAssociatedTypeCompound (GetDependentGenericParamType (0, 0)); - AddSubstitution (t); - return t; - } - default: - return null; - } - } - - Node DemangleAssociatedTypeSimple (Node genericParamIdx) - { - var GPI = CreateType (genericParamIdx); - var ATName = PopAssocTypeName (); - return CreateType (CreateWithChildren (NodeKind.DependentMemberType, GPI, ATName)); - } - - Node DemangleAssociatedTypeCompound (Node genericParamIdx) - { - var assocTyNames = new List (); - bool firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker) != null); - var assocTyName = PopAssocTypeName (); - if (assocTyName == null) - return null; - assocTyNames.Add (assocTyName); - } while (!firstElem); - - var @base = genericParamIdx; - - - for (int i = assocTyNames.Count - 1; i >= 0; --i) { - var assocTy = assocTyNames [i]; - var depTy = new Node (NodeKind.DependentMemberType); - depTy = AddChild (depTy, CreateType (@base)); - @base = AddChild (depTy, assocTy); - } - return CreateType (@base); - } - - Node PopAssocTypeName () - { - var proto = PopNode (NodeKind.Type); - if (proto != null && !IsProtocolNode (proto)) - return null; - - // If we haven't seen a protocol, check for a symbolic reference. - if (proto == null) - proto = PopNode (NodeKind.ProtocolSymbolicReference); - - var id = PopNode (NodeKind.Identifier); - var assocTy = ChangeKind (id, NodeKind.DependentAssociatedTypeRef); - AddChild (assocTy, proto); - return assocTy; - } - - Node PopAssocTypePath () - { - var assocTypePath = new Node (NodeKind.AssocTypePath); - bool firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker) != null); - var assocTy = PopAssocTypeName (); - if (assocTy == null) - return null; - assocTypePath.AddChild (assocTy); - } while (!firstElem); - assocTypePath.ReverseChildren (); - return assocTypePath; - } - - Node GetDependentGenericParamType (int depth, int index) - { - if (depth < 0 || index < 0) - return null; - - StringBuilder name = new StringBuilder (); - int idxChar = index; - do { - name.Append ((char)('A' + (idxChar % 26))); - idxChar /= 26; - } while (idxChar > 0); - if (depth != 0) - name.Append (depth); - - var paramTy = new Node (NodeKind.DependentGenericParamType, name.ToString ()); - paramTy.AddChild (new Node (NodeKind.Index, depth)); - paramTy.AddChild (new Node (NodeKind.Index, index)); - return paramTy; - } - - Node DemangleGenericParamIndex () - { - if (NextIf ('d')) { - int depth = DemangleIndex () + 1; - int index = DemangleIndex (); - return GetDependentGenericParamType (depth, index); - } - if (NextIf ('z')) { - return GetDependentGenericParamType (0, 0); - } - return GetDependentGenericParamType (0, DemangleIndex () + 1); - } - - Node PopProtocolConformance () - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var module = PopModule (); - var proto = PopProtocol (); - var type = PopNode (NodeKind.Type); - Node Ident = null; - if (type == null) { - // Property behavior conformance - Ident = PopNode (NodeKind.Identifier); - type = PopNode (NodeKind.Type); - } - if (genSig != null) { - type = CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, type)); - } - var Conf = CreateWithChildren (NodeKind.ProtocolConformance, type, proto, module); - AddChild (Conf, Ident); - return Conf; - } - - Node DemangleThunkOrSpecialization () - { - var c = NextChar (); - switch (c) { - case 'c': return CreateWithChild (NodeKind.CurryThunk, PopNode (IsEntity)); - case 'j': return CreateWithChild (NodeKind.DispatchThunk, PopNode (IsEntity)); - case 'q': return CreateWithChild (NodeKind.MethodDescriptor, PopNode (IsEntity)); - case 'o': return new Node (NodeKind.ObjCAttribute); - case 'O': return new Node (NodeKind.NonObjCAttribute); - case 'D': return new Node (NodeKind.DynamicAttribute); - case 'd': return new Node (NodeKind.DirectMethodReferenceAttribute); - case 'a': return new Node (NodeKind.PartialApplyObjCForwarder); - case 'A': return new Node (NodeKind.PartialApplyForwarder); - case 'm': return new Node (NodeKind.MergedFunction); - case 'X': return new Node (NodeKind.DynamicallyReplaceableFunctionVar); - case 'x': return new Node (NodeKind.DynamicallyReplaceableFunctionKey); - case 'I': return new Node (NodeKind.DynamicallyReplaceableFunctionImpl); - case 'C': { - var type = PopNode (NodeKind.Type); - return CreateWithChild (NodeKind.CoroutineContinuationPrototype, type); - } - case 'V': { - var @base = PopNode (IsEntity); - var derived = PopNode (IsEntity); - return CreateWithChildren (NodeKind.VTableThunk, derived, @base); - } - case 'W': { - var entity = PopNode (IsEntity); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.ProtocolWitness, conf, entity); - } - case 'S': - return CreateWithChild (NodeKind.ProtocolSelfConformanceWitness, - PopNode (IsEntity)); - case 'R': - case 'r': { - var thunk = new Node (c == 'R' ? - NodeKind.ReabstractionThunkHelper : - NodeKind.ReabstractionThunk); - Node genSig; - if ((genSig = PopNode (NodeKind.DependentGenericSignature)) != null) - AddChild (thunk, genSig); - var Ty2 = PopNode (NodeKind.Type); - thunk = AddChild (thunk, PopNode (NodeKind.Type)); - return AddChild (thunk, Ty2); - } - case 'g': - return DemangleGenericSpecialization (NodeKind.GenericSpecialization); - case 'G': - return DemangleGenericSpecialization (NodeKind.GenericSpecializationNotReAbstracted); - case 'i': - return DemangleGenericSpecialization (NodeKind.InlinedGenericFunction); - case 'p': { - var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecialization); - var param = CreateWithChild (NodeKind.GenericSpecializationParam, PopNode (NodeKind.Type)); - return AddChild (spec, param); - } - case 'P': { - var spec = DemangleSpecAttributes (NodeKind.GenericPartialSpecializationNotReAbstracted); - var param = CreateWithChild (NodeKind.GenericSpecializationParam, PopNode (NodeKind.Type)); - return AddChild (spec, param); - } - case 'f': - return DemangleFunctionSpecialization (); - case 'K': - case 'k': { - var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper - : NodeKind.KeyPathSetterThunkHelper; - var types = new List (); - var node = PopNode (); - if (node == null || node.Kind != NodeKind.Type) - return null; - do { - types.Add (node); - node = PopNode (); - } while (node != null && node.Kind == NodeKind.Type); - - Node result; - if (node != null) { - if (node.Kind == NodeKind.DependentGenericSignature) { - var decl = PopNode (); - if (decl == null) - return null; - result = CreateWithChildren (nodeKind, decl, /*sig*/ node); - } else { - result = CreateWithChild (nodeKind, /*decl*/ node); - } - } else { - return null; - } - foreach (var i in types) { - result.AddChild (i); - } - return result; - } - case 'l': { - var assocTypeName = PopAssocTypeName (); - if (assocTypeName == null) - return null; - - return CreateWithChild (NodeKind.AssociatedTypeDescriptor, - assocTypeName); - } - case 'L': - return CreateWithChild (NodeKind.ProtocolRequirementsBaseDescriptor, - PopProtocol ()); - case 'M': - return CreateWithChild (NodeKind.DefaultAssociatedTypeMetadataAccessor, - PopAssocTypeName ()); - - case 'n': { - var requirementTy = PopProtocol (); - var conformingType = PopAssocTypePath (); - var protoTy = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.AssociatedConformanceDescriptor, - protoTy, conformingType, requirementTy); - } - - case 'N': { - var requirementTy = PopProtocol (); - var assocTypePath = PopAssocTypePath (); - var protoTy = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.DefaultAssociatedConformanceAccessor, - protoTy, assocTypePath, requirementTy); - } - - case 'b': { - var requirementTy = PopProtocol (); - var protoTy = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.BaseConformanceDescriptor, - protoTy, requirementTy); - } - - case 'H': - case 'h': { - var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper - : NodeKind.KeyPathHashThunkHelper; - Node genericSig = null; - var types = new List (); - - var node = PopNode (); - if (node != null) { - if (node.Kind == NodeKind.DependentGenericSignature) { - genericSig = node; - } else if (node.Kind == NodeKind.Type) { - types.Add (node); - } else { - return null; - } - } else { - return null; - } - - Node node1; - while ((node1 = PopNode ()) != null) { - if (node1.Kind != NodeKind.Type) { - return null; - } - types.Add (node); - } - - var result = new Node (nodeKind); - foreach (var i in types) { - result.AddChild (i); - } - if (genericSig != null) - result.AddChild (genericSig); - return result; - } - case 'v': { - int idx = DemangleIndex (); - if (idx < 0) - return null; - return new Node (NodeKind.OutlinedVariable, idx); - } - case 'e': { - string @params = DemangleBridgedMethodParams (); - if (string.IsNullOrEmpty (@params)) - return null; - return new Node (NodeKind.OutlinedBridgedMethod, @params); - } - default: - return null; - } - } - - string DemangleBridgedMethodParams () - { - if (NextIf ('_')) - return ""; - - StringBuilder Str = new StringBuilder (); - - var kind = NextChar (); - switch (kind) { - default: - return ""; - case 'p': - case 'a': - case 'm': - Str.Append (kind); - break; - } - - while (!NextIf ('_')) { - var c = NextChar (); - if (c != 0 && c != 'n' && c != 'b') - return ""; - Str.Append (c); - } - return Str.ToString (); - } - - Node DemangleGenericSpecialization (NodeKind SpecKind) - { - var Spec = DemangleSpecAttributes (SpecKind); - if (Spec == null) - return null; - var TyList = PopTypeList (); - if (TyList == null) - return null; - foreach (var Ty in TyList.Children) { - Spec.AddChild (CreateWithChild (NodeKind.GenericSpecializationParam, Ty)); - } - return Spec; - } - - - Node DemangleFunctionSpecialization () - { - var spec = DemangleSpecAttributes (NodeKind.FunctionSignatureSpecialization); - ulong paramIdx = 0; - while (spec != null && !NextIf ('_')) { - spec = AddChild (spec, DemangleFuncSpecParam (paramIdx)); - paramIdx++; - } - if (!NextIf ('n')) - spec = AddChild (spec, DemangleFuncSpecParam ((~(ulong)0))); - - if (spec == null) - return null; - - // Add the required parameters in reverse order. - for (int idx = 0, num = spec.Children.Count; idx < num; ++idx) { - var param = spec.Children [num - idx - 1]; - if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) - continue; - - if (param.Children.Count == 0) - continue; - var kindNd = param.Children [0]; - var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; - switch (paramKind) { - case FunctionSigSpecializationParamKind.ConstantPropFunction: - case FunctionSigSpecializationParamKind.ConstantPropGlobal: - case FunctionSigSpecializationParamKind.ConstantPropString: - case FunctionSigSpecializationParamKind.ClosureProp: { - var fixedChildren = param.Children.Count; - Node ty; - while ((ty = PopNode (NodeKind.Type)) != null) { - if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) - return null; - param = AddChild (param, ty); - } - var name = PopNode (NodeKind.Identifier); - if (name == null) - return null; - string nameText = name.Text; - if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && !String.IsNullOrEmpty (nameText) - && nameText [0] == '_') { - // A '_' escapes a leading digit or '_' of a string constant. - nameText = nameText.Substring (1); - } - AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, nameText)); - param.ReverseChildren (fixedChildren); - break; - } - default: - break; - } - } - return spec; - } - - Node DemangleFuncSpecParam (ulong paramIdx) - { - var param = new Node (NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); - switch (NextChar ()) { - case 'n': - return param; - case 'c': - // Consumes an identifier and multiple type parameters. - // The parameters will be added later. - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ClosureProp)); - case 'p': { - switch (NextChar ()) { - case 'f': - // Consumes an identifier parameter, which will be added later. - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)(FunctionSigSpecializationParamKind.ConstantPropFunction))); - case 'g': - // Consumes an identifier parameter, which will be added later. - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); - case 'i': - return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropInteger); - case 'd': - return AddFuncSpecParamNumber (param, FunctionSigSpecializationParamKind.ConstantPropFloat); - case 's': { - // Consumes an identifier parameter (the string constant), - // which will be added later. - string encoding = null; - switch (NextChar ()) { - case 'b': encoding = "u8"; break; - case 'w': encoding = "u16"; break; - case 'c': encoding = "objc"; break; - default: return null; - } - AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropString)); - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); - } - default: - return null; - } - } - case 'e': { - uint value = (uint)FunctionSigSpecializationParamKind.ExistentialToGeneric; - if (NextIf ('D')) - value |= (uint)FunctionSigSpecializationParamKind.Dead; - if (NextIf ('G')) - value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf ('O')) - value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'd': { - uint value = (uint)FunctionSigSpecializationParamKind.Dead; - if (NextIf ('G')) - value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf ('O')) - value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'g': { - uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'o': { - uint value = (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf ('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'x': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.SROA)); - case 'i': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.BoxToValue)); - case 's': - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.BoxToStack)); - default: - return null; - } - } - - Node AddFuncSpecParamNumber (Node param, FunctionSigSpecializationParamKind kind) - { - param.AddChild (new Node (NodeKind.FunctionSignatureSpecializationParamKind, (uint)kind)); - var str = new StringBuilder (); - while (Char.IsDigit (PeekChar ())) { - str.Append (NextChar ()); - } - if (str.Length == 0) - return null; - return AddChild (param, new Node (NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString ())); - } - - Node DemangleSpecAttributes (NodeKind SpecKind) - { - bool isFragile = NextIf ('q'); - - int passID = (int)NextChar () - '0'; - if (passID < 0 || passID > 9) - return null; - - var specNd = new Node (SpecKind); - if (isFragile) - specNd.AddChild (new Node (NodeKind.SpecializationIsFragile)); - - specNd.AddChild (new Node (NodeKind.SpecializationPassID, passID)); - return specNd; - } - - Node DemangleWitness () - { - switch (NextChar ()) { - case 'C': - return CreateWithChild (NodeKind.EnumCase, PopNode (IsEntity)); - case 'V': - return CreateWithChild (NodeKind.ValueWitnessTable, PopNode (NodeKind.Type)); - case 'v': { - uint directness; - switch (NextChar ()) { - case 'd': directness = (uint)Directness.Direct; break; - case 'i': directness = (uint)Directness.Indirect; break; - default: return null; - } - return CreateWithChildren (NodeKind.FieldOffset, new Node (NodeKind.Directness, directness), - PopNode (IsEntity)); - } - case 'S': - return CreateWithChild (NodeKind.ProtocolSelfConformanceWitnessTable, PopProtocol ()); - case 'P': - return CreateWithChild (NodeKind.ProtocolWitnessTable, PopProtocolConformance ()); - case 'p': - return CreateWithChild (NodeKind.ProtocolWitnessTablePattern, PopProtocolConformance ()); - case 'G': - return CreateWithChild (NodeKind.GenericProtocolWitnessTable, PopProtocolConformance ()); - case 'I': - return CreateWithChild (NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance ()); - - case 'r': - return CreateWithChild (NodeKind.ResilientProtocolWitnessTable, PopProtocolConformance ()); - - case 'l': { - var conf = PopProtocolConformance (); - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.LazyProtocolWitnessTableAccessor, type, conf); - } - case 'L': { - var conf = PopProtocolConformance (); - var type = PopNode (NodeKind.Type); - return CreateWithChildren (NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); - } - case 'a': - return CreateWithChild (NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance ()); - case 't': { - var name = PopNode (IsDeclName); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.AssociatedTypeMetadataAccessor, conf, name); - } - case 'T': { - var protoTy = PopNode (NodeKind.Type); - var conformingType = PopAssocTypePath (); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.AssociatedTypeWitnessTableAccessor, conf, conformingType, protoTy); - } - case 'b': { - var protoTy = PopNode (NodeKind.Type); - var conf = PopProtocolConformance (); - return CreateWithChildren (NodeKind.BaseWitnessTableAccessor, conf, protoTy); - } - case 'O': { - switch (NextChar ()) { - case 'y': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedCopy, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedCopy, PopNode (NodeKind.Type)); - } - case 'e': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedConsume, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedConsume, PopNode (NodeKind.Type)); - } - case 'r': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedRetain, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedRetain, PopNode (NodeKind.Type)); - } - case 's': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedRelease, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedRelease, PopNode (NodeKind.Type)); - } - case 'b': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedInitializeWithTake, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedInitializeWithTake, PopNode (NodeKind.Type)); - } - case 'c': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedInitializeWithCopy, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedInitializeWithCopy, PopNode (NodeKind.Type)); - } - case 'd': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedAssignWithTake, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedAssignWithTake, PopNode (NodeKind.Type)); - } - case 'f': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedAssignWithCopy, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedAssignWithCopy, PopNode (NodeKind.Type)); - } - case 'h': { - Node sig; - if ((sig = PopNode (NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren (NodeKind.OutlinedDestroy, PopNode (NodeKind.Type), sig); - return CreateWithChild (NodeKind.OutlinedDestroy, PopNode (NodeKind.Type)); - } - default: - return null; - } - } - default: - return null; - } - } - - Node DemangleSpecialType () - { - char specialChar; - switch (specialChar = NextChar ()) { - case 'E': - return PopFunctionType (NodeKind.NoEscapeFunctionType); - case 'A': - return PopFunctionType (NodeKind.EscapingAutoClosureType); - case 'f': - return PopFunctionType (NodeKind.ThinFunctionType); - case 'K': - return PopFunctionType (NodeKind.AutoClosureType); - case 'U': - return PopFunctionType (NodeKind.UncurriedFunctionType); - case 'B': - return PopFunctionType (NodeKind.ObjCBlock); - case 'C': - return PopFunctionType (NodeKind.CFunctionPointer); - case 'o': - return CreateType (CreateWithChild (NodeKind.Unowned, PopNode (NodeKind.Type))); - case 'u': - return CreateType (CreateWithChild (NodeKind.Unmanaged, PopNode (NodeKind.Type))); - case 'w': - return CreateType (CreateWithChild (NodeKind.Weak, PopNode (NodeKind.Type))); - case 'b': - return CreateType (CreateWithChild (NodeKind.SILBoxType, PopNode (NodeKind.Type))); - case 'D': - return CreateType (CreateWithChild (NodeKind.DynamicSelf, PopNode (NodeKind.Type))); - case 'M': { - var MTR = DemangleMetatypeRepresentation (); - var type = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.Metatype, MTR, type)); - } - case 'm': { - var MTR = DemangleMetatypeRepresentation (); - var type = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.ExistentialMetatype, MTR, type)); - } - case 'p': - return CreateType (CreateWithChild (NodeKind.ExistentialMetatype, PopNode (NodeKind.Type))); - case 'c': { - var Superclass = PopNode (NodeKind.Type); - var Protocols = DemangleProtocolList (); - return CreateType (CreateWithChildren (NodeKind.ProtocolListWithClass, Protocols, Superclass)); - } - case 'l': { - var Protocols = DemangleProtocolList (); - return CreateType (CreateWithChild (NodeKind.ProtocolListWithAnyObject, Protocols)); - } - case 'X': - case 'x': { - // SIL box types. - Node signature = null, genericArgs = null; - if (specialChar == 'X') { - signature = PopNode (NodeKind.DependentGenericSignature); - if (signature == null) - return null; - genericArgs = PopTypeList (); - if (genericArgs == null) - return null; - } - - var fieldTypes = PopTypeList (); - if (fieldTypes == null) - return null; - // Build layout. - var layout = new Node (NodeKind.SILBoxLayout); - for (int i = 0, e = fieldTypes.Children.Count; i < e; ++i) { - var fieldType = fieldTypes.Children [i]; - bool isMutable = false; - // 'inout' typelist mangling is used to represent mutable fields. - if (fieldType.Children [0].Kind == NodeKind.InOut) { - isMutable = true; - fieldType = CreateType (fieldType.Children [0].Children [0]); - } - var field = new Node (isMutable - ? NodeKind.SILBoxMutableField - : NodeKind.SILBoxImmutableField); - field.AddChild (fieldType); - layout.AddChild (field); - } - var boxTy = new Node (NodeKind.SILBoxTypeWithLayout); - boxTy.AddChild (layout); - if (signature != null) { - boxTy.AddChild (signature); - boxTy.AddChild (genericArgs); - } - return CreateType (boxTy); - } - case 'Y': - return DemangleAnyGenericType (NodeKind.OtherNominalType); - case 'Z': { - var types = PopTypeList (); - var name = PopNode (NodeKind.Identifier); - var parent = PopContext (); - var anon = new Node (NodeKind.AnonymousContext); - anon = AddChild (anon, name); - anon = AddChild (anon, parent); - anon = AddChild (anon, types); - return anon; - } - case 'e': - return CreateType (new Node (NodeKind.ErrorType)); - default: - return null; - } - } - - Node DemangleMetatypeRepresentation () - { - switch (NextChar ()) { - case 't': - return new Node (NodeKind.MetatypeRepresentation, "@thin"); - case 'T': - return new Node (NodeKind.MetatypeRepresentation, "@thick"); - case 'o': - return new Node (NodeKind.MetatypeRepresentation, "@objc_metatype"); - default: - return null; - } - } - - Node DemangleAccessor (Node childNode) - { - NodeKind kind; - switch (NextChar ()) { - case 'm': kind = NodeKind.MaterializeForSet; break; - case 's': kind = NodeKind.Setter; break; - case 'g': kind = NodeKind.Getter; break; - case 'G': kind = NodeKind.GlobalGetter; break; - case 'w': kind = NodeKind.WillSet; break; - case 'W': kind = NodeKind.DidSet; break; - case 'r': kind = NodeKind.ReadAccessor; break; - case 'M': kind = NodeKind.ModifyAccessor; break; - case 'a': - switch (NextChar ()) { - case 'O': kind = NodeKind.OwningMutableAddressor; break; - case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; - case 'P': kind = NodeKind.NativePinningMutableAddressor; break; - case 'u': kind = NodeKind.UnsafeMutableAddressor; break; - default: return null; - } - break; - case 'l': - switch (NextChar ()) { - case 'O': kind = NodeKind.OwningAddressor; break; - case 'o': kind = NodeKind.NativeOwningAddressor; break; - case 'p': kind = NodeKind.NativePinningAddressor; break; - case 'u': kind = NodeKind.UnsafeAddressor; break; - default: return null; - } - break; - case 'p': // Pseudo-accessor referring to the variable/subscript itself - return childNode; - default: return null; - } - var entity = CreateWithChild (kind, childNode); - return entity; - } - - enum Args { - None, - TypeAndMaybePrivateName, - TypeAndIndex, - Index - } - - Node DemangleFunctionEntity () - { - var args = Args.None; - NodeKind Kind = NodeKind.EmptyList; - switch (NextChar ()) { - case 'D': args = Args.None; Kind = NodeKind.Deallocator; break; - case 'd': args = Args.None; Kind = NodeKind.Destructor; break; - case 'E': args = Args.None; Kind = NodeKind.IVarDestroyer; break; - case 'e': args = Args.None; Kind = NodeKind.IVarInitializer; break; - case 'i': args = Args.None; Kind = NodeKind.Initializer; break; - case 'C': - args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Allocator; break; - case 'c': - args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Constructor; break; - case 'U': args = Args.TypeAndIndex; Kind = NodeKind.ExplicitClosure; break; - case 'u': args = Args.TypeAndIndex; Kind = NodeKind.ImplicitClosure; break; - case 'A': args = Args.Index; Kind = NodeKind.DefaultArgumentInitializer; break; - case 'p': return DemangleEntity (NodeKind.GenericTypeParamDecl); - default: return null; - } - - Node nameOrIndex = null, paramType = null, labelList = null; - switch (args) { - case Args.None: - break; - case Args.TypeAndMaybePrivateName: - nameOrIndex = PopNode (NodeKind.PrivateDeclName); - paramType = PopNode (NodeKind.Type); - labelList = PopFunctionParamLabels (paramType); - break; - case Args.TypeAndIndex: - nameOrIndex = DemangleIndexAsNode (); - paramType = PopNode (NodeKind.Type); - break; - case Args.Index: - nameOrIndex = DemangleIndexAsNode (); - break; - } - var entity = CreateWithChild (Kind, PopContext ()); - switch (args) { - case Args.None: - break; - case Args.Index: - entity = AddChild (entity, nameOrIndex); - break; - case Args.TypeAndMaybePrivateName: - AddChild (entity, labelList); - entity = AddChild (entity, paramType); - AddChild (entity, nameOrIndex); - break; - case Args.TypeAndIndex: - entity = AddChild (entity, nameOrIndex); - entity = AddChild (entity, paramType); - break; - } - return entity; - } - - Node DemangleEntity (NodeKind Kind) - { - var type = PopNode (NodeKind.Type); - var labelList = PopFunctionParamLabels (type); - var name = PopNode (IsDeclName); - var context = PopContext (); - return labelList != null ? CreateWithChildren (Kind, context, name, labelList, type) - : CreateWithChildren (Kind, context, name, type); - } - - Node DemangleVariable () - { - var variable = DemangleEntity (NodeKind.Variable); - return DemangleAccessor (variable); - } - - Node DemangleSubscript () - { - var privateName = PopNode (NodeKind.PrivateDeclName); - var type = PopNode (NodeKind.Type); - var labelList = PopFunctionParamLabels (type); - var context = PopContext (); - - var subscript = new Node (NodeKind.Subscript); - subscript = AddChild (subscript, context); - AddChild (subscript, labelList); - subscript = AddChild (subscript, type); - AddChild (subscript, privateName); - - return DemangleAccessor (subscript); - } - - Node DemangleProtocolList () - { - var typeList = new Node (NodeKind.TypeList); - var protoList = CreateWithChild (NodeKind.ProtocolList, typeList); - if (PopNode (NodeKind.EmptyList) == null) { - bool firstElem = false; - do { - firstElem = (PopNode (NodeKind.FirstElementMarker) != null); - var proto = PopProtocol (); - if (proto == null) - return null; - typeList.AddChild (proto); - } while (!firstElem); - - typeList.ReverseChildren (); - } - return protoList; - } - - Node DemangleProtocolListType () - { - var protoList = DemangleProtocolList (); - return CreateType (protoList); - } - - Node DemangleGenericSignature (bool hasParamCounts) - { - var Sig = new Node (NodeKind.DependentGenericSignature); - if (hasParamCounts) { - while (!NextIf ('l')) { - int count = 0; - if (!NextIf ('z')) - count = DemangleIndex () + 1; - if (count < 0) - return null; - Sig.AddChild (new Node (NodeKind.DependentGenericParamCount, count)); - } - } else { - Sig.AddChild (new Node (NodeKind.DependentGenericParamCount, 1)); - } - var NumCounts = Sig.Children.Count; - Node Req; - while ((Req = PopNode (IsRequirement)) != null) { - Sig.AddChild (Req); - } - Sig.ReverseChildren (NumCounts); - return Sig; - } - - enum TypeKind { - Generic, - Assoc, - CompoundAssoc, - Substitution - } - - enum ConstraintKind { - Protocol, - BaseClass, - SameType, - Layout - } - - Node DemangleGenericRequirement () - { - TypeKind typeKind; - ConstraintKind constraintKind; - - switch (NextChar ()) { - case 'c': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Assoc; break; - case 'C': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.CompoundAssoc; break; - case 'b': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Generic; break; - case 'B': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Substitution; break; - case 't': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Assoc; break; - case 'T': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.CompoundAssoc; break; - case 's': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Generic; break; - case 'S': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Substitution; break; - case 'm': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Assoc; break; - case 'M': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.CompoundAssoc; break; - case 'l': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Generic; break; - case 'L': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Substitution; break; - case 'p': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Assoc; break; - case 'P': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.CompoundAssoc; break; - case 'Q': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Substitution; break; - default: constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Generic; PushBack (); break; - } - - Node ConstrTy = null; - - switch (typeKind) { - case TypeKind.Generic: - ConstrTy = CreateType (DemangleGenericParamIndex ()); - break; - case TypeKind.Assoc: - ConstrTy = DemangleAssociatedTypeSimple (DemangleGenericParamIndex ()); - AddSubstitution (ConstrTy); - break; - case TypeKind.CompoundAssoc: - ConstrTy = DemangleAssociatedTypeCompound (DemangleGenericParamIndex ()); - AddSubstitution (ConstrTy); - break; - case TypeKind.Substitution: - ConstrTy = PopNode (NodeKind.Type); - break; - } - - switch (constraintKind) { - case ConstraintKind.Protocol: - return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopProtocol ()); - case ConstraintKind.BaseClass: - return CreateWithChildren (NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopNode (NodeKind.Type)); - case ConstraintKind.SameType: - return CreateWithChildren (NodeKind.DependentGenericSameTypeRequirement, ConstrTy, PopNode (NodeKind.Type)); - case ConstraintKind.Layout: { - var c = NextChar (); - Node size = null; - Node alignment = null; - string name = null; - if (c == 'U') { - name = "U"; - } else if (c == 'R') { - name = "R"; - } else if (c == 'N') { - name = "N"; - } else if (c == 'C') { - name = "C"; - } else if (c == 'D') { - name = "D"; - } else if (c == 'T') { - name = "T"; - } else if (c == 'E') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - alignment = DemangleIndexAsNode (); - name = "E"; - } else if (c == 'e') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - name = "e"; - } else if (c == 'M') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - alignment = DemangleIndexAsNode (); - name = "M"; - } else if (c == 'm') { - size = DemangleIndexAsNode (); - if (size == null) - return null; - name = "m"; - } else { - // Unknown layout constraint. - return null; - } - - var NameNode = new Node (NodeKind.Identifier, name); - var LayoutRequirement = CreateWithChildren (NodeKind.DependentGenericLayoutRequirement, ConstrTy, NameNode); - if (size != null) - AddChild (LayoutRequirement, size); - if (alignment != null) - AddChild (LayoutRequirement, alignment); - return LayoutRequirement; - } - } - return null; - } - - Node DemangleGenericType () - { - var genSig = PopNode (NodeKind.DependentGenericSignature); - var ty = PopNode (NodeKind.Type); - return CreateType (CreateWithChildren (NodeKind.DependentGenericType, genSig, ty)); - } - - int DecodeValueWitnessKind (string codeStr) - { - switch (codeStr) { - case "al": return (int)ValueWitnessKind.AllocateBuffer; - case "ca": return (int)ValueWitnessKind.AssignWithCopy; - case "ta": return (int)ValueWitnessKind.AssignWithTake; - case "de": return (int)ValueWitnessKind.DeallocateBuffer; - case "xx": return (int)ValueWitnessKind.Destroy; - case "XX": return (int)ValueWitnessKind.DestroyBuffer; - case "Xx": return (int)ValueWitnessKind.DestroyArray; - case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; - case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; - case "cp": return (int)ValueWitnessKind.InitializeWithCopy; - case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; - case "tk": return (int)ValueWitnessKind.InitializeWithTake; - case "pr": return (int)ValueWitnessKind.ProjectBuffer; - case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; - case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; - case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; - case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; - case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; - case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; - case "ug": return (int)ValueWitnessKind.GetEnumTag; - case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; - case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; - case "et": return (int)ValueWitnessKind.GetEnumTagSinglePayload; - case "st": return (int)ValueWitnessKind.StoreEnumTagSinglePayload; - default: - return -1; - } - } - - Node DemangleValueWitness () - { - char [] code = new char [2]; - code [0] = NextChar (); - code [1] = NextChar (); - int kind = DecodeValueWitnessKind (new string (code)); - if (kind < 0) - return null; - var vw = new Node (NodeKind.ValueWitness, (uint)kind); - return AddChild (vw, PopNode (NodeKind.Type)); - } - - Node DemangleObjCTypeName () - { - var ty = new Node (NodeKind.Type); - var global = AddChild (new Node (NodeKind.Global), AddChild (new Node (NodeKind.TypeMangling), ty)); - Node nominal = null; - bool isProto = false; - if (NextIf ('C')) { - nominal = new Node (NodeKind.Class); - AddChild (ty, nominal); - } else if (NextIf ('P')) { - isProto = true; - nominal = new Node (NodeKind.Protocol); - AddChild (ty, AddChild (new Node (NodeKind.ProtocolList), - AddChild (new Node (NodeKind.TypeList), - AddChild (new Node (NodeKind.Type), nominal)))); - } else { - return null; - } - - if (NextIf ('s')) { - nominal.AddChild (new Node (NodeKind.Module, "Swift")); - } else { - var Module = DemangleIdentifier (); - if (Module == null) - return null; - nominal.AddChild (ChangeKind (Module, NodeKind.Module)); - } - - var ident = DemangleIdentifier (); - if (ident == null) - return null; - nominal.AddChild (ident); - - if (isProto && !NextIf ('_')) - return null; - - if (!slice.IsAtEnd) - return null; - - return global; - } - - } + }; + + Swift5Demangler() + { + } + + + public Swift5Demangler(string mangledName, ulong offset = 0) + { + originalIdentifier = mangledName; + this.offset = offset; + slice = new StringSlice(originalIdentifier); + slice.Advance(GetManglingPrefixLength(originalIdentifier)); + } + + public TLDefinition Run() + { + Node topLevelNode = DemangleType(null); + if (topLevelNode != null && topLevelNode.IsAttribute() && nodeStack.Count >= 1) + { + var attribute = topLevelNode.ExtractAttribute(); + var tld = Run(); + if (tld != null && tld is TLFunction tlf) + { + tlf.Signature.Attributes.Add(attribute); + } + return tld; + } + else + { + Swift5NodeToTLDefinition converter = new Swift5NodeToTLDefinition(originalIdentifier, offset); + return converter.Convert(topLevelNode); + } + } + + bool NextIf(string str) + { + if (slice.StartsWith(str)) + { + slice.Advance(str.Length); + return true; + } + return false; + + } + + char PeekChar() + { + if (slice.IsAtEnd) + return (char)0; + return slice.Current; + } + + char NextChar() + { + return slice.Advance(); + } + + bool NextIf(char c) + { + return slice.AdvanceIfEquals(c); + } + + void PushBack() + { + slice.Rewind(); + } + + string ConsumeAll() + { + return slice.ConsumeRemaining(); + } + + void PushNode(Node node) + { + nodeStack.Push(node); + } + + Node PopNode() + { + if (nodeStack.Count == 0) + return null; + return nodeStack.Pop(); + } + + Node PopNode(NodeKind kind) + { + if (nodeStack.Count == 0) + return null; + if (kind != nodeStack.Peek().Kind) + return null; + return PopNode(); + } + + Node PopNode(Predicate pred) + { + if (nodeStack.Count == 0) + return null; + if (!pred(nodeStack.Peek().Kind)) + return null; + return PopNode(); + } + + void AddSubstitution(Node nd) + { + if (nd != null) + substitutions.Add(nd); + } + + Node CreateWithPoppedType(NodeKind kind) + { + return CreateWithChild(kind, PopNode(NodeKind.Type)); + } + + + // beginning of swift 5 demangler port + + static bool IsDeclName(NodeKind kind) + { + switch (kind) + { + case NodeKind.Identifier: + case NodeKind.LocalDeclName: + case NodeKind.PrivateDeclName: + case NodeKind.RelatedEntityDeclName: + case NodeKind.PrefixOperator: + case NodeKind.PostfixOperator: + case NodeKind.InfixOperator: + case NodeKind.TypeSymbolicReference: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsContext(NodeKind node) + { + var type = typeof(NodeKind); + var memInfo = type.GetMember(node.ToString()); + return memInfo[0].GetCustomAttributes(typeof(ContextAttribute), false).Length > 0; + } + + static bool IsAnyGeneric(NodeKind kind) + { + switch (kind) + { + case NodeKind.Structure: + case NodeKind.Class: + case NodeKind.Enum: + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + case NodeKind.OtherNominalType: + case NodeKind.TypeAlias: + case NodeKind.TypeSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsEntity(NodeKind kind) + { + if (kind == NodeKind.Type) + return true; + return IsContext(kind); + } + + static bool IsRequirement(NodeKind kind) + { + switch (kind) + { + case NodeKind.DependentGenericSameTypeRequirement: + case NodeKind.DependentGenericLayoutRequirement: + case NodeKind.DependentGenericConformanceRequirement: + return true; + default: + return false; + } + } + + static bool IsFunctionAttr(NodeKind kind) + { + switch (kind) + { + case NodeKind.FunctionSignatureSpecialization: + case NodeKind.GenericSpecialization: + case NodeKind.InlinedGenericFunction: + case NodeKind.GenericSpecializationNotReAbstracted: + case NodeKind.GenericPartialSpecialization: + case NodeKind.GenericPartialSpecializationNotReAbstracted: + case NodeKind.ObjCAttribute: + case NodeKind.NonObjCAttribute: + case NodeKind.DynamicAttribute: + case NodeKind.DirectMethodReferenceAttribute: + case NodeKind.VTableAttribute: + case NodeKind.PartialApplyForwarder: + case NodeKind.PartialApplyObjCForwarder: + case NodeKind.OutlinedVariable: + case NodeKind.OutlinedBridgedMethod: + case NodeKind.MergedFunction: + case NodeKind.DynamicallyReplaceableFunctionImpl: + case NodeKind.DynamicallyReplaceableFunctionKey: + case NodeKind.DynamicallyReplaceableFunctionVar: + return true; + default: + return false; + } + } + + int GetManglingPrefixLength(string mangledName) + { + if (string.IsNullOrEmpty(mangledName)) + return 0; + foreach (var prefix in prefixes) + { + mangledName.StartsWith(prefix, StringComparison.Ordinal); + return prefix.Length; + } + return 0; + } + + bool IsSwiftSymbol(string mangledName) + { + if (IsOldFunctionTypeMangling(mangledName)) + return true; + return GetManglingPrefixLength(mangledName) != 0; + } + + bool IsObjCSymbol(string mangledName) + { + var nameWithoutPrefix = DropSwiftManglingPrefix(mangledName); + return nameWithoutPrefix.StartsWith("So", StringComparison.Ordinal) || nameWithoutPrefix.StartsWith("Sc", StringComparison.Ordinal); + } + + bool IsOldFunctionTypeMangling(string mangledName) + { + return mangledName.StartsWith("_T", StringComparison.Ordinal); + } + + string DropSwiftManglingPrefix(string mangledName) + { + return mangledName.Substring(GetManglingPrefixLength(mangledName)); + } + + static bool IsAliasNode(Node node) + { + switch (node.Kind) + { + case NodeKind.Type: + return IsAliasNode(node.Children[0]); + case NodeKind.TypeAlias: + return true; + default: + return false; + } + } + + static bool IsAlias(string mangledName) + { + return IsAliasNode(new Swift5Demangler().DemangleType(mangledName)); + } + + static bool IsClassNode(Node node) + { + switch (node.Kind) + { + case NodeKind.Type: + return IsClassNode(node.Children[0]); + case NodeKind.Class: + case NodeKind.BoundGenericClass: + return true; + default: + return false; + } + } + + static bool IsClass(string mangledName) + { + return IsClassNode(new Swift5Demangler().DemangleType(mangledName)); + } + + static bool IsEnumNode(Node node) + { + switch (node.Kind) + { + case NodeKind.Type: + return IsEnumNode(node.Children[0]); + case NodeKind.Enum: + case NodeKind.BoundGenericEnum: + return true; + default: + return false; + } + } + + static bool IsEnum(string mangledName) + { + return IsEnumNode(new Swift5Demangler().DemangleType(mangledName)); + } + + static bool IsProtocolNode(Node node) + { + switch (node.Kind) + { + case NodeKind.Type: + return IsProtocolNode(node.Children[0]); + case NodeKind.Protocol: + case NodeKind.ProtocolSymbolicReference: + return true; + default: + return false; + } + } + + static bool IsProtocol(string mangledName) + { + return IsProtocolNode(new Swift5Demangler().DemangleType(mangledName)); + } + + static bool IsStructNode(Node node) + { + switch (node.Kind) + { + case NodeKind.Type: + return IsStructNode(node.Children[0]); + case NodeKind.Structure: + case NodeKind.BoundGenericStructure: + return true; + default: + return false; + } + } + + static bool IsStruct(string mangledName) + { + return IsStructNode(new Swift5Demangler().DemangleType(mangledName)); + } + + + + + void Clear() + { + nodeStack.Clear(); + substitutions.Clear(); + } + + void Init(string mangledName) + { + nodeStack = new Stack(); + substitutions = new List(); + words = new List(); + if (mangledName != null) + { + text = mangledName; + slice = new StringSlice(mangledName); + } + } + + public Node DemangleSymbol(string mangledName) + { + Init(mangledName); + + if (NextIf("_Tt")) + return DemangleObjCTypeName(); + + var prefixLength = GetManglingPrefixLength(mangledName); + if (prefixLength == 0) + return null; + isOldFunctionTypeMangling = IsOldFunctionTypeMangling(mangledName); + slice.Advance(prefixLength); + + if (!ParseAndPushNodes()) + return null; + + var topLevel = new Node(NodeKind.Global); + var parent = topLevel; + Node funcAttr = null; + while ((funcAttr = PopNode(IsFunctionAttr)) != null) + { + parent.AddChild(funcAttr); + if (funcAttr.Kind == NodeKind.PartialApplyForwarder || funcAttr.Kind == NodeKind.PartialApplyObjCForwarder) + parent = funcAttr; + foreach (var nd in nodeStack) + { + switch (nd.Kind) + { + case NodeKind.Type: + parent.AddChild(nd.Children[0]); + break; + default: + parent.AddChild(nd); + break; + } + } + } + if (topLevel.Children.Count == 0) + return null; + + return topLevel; + } + + Node DemangleType(string mangledName) + { + Init(mangledName); + + ParseAndPushNodes(); + + var result = PopNode(); + if (result != null) + return result; + + return new Node(NodeKind.Suffix, text); + } + + bool ParseAndPushNodes() + { + var idx = 0; + while (!slice.IsAtEnd) + { + var node = DemangleOperator(); + if (node == null) + return false; + PushNode(node); + idx++; + } + return true; + } + + Node AddChild(Node parent, Node child) + { + if (parent == null || child == null) + return null; + parent.Children.Add(child); + return parent; + } + + Node CreateWithChild(NodeKind kind, Node child) + { + if (child == null) + return null; + var node = new Node(kind); + node.Children.Add(child); + return node; + } + + Node CreateType(Node child) + { + return CreateWithChild(NodeKind.Type, child); + } + + Node CreateWithChildren(NodeKind kind, params Node[] children) + { + foreach (var nd in children) + if (nd == null) + throw new ArgumentOutOfRangeException(nameof(children)); + var node = new Node(kind); + node.Children.AddRange(children); + return node; + } + + Node ChangeKind(Node node, NodeKind newKind) + { + Node newNode = null; + if (node.HasText) + { + newNode = new Node(newKind, node.Text); + } + else if (node.HasIndex) + { + newNode = new Node(newKind, node.Index); + } + else + { + newNode = new Node(newKind); + } + newNode.Children.AddRange(node.Children); + return newNode; + } + + Node DemangleTypeMangling() + { + var type = PopNode(NodeKind.Type); + var labelList = PopFunctionParamLabels(type); + var typeMangling = new Node(NodeKind.TypeMangling); + + AddChild(typeMangling, labelList); + typeMangling = AddChild(typeMangling, type); + return typeMangling; + } + + Node DemangleSymbolicReference(int rawKind) + { + var data = new byte[4]; + for (int i = 0; i < 4; i++) + { + data[i] = (byte)NextChar(); + } + var value = BitConverter.ToInt32(data, 0); + + SymbolicReferenceKind kind; + Directness direct; + switch (rawKind) + { + case 1: + kind = SymbolicReferenceKind.Context; + direct = Directness.Direct; + break; + case 2: + kind = SymbolicReferenceKind.Context; + direct = Directness.Indirect; + break; + default: + return null; + } + + Node resolved = null; + if (SymbolicReferenceResolver != null) + { + resolved = SymbolicReferenceResolver(kind, direct, value, data); + } + if (resolved == null) + return null; + + if (kind == SymbolicReferenceKind.Context) + AddSubstitution(resolved); + return resolved; + } + + Node DemangleOperator() + { + var c = NextChar(); + switch (c) + { + case '\x01': + case '\x02': + case '\x03': + case '\x04': + return DemangleSymbolicReference(c); + case 'A': return DemangleMultiSubstitutions(); + case 'B': return DemangleBuiltinType(); + case 'C': return DemangleAnyGenericType(NodeKind.Class); + case 'D': return DemangleTypeMangling(); + case 'E': return DemangleExtensionContext(); + case 'F': return DemanglePlainFunction(); + case 'G': return DemangleBoundGenericType(); + case 'H': + var c2 = NextChar(); + switch (c2) + { + case 'A': return DemangleDependentProtocolConformanceAssociated(); + case 'C': return DemangleConcreteProtocolConformance(); + case 'D': return DemangleDependentProtocolConformanceRoot(); + case 'I': return DemangleDependentProtocolConformanceInherited(); + case 'P': + return CreateWithChild(NodeKind.ProtocolConformanceRefInTypeModule, PopProtocol()); + case 'p': + return CreateWithChild(NodeKind.ProtocolConformanceRefInProtocolModule, PopProtocol()); + default: + PushBack(); + PushBack(); + return DemangleIdentifier(); + } + case 'I': return DemangleImplFunctionType(); + case 'K': return new Node(NodeKind.ThrowsAnnotation); + case 'L': return DemangleLocalIdentifier(); + case 'M': return DemangleMetatype(); + case 'N': return CreateWithChild(NodeKind.TypeMetadata, PopNode(NodeKind.Type)); + case 'O': return DemangleAnyGenericType(NodeKind.Enum); + case 'P': return DemangleAnyGenericType(NodeKind.Protocol); + case 'Q': return DemangleArchetype(); + case 'R': return DemangleGenericRequirement(); + case 'S': return DemangleStandardSubstitution(); + case 'T': return DemangleThunkOrSpecialization(); + case 'V': return DemangleAnyGenericType(NodeKind.Structure); + case 'W': return DemangleWitness(); + case 'X': return DemangleSpecialType(); + case 'Z': return CreateWithChild(NodeKind.Static, PopNode(IsEntity)); + case 'a': return DemangleAnyGenericType(NodeKind.TypeAlias); + case 'c': return PopFunctionType(NodeKind.FunctionType); + case 'd': return new Node(NodeKind.VariadicMarker); + case 'f': return DemangleFunctionEntity(); + case 'g': return DemangleRetroactiveConformance(); + case 'h': return CreateType(CreateWithChild(NodeKind.Shared, PopTypeAndGetChild())); + case 'i': return DemangleSubscript(); + case 'l': return DemangleGenericSignature(false); + case 'm': return CreateType(CreateWithChild(NodeKind.Metatype, PopNode(NodeKind.Type))); + case 'n': return CreateType(CreateWithChild(NodeKind.Owned, PopTypeAndGetChild())); + case 'o': return DemangleOperatorIdentifier(); + case 'p': return DemangleProtocolListType(); + case 'q': return CreateType(DemangleGenericParamIndex()); + case 'r': return DemangleGenericSignature(true); + case 's': return new Node(NodeKind.Module, "Swift"); + case 't': return PopTuple(); + case 'u': return DemangleGenericType(); + case 'v': return DemangleVariable(); + case 'w': return DemangleValueWitness(); + case 'x': return CreateType(GetDependentGenericParamType(0, 0)); + case 'y': return new Node(NodeKind.EmptyList); + case 'z': return CreateType(CreateWithChild(NodeKind.InOut, PopTypeAndGetChild())); + case '_': return new Node(NodeKind.FirstElementMarker); + case '.': + PushBack(); + return new Node(NodeKind.Suffix, slice.ConsumeRemaining()); + default: + PushBack(); + return DemangleIdentifier(); + } + } + + int DemangleNatural() + { + if (!Char.IsDigit(slice.Current)) + return -1000; + var num = 0; + while (true) + { + var c = slice.Current; + if (!Char.IsDigit(c)) + return num; + var newNum = (10 * num) + (c - '0'); + if (newNum < num) + return -1000; + num = newNum; + NextChar(); + } + } + + int DemangleIndex() + { + if (NextIf('_')) + return 0; + var num = DemangleNatural(); + if (num >= 0 && NextIf('_')) + return num + 1; + return -1000; + } + + + Node DemangleIndexAsNode() + { + var idx = DemangleIndex(); + if (idx >= 0) + return new Node(NodeKind.Number, idx); + return null; + } + + Node DemangleMultiSubstitutions() + { + var repeatCount = 1; + while (true) + { + if (slice.IsAtEnd) + return null; + var c = NextChar(); + if (Char.IsLower(c)) + { + var nd = PushMultiSubstitutions(repeatCount, c - 'a'); + if (nd == null) + return null; + PushNode(nd); + repeatCount = -1; + continue; + } + if (Char.IsUpper(c)) + { + return PushMultiSubstitutions(repeatCount, c - 'A'); + } + if (c == '_') + { + var idx = repeatCount + 27; + if (idx >= substitutions.Count) + return null; + return substitutions[idx]; + } + PushBack(); + repeatCount = DemangleNatural(); + if (repeatCount < 0) + return null; + } + } + + Node PushMultiSubstitutions(int repeatCount, int substIdx) + { + if (substIdx >= substitutions.Count) + return null; + var nd = substitutions[substIdx]; + while (repeatCount-- > 1) + { + PushNode(nd); + } + return nd; + } + + Node CreateSwiftType(NodeKind typeKind, string name) + { + return CreateType(CreateWithChildren(typeKind, new Node(NodeKind.Module, "Swift"), new Node(NodeKind.Identifier, name))); + } + + Node DemangleStandardSubstitution() + { + var c = NextChar(); + switch (c) + { + case 'o': + return new Node(NodeKind.Module, "__C"); + case 'C': + return new Node(NodeKind.Module, "__C_Synthesized"); + case 'g': + { + var optionalTy = CreateType(CreateWithChildren(NodeKind.BoundGenericEnum, + CreateSwiftType(NodeKind.Enum, "Optional"), + CreateWithChild(NodeKind.TypeList, PopNode(NodeKind.Type)))); + AddSubstitution(optionalTy); + return optionalTy; + } + default: + PushBack(); + Node nd; + var repeatCount = DemangleNatural(); + if ((nd = CreateStandardSubstitution(NextChar())) != null) + { + while (repeatCount-- > 1) + { + PushNode(nd); + } + return nd; + } + return null; + } + } + + Node CreateStandardSubstitution(char subst) + { + var kind = NodeKind.Structure; + string name = null; + switch (subst) + { + case 'A': name = "AutoreleasingUnsafeMutablePointer"; break; + case 'a': name = "Array"; break; + case 'b': name = "Bool"; break; + case 'c': name = "UnicodeScalar"; break; + case 'D': name = "Dictionary"; break; + case 'd': name = "Double"; break; + case 'f': name = "Float"; break; + case 'h': name = "Set"; break; + case 'I': name = "DefaultIndicies"; break; + case 'i': name = "Int"; break; + case 'J': name = "Character"; break; + case 'N': name = "ClosedRange"; break; + case 'n': name = "Range"; break; + case 'O': name = "ObjectIdentifier"; break; + case 'P': name = "UnsafePointer"; break; + case 'p': name = "UnsafeMutablePointer"; break; + case 'R': name = "UnsafeBufferPointer"; break; + case 'r': name = "UnsafeMutableBufferPointer"; break; + case 'S': name = "String"; break; + case 's': name = "Substring"; break; + case 'u': name = "UInt"; break; + case 'V': name = "UnsafeRawPointer"; break; + case 'v': name = "UnsafeMutableRawPointer"; break; + case 'W': name = "UnsafeRawBufferPointer"; break; + case 'w': name = "UnsafeMutableRawBufferPointer"; break; + + case 'q': name = "Optional"; kind = NodeKind.Enum; break; + + case 'B': name = "BinaryFloatingPoint"; kind = NodeKind.Protocol; break; + case 'E': name = "Encodable"; kind = NodeKind.Protocol; break; + case 'e': name = "Decodable"; kind = NodeKind.Protocol; break; + case 'F': name = "FloatingPoint"; kind = NodeKind.Protocol; break; + case 'G': name = "RandomNumberGenerator"; kind = NodeKind.Protocol; break; + case 'H': name = "Hashable"; kind = NodeKind.Protocol; break; + case 'j': name = "Numeric"; kind = NodeKind.Protocol; break; + case 'K': name = "BidirectionalCollection"; kind = NodeKind.Protocol; break; + case 'k': name = "RandomAccessCollection"; kind = NodeKind.Protocol; break; + case 'L': name = "Comparable"; kind = NodeKind.Protocol; break; + case 'l': name = "Collection"; kind = NodeKind.Protocol; break; + case 'M': name = "MutableCollection"; kind = NodeKind.Protocol; break; + case 'm': name = "RangeReplaceableCollection"; kind = NodeKind.Protocol; break; + case 'Q': name = "Equatable"; kind = NodeKind.Protocol; break; + case 'T': name = "Sequence"; kind = NodeKind.Protocol; break; + case 't': name = "IteratorProtocol"; kind = NodeKind.Protocol; break; + case 'U': name = "UnsignedInteger"; kind = NodeKind.Protocol; break; + case 'X': name = "RangeExpression"; kind = NodeKind.Protocol; break; + case 'x': name = "Strideable"; kind = NodeKind.Protocol; break; + case 'Y': name = "RawRepresentable"; kind = NodeKind.Protocol; break; + case 'y': name = "StringProtocol"; kind = NodeKind.Protocol; break; + case 'Z': name = "SignedInteger"; kind = NodeKind.Protocol; break; + case 'z': name = "BinaryInteger"; kind = NodeKind.Protocol; break; + default: + return null; + } + + return CreateSwiftType(kind, name); + } + + Node DemangleIdentifier() + { + var hasWordSubsts = false; + var isPunycoded = false; + var c = PeekChar(); + if (!Char.IsDigit(c)) + return null; + if (c == '0') + { + NextChar(); + if (PeekChar() == '0') + { + NextChar(); + isPunycoded = true; + } + else + { + hasWordSubsts = true; + } + } + var identifier = new StringBuilder(); + do + { + while (hasWordSubsts && Char.IsLetter(PeekChar())) + { + var cc = NextChar(); + var wordIdx = 0; + if (Char.IsLower(cc)) + { + wordIdx = cc - 'a'; + } + else + { + wordIdx = cc - 'A'; + hasWordSubsts = false; + } + if (wordIdx >= words.Count) + return null; + string piece0 = words[wordIdx]; + identifier.Append(piece0); + } + if (NextIf('0')) + break; + var numChars = DemangleNatural(); + if (numChars <= 0) + return null; + if (isPunycoded) + NextIf('_'); + if (numChars > slice.Length) + return null; + string piece = slice.Substring(slice.Position, numChars); + if (isPunycoded) + { + PunyCode puny = new PunyCode(); + string punyCodedString = puny.Decode(piece); + identifier.Append(punyCodedString); + } + else + { + identifier.Append(piece); + var wordStartPos = -1; + for (int idx = 0; idx <= piece.Length; idx++) + { + char ccc = idx < piece.Length ? piece[idx] : (char)0; + if (wordStartPos >= 0 && IsWordEnd(ccc, piece[idx - 1])) + { + if (idx - wordStartPos >= 2 && words.Count < 26) + { + var word = piece.Substring(wordStartPos, idx - wordStartPos); + words.Add(word); + } + wordStartPos = -1; + } + if (wordStartPos < 0 && IsWordStart(ccc)) + { + wordStartPos = idx; + } + } + } + slice.Advance(numChars); + } while (hasWordSubsts); + if (identifier.Length == 0) + return null; + var ident = new Node(NodeKind.Identifier, identifier.ToString()); + AddSubstitution(ident); + return ident; + } + + bool IsWordStart(char ch) + { + return !Char.IsDigit(ch) && ch != '_' && ch != (char)0; + } + + bool IsWordEnd(char ch, char prevCh) + { + if (ch == '_' || ch == (char)0) + return true; + if (!Char.IsUpper(prevCh) && Char.IsUpper(ch)) + return true; + return false; + } + + + Node DemangleOperatorIdentifier() + { + var ident = PopNode(NodeKind.Identifier); + if (ident == null) + return null; + var op_char_table = "& @/= > <*!|+?%-~ ^ ."; + StringBuilder opStr = new StringBuilder(); + foreach (var c in ident.Text) + { + if (c > 0x7f) + { + opStr.Append(c); + continue; + } + if (!Char.IsLower(c)) + return null; + char o = op_char_table[c - 'a']; + if (o == ' ') + return null; + opStr.Append(o); + } + switch (NextChar()) + { + case 'i': return new Node(NodeKind.InfixOperator, opStr.ToString()); + case 'p': return new Node(NodeKind.PrefixOperator, opStr.ToString()); + case 'P': return new Node(NodeKind.PostfixOperator, opStr.ToString()); + default: return null; + } + } + + + Node DemangleLocalIdentifier() + { + if (NextIf('L')) + { + var discriminator = PopNode(NodeKind.Identifier); + var name = PopNode(IsDeclName); + return CreateWithChildren(NodeKind.PrivateDeclName, discriminator, name); + } + if (NextIf('l')) + { + var discriminator = PopNode(NodeKind.Identifier); + return CreateWithChild(NodeKind.PrivateDeclName, discriminator); + } + if ((PeekChar() >= 'a' && PeekChar() <= 'j') || + (PeekChar() >= 'A' && PeekChar() <= 'J')) + { + var relatedEntityKind = NextChar(); + var name = PopNode(); + var result = new Node(NodeKind.RelatedEntityDeclName, relatedEntityKind.ToString()); + return AddChild(result, name); + } + var discriminatorx = DemangleIndexAsNode(); + var namex = PopNode(IsDeclName); + return CreateWithChildren(NodeKind.LocalDeclName, discriminatorx, namex); + } + + Node PopModule() + { + var ident = PopNode(NodeKind.Identifier); + if (ident != null) + return ChangeKind(ident, NodeKind.Module); + return PopNode(NodeKind.Module); + } + + Node PopContext() + { + var mod = PopModule(); + if (mod != null) + return mod; + + var ty = PopNode(NodeKind.Type); + if (ty != null) + { + if (ty.Children.Count != 1) + return null; + var child = ty.Children[0]; + if (!IsContext(child.Kind)) + return null; + return child; + } + return PopNode(IsContext); + } + + Node PopTypeAndGetChild() + { + var ty = PopNode(NodeKind.Type); + if (ty == null || ty.Children.Count != 1) + return null; + return ty.Children[0]; + } + + + Node PopTypeAndGetAnyGeneric() + { + var child = PopTypeAndGetChild(); + if (child != null && IsAnyGeneric(child.Kind)) + return child; + return null; + } + + Node DemangleBuiltinType() + { + Node ty = null; + const int maxTypeSize = 4096; + switch (NextChar()) + { + case 'b': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); + break; + case 'B': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); + break; + case 'f': + { + var size = DemangleIndex() - 1; + if (size <= 0 || size > maxTypeSize) + return null; + var floatName = $"Builtin.FPIEEE{size}"; + ty = new Node(NodeKind.BuiltinTypeName, floatName); + break; + } + case 'i': + { + var size = DemangleIndex() - 1; + if (size < 0 || size > maxTypeSize) + return null; + var intName = $"Builtin.Int{size}"; + ty = new Node(NodeKind.BuiltinTypeName, intName); + break; + } + case 'I': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.IntLiteral"); + break; + case 'v': + var elts = DemangleIndex() - 1; + if (elts <= 0 || elts > maxTypeSize) + return null; + var eltType = PopTypeAndGetChild(); + if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || + !eltType.Text.StartsWith("Builtin.", StringComparison.Ordinal)) + return null; + var name = $"Builtin.Vec{elts}x{eltType.Text.Substring("Builtin.".Length)}"; + ty = new Node(NodeKind.BuiltinTypeName, name); + break; + case 'O': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); + break; + case 'o': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.NativeObject"); + break; + case 'p': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.RawPointer"); + break; + case 't': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.SILToken"); + break; + case 'w': + ty = new Node(NodeKind.BuiltinTypeName, "Builtin.Word"); + break; + default: + return null; + } + return CreateType(ty); + } + + Node DemangleAnyGenericType(NodeKind kind) + { + var name = PopNode(IsDeclName); + var ctx = PopContext(); + var nty = CreateType(CreateWithChildren(kind, ctx, name)); + AddSubstitution(nty); + return nty; + } + + Node DemangleExtensionContext() + { + var genSig = PopNode(NodeKind.DependentGenericSignature); + var module = PopModule(); + var type = PopTypeAndGetAnyGeneric(); + var ext = CreateWithChildren(NodeKind.Extension, module, type); + if (genSig != null) + ext = AddChild(ext, genSig); + return ext; + } + + Node DemanglePlainFunction() + { + var genSig = PopNode(NodeKind.DependentGenericSignature); + var type = PopFunctionType(NodeKind.FunctionType); + var labelList = PopFunctionParamLabels(type); + + if (genSig != null) + { + type = CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, type)); + } + + var name = PopNode(IsDeclName); + var ctx = PopContext(); + + if (labelList != null) + return CreateWithChildren(NodeKind.Function, ctx, name, labelList, type); + return CreateWithChildren(NodeKind.Function, ctx, name, type); + } + + + Node PopFunctionType(NodeKind kind) + { + var funcType = new Node(kind); + AddChild(funcType, PopNode(NodeKind.ThrowsAnnotation)); + funcType = AddChild(funcType, PopFunctionParams(NodeKind.ArgumentTuple)); + funcType = AddChild(funcType, PopFunctionParams(NodeKind.ReturnType)); + return CreateType(funcType); + } + + Node PopFunctionParams(NodeKind kind) + { + Node paramsType = null; + if (PopNode(NodeKind.EmptyList) != null) + { + paramsType = CreateType(new Node(NodeKind.Tuple)); + } + else + { + paramsType = PopNode(NodeKind.Type); + } + Node node = null; + + if (paramsType != null && kind == NodeKind.ArgumentTuple) + { + var @params = paramsType.Children[0]; + var numParams = @params.Kind == NodeKind.Tuple ? @params.Children.Count : 1; + node = new Node(kind, numParams); + } + else + { + node = new Node(kind); + } + + return AddChild(node, paramsType); + } + + Node PopFunctionParamLabels(Node type) + { + if (!isOldFunctionTypeMangling && PopNode(NodeKind.EmptyList) != null) + return new Node(NodeKind.LabelList); + + if (type == null || type.Kind != NodeKind.Type) + return null; + + var funcType = type.Children[0]; + if (funcType.Kind == NodeKind.DependentGenericType) + funcType = funcType.Children[1].Children[0]; + + if (funcType.Kind != NodeKind.FunctionType && funcType.Kind != NodeKind.NoEscapeFunctionType) + return null; + + var parameterType = funcType.Children[0]; + if (parameterType.Kind == NodeKind.ThrowsAnnotation) + parameterType = funcType.Children[1]; + + + if (parameterType.Index == 0) + return null; + + Func> getChildIf = (node, filterBy) => + { + for (int i = 0, n = node.Children.Count; i != n; ++i) + { + var child = node.Children[i]; + if (child.Kind == filterBy) + return new KeyValuePair(child, i); + } + return new KeyValuePair(null, 0); + }; + + Func getLabel = (@params, idx) => + { + if (isOldFunctionTypeMangling) + { + var param = @params.Children[idx]; + var label = getChildIf(param, NodeKind.TupleElementName); + + if (label.Key != null) + { + param.RemoveChildAt(label.Value); + return new Node(NodeKind.Identifier, label.Key.Text); + } + return new Node(NodeKind.FirstElementMarker); + } + return PopNode(); + }; + + var labelList = new Node(NodeKind.LabelList); + var tuple = parameterType.Children[0].Children[0]; + + if (isOldFunctionTypeMangling && (tuple != null || tuple.Kind != NodeKind.Tuple)) + return labelList; + + var hasLabels = false; + for (int i = 0; i != parameterType.Index; ++i) + { + var label = getLabel(tuple, i); + if (label == null) + return null; + + if (label.Kind != NodeKind.Identifier && label.Kind != NodeKind.FirstElementMarker) + return null; + + labelList.AddChild(label); + hasLabels |= label.Kind != NodeKind.FirstElementMarker; + } + + if (!hasLabels) + return new Node(NodeKind.LabelList); + + if (!isOldFunctionTypeMangling) + labelList.ReverseChildren(); + + return labelList; + } + + Node PopTuple() + { + var root = new Node(NodeKind.Tuple); + + if (PopNode(NodeKind.EmptyList) == null) + { + var firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker)) != null; + var tupleElmt = new Node(NodeKind.TupleElement); + AddChild(tupleElmt, PopNode(NodeKind.VariadicMarker)); + Node ident; + if ((ident = PopNode(NodeKind.Identifier)) != null) + { + tupleElmt.AddChild(new Node(NodeKind.TupleElementName, ident.Text)); + } + var ty = PopNode(NodeKind.Type); + if (ty == null) + return null; + tupleElmt.AddChild(ty); + root.AddChild(tupleElmt); + } while (!firstElem); + + root.ReverseChildren(); + } + return CreateType(root); + } + + Node PopTypeList() + { + var root = new Node(NodeKind.TypeList); + + if (PopNode(NodeKind.EmptyList) == null) + { + var firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker) != null); + var ty = PopNode(NodeKind.Type); + if (ty == null) + return ty; + root.AddChild(ty); + } while (!firstElem); + root.ReverseChildren(); + } + return root; + } + + Node PopProtocol() + { + Node type; + if ((type = PopNode(NodeKind.Type)) != null) + { + if (type.Children.Count < 1) + return null; + + if (!IsProtocolNode(type)) + return null; + return type; + } + + Node symbolicRef; + if ((symbolicRef = PopNode(NodeKind.ProtocolSymbolicReference)) != null) + { + return symbolicRef; + } + + var name = PopNode(IsDeclName); + var ctx = PopContext(); + var proto = CreateWithChildren(NodeKind.Protocol, ctx, name); + return CreateType(proto); + } + + Node PopAnyProtocolConformanceList() + { + var conformanceList = new Node(NodeKind.AnyProtocolConformanceList); + if (PopNode(NodeKind.EmptyList) == null) + { + var firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker) != null); + var anyConformance = PopAnyProtocolConformance(); + if (anyConformance == null) + return null; + conformanceList.AddChild(anyConformance); + } while (!firstElem); + conformanceList.ReverseChildren(); + } + return conformanceList; + } + + Node PopAnyProtocolConformance() + { + return PopNode((kind) => + { + switch (kind) + { + case NodeKind.ConcreteProtocolConformance: + case NodeKind.DependentProtocolConformanceRoot: + case NodeKind.DependentProtocolConformanceInherited: + case NodeKind.DependentProtocolConformanceAssociated: + return true; + default: + return false; + } + }); + } + + Node DemangleRetroactiveProtocolConformanceRef() + { + var module = PopModule(); + var proto = PopProtocol(); + var protocolConformanceRef = CreateWithChildren(NodeKind.ProtocolConformanceRefInOtherModule, proto, module); + return protocolConformanceRef; + } + + Node DemangleConcreteProtocolConformance() + { + var conditionalConformanceList = PopAnyProtocolConformanceList(); + + var conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInTypeModule); + if (conformanceRef == null) + { + conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInProtocolModule); + } + if (conformanceRef == null) + conformanceRef = DemangleRetroactiveProtocolConformanceRef(); + + var type = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.ConcreteProtocolConformance, + type, conformanceRef, conditionalConformanceList); + } + + + Node DemangleProtocolConformance() + { + var conditionalConformanceList = PopAnyProtocolConformanceList(); + + var conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInTypeModule); + if (conformanceRef == null) + { + conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInProtocolModule); + } + + if (conformanceRef == null) + conformanceRef = DemangleRetroactiveProtocolConformanceRef(); + + var type = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.ConcreteProtocolConformance, type, conformanceRef, conditionalConformanceList); + } + + Node PopDependentProtocolConformance() + { + return PopNode((kind) => + { + switch (kind) + { + case NodeKind.DependentProtocolConformanceRoot: + case NodeKind.DependentProtocolConformanceInherited: + case NodeKind.DependentProtocolConformanceAssociated: + return true; + default: + return false; + } + }); + } + + Node DemangleDependentProtocolConformanceRoot() + { + var index = DemangleIndex(); + var conformance = + index > 0 ? new Node(NodeKind.DependentProtocolConformanceRoot, index - 1) + : new Node(NodeKind.DependentProtocolConformanceRoot); + Node protocol = null; + if ((protocol = PopProtocol()) != null) + conformance.AddChild(protocol); + else + return null; + + Node dependentType; + if ((dependentType = PopNode(NodeKind.Type)) != null) + conformance.AddChild(dependentType); + else + return null; + + return conformance; + } + + Node DemangleDependentProtocolConformanceInherited() + { + var index = DemangleIndex(); + var conformance = + index > 0 ? new Node(NodeKind.DependentProtocolConformanceInherited, index - 1) + : new Node(NodeKind.DependentProtocolConformanceInherited); + Node protocol; + if ((protocol = PopProtocol()) != null) + conformance.AddChild(protocol); + else + return null; + + Node nested; + + if ((nested = PopDependentProtocolConformance()) != null) + conformance.AddChild(nested); + else + return null; + + conformance.ReverseChildren(); + return conformance; + } + + Node PopDependentAssociatedConformance() + { + var protocol = PopProtocol(); + var dependentType = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.DependentAssociatedConformance, dependentType, protocol); + } + + Node DemangleDependentProtocolConformanceAssociated() + { + var index = DemangleIndex(); + var conformance = index > 0 ? new Node(NodeKind.DependentProtocolConformanceRoot, index - 1) + : new Node(NodeKind.DependentProtocolConformanceRoot); + + Node associatedConformance; + if ((associatedConformance = PopDependentAssociatedConformance()) != null) + conformance.AddChild(associatedConformance); + else + return null; + + Node nested; + if ((nested = PopDependentProtocolConformance()) != null) + conformance.AddChild(nested); + else + return null; + + conformance.ReverseChildren(); + + return conformance; + } + + Node DemangleRetroactiveConformance() + { + var index = DemangleIndex(); + if (index < 0) + return null; + + var conformance = PopAnyProtocolConformance(); + if (conformance == null) + return null; + + var retroactiveConformance = new Node(NodeKind.RetroactiveConformance, index); + retroactiveConformance.AddChild(conformance); + return retroactiveConformance; + } + + Node DemangleBoundGenericType() + { + Node retroactiveConformances = null; + Node retroactiveConformance; + while ((retroactiveConformance = PopNode(NodeKind.RetroactiveConformance)) != null) + { + if (retroactiveConformances == null) + retroactiveConformances = new Node(NodeKind.TypeList); + retroactiveConformances.AddChild(retroactiveConformance); + } + if (retroactiveConformances != null) + retroactiveConformances.ReverseChildren(); + + var typeListList = new List(); + for (; ; ) + { + var tlist = new Node(NodeKind.TypeList); + typeListList.Add(tlist); + Node ty; + while ((ty = PopNode(NodeKind.Type)) != null) + { + tlist.AddChild(ty); + } + tlist.ReverseChildren(); + if (PopNode(NodeKind.EmptyList) != null) + break; + if (PopNode(NodeKind.FirstElementMarker) == null) + return null; + } + var nominal = PopTypeAndGetAnyGeneric(); + var boundNode = DemangleBoundGenericArgs(nominal, typeListList, 0); + AddChild(boundNode, retroactiveConformances); + var nty = CreateType(boundNode); + AddSubstitution(nty); + return nty; + } + + Node DemangleBoundGenericArgs(Node nominal, List typeLists, int typeListIdx) + { + if (nominal == null) + return null; + + if (typeListIdx >= typeLists.Count) + return null; + + if (nominal.Kind == NodeKind.TypeSymbolicReference || nominal.Kind == NodeKind.ProtocolSymbolicReference) + { + var remainingTypeList = new Node(NodeKind.TypeList); + for (int i = typeLists.Count - 1; i >= typeListIdx && i < typeLists.Count; --i) + { + var list = typeLists[i]; + foreach (var child in list.Children) + { + remainingTypeList.AddChild(child); + } + } + return CreateWithChildren(NodeKind.BoundGenericOtherNominalType, CreateType(nominal), remainingTypeList); + } + + if (nominal.Children.Count == 0) + return null; + var context = nominal.Children[0]; + + var consumesGenericArgs = true; + switch (nominal.Kind) + { + case NodeKind.Variable: + case NodeKind.ExplicitClosure: + case NodeKind.Subscript: + consumesGenericArgs = false; + break; + default: + break; + } + + var args = typeLists[typeListIdx]; + if (consumesGenericArgs) + ++typeListIdx; + + if (typeListIdx < typeLists.Count) + { + Node boundParent = null; + if (context.Kind == NodeKind.Extension) + { + boundParent = DemangleBoundGenericArgs(context.Children[1], typeLists, typeListIdx); + boundParent = CreateWithChildren(NodeKind.Extension, context.Children[0], boundParent); + if (context.Children.Count == 3) + { + AddChild(boundParent, context.Children[2]); + } + } + else + { + boundParent = DemangleBoundGenericArgs(context, typeLists, typeListIdx); + } + + var newNominal = CreateWithChild(nominal.Kind, boundParent); + if (newNominal == null) + return null; + + for (int idx = 1; idx < nominal.Children.Count; ++idx) + { + AddChild(newNominal, nominal.Children[idx]); + } + nominal = newNominal; + } + if (!consumesGenericArgs) + return nominal; + + if (args.Children.Count == 0) + return nominal; + + NodeKind kind; + switch (nominal.Kind) + { + case NodeKind.Class: + kind = NodeKind.BoundGenericClass; + break; + case NodeKind.Structure: + kind = NodeKind.BoundGenericStructure; + break; + case NodeKind.Enum: + kind = NodeKind.BoundGenericEnum; + break; + case NodeKind.Protocol: + kind = NodeKind.BoundGenericProtocol; + break; + case NodeKind.OtherNominalType: + kind = NodeKind.BoundGenericOtherNominalType; + break; + case NodeKind.TypeAlias: + kind = NodeKind.BoundGenericTypeAlias; + break; + case NodeKind.Function: + case NodeKind.Constructor: + return CreateWithChildren(NodeKind.BoundGenericFunction, nominal, args); + default: + return null; + } + return CreateWithChildren(kind, CreateType(nominal), args); + } + + Node DemangleImpleParamConvention() + { + string attr = null; + switch (NextChar()) + { + case 'i': attr = "@in"; break; + case 'c': attr = "@in_constant"; break; + case 'l': attr = "@inout"; break; + case 'b': attr = "@inout_aliasable"; break; + case 'n': attr = "@in_guaranteed"; break; + case 'x': attr = "@owned"; break; + case 'g': attr = "@guaranteed"; break; + case 'e': attr = "@deallocating"; break; + case 'y': attr = "@unowned"; break; + default: + PushBack(); + return null; + } + return CreateWithChild(NodeKind.ImplParameter, new Node(NodeKind.ImplConvention, attr)); + } + + Node DemangleImplResultConvention(NodeKind convKind) + { + string attr = null; + switch (NextChar()) + { + case 'r': attr = "@out"; break; + case 'o': attr = "@owned"; break; + case 'd': attr = "@unowned"; break; + case 'u': attr = "@unowned_inner_pointer"; break; + case 'a': attr = "@autoreleased"; break; + default: + PushBack(); + return null; + } + return CreateWithChild(convKind, new Node(NodeKind.ImplConvention, attr)); + } + + Node DemangleImplFunctionType() + { + var type = new Node(NodeKind.ImplFunctionType); + + var genSig = PopNode(NodeKind.DependentGenericSignature); + if (genSig != null && NextIf('P')) + genSig = ChangeKind(genSig, NodeKind.DependentPseudogenericSignature); + + if (NextIf('e')) + type.AddChild(new Node(NodeKind.ImplEscaping)); + + string cattr = null; + switch (NextChar()) + { + case 'y': cattr = "@callee_unowned"; break; + case 'g': cattr = "@callee_guaranteed"; break; + case 'x': cattr = "@callee_owned"; break; + case 't': cattr = "@convention(thin)"; break; + default: + return null; + } + type.AddChild(new Node(NodeKind.ImplConvention, cattr)); + + string fattr = null; + switch (NextChar()) + { + case 'B': fattr = "@convention(block)"; break; + case 'C': fattr = "@convention(c)"; break; + case 'M': fattr = "@convention(method)"; break; + case 'O': fattr = "@convention(objc_method)"; break; + case 'K': fattr = "@convention(closure)"; break; + case 'W': fattr = "@convention(witness_method)"; break; + default: + PushBack(); + break; + } + if (fattr != null) + type.AddChild(new Node(NodeKind.ImplFunctionAttribute, fattr)); + + AddChild(type, genSig); + + var numTypesToAdd = 0; + Node param; + while ((param = DemangleImpleParamConvention()) != null) + { + type = AddChild(type, param); + numTypesToAdd++; + } + Node result; + while ((result = DemangleImplResultConvention(NodeKind.ImplResult)) != null) + { + type = AddChild(type, result); + numTypesToAdd++; + } + if (NextIf('z')) + { + var errorResult = DemangleImplResultConvention(NodeKind.ImplErrorResult); + if (errorResult == null) + return null; + type = AddChild(type, errorResult); + numTypesToAdd++; + } + if (!NextIf('_')) + return null; + + for (int idx = 0; idx < numTypesToAdd; ++idx) + { + var convTy = PopNode(NodeKind.Type); + if (convTy == null) + return null; + type.Children[type.Children.Count - idx - 1].AddChild(convTy); + } + + return CreateType(type); + } + + Node DemangleMetatype() + { + switch (NextChar()) + { + case 'c': + return CreateWithChild(NodeKind.ProtocolConformanceDescriptor, PopProtocolConformance()); + case 'f': + return CreateWithPoppedType(NodeKind.FullTypeMetadata); + case 'P': + return CreateWithPoppedType(NodeKind.GenericTypeMetadataPattern); + case 'a': + return CreateWithPoppedType(NodeKind.TypeMetadataAccessFunction); + case 'I': + return CreateWithPoppedType(NodeKind.TypeMetadataInstantiationCache); + case 'i': + return CreateWithPoppedType(NodeKind.TypeMetadataInstantiationFunction); + case 'r': + return CreateWithPoppedType(NodeKind.TypeMetadataCompletionFunction); + case 'l': + return CreateWithPoppedType( + NodeKind.TypeMetadataSingletonInitializationCache); + case 'L': + return CreateWithPoppedType(NodeKind.TypeMetadataLazyCache); + case 'm': + return CreateWithPoppedType(NodeKind.Metaclass); + case 'n': + return CreateWithPoppedType(NodeKind.NominalTypeDescriptor); + case 'o': + return CreateWithPoppedType(NodeKind.ClassMetadataBaseOffset); + case 'p': + return CreateWithChild(NodeKind.ProtocolDescriptor, PopProtocol()); + case 'S': + return CreateWithChild(NodeKind.ProtocolSelfConformanceDescriptor, + PopProtocol()); + case 'u': + return CreateWithPoppedType(NodeKind.MethodLookupFunction); + case 'U': + return CreateWithPoppedType(NodeKind.ObjCMetadataUpdateFunction); + case 'B': + return CreateWithChild(NodeKind.ReflectionMetadataBuiltinDescriptor, + PopNode(NodeKind.Type)); + case 'F': + return CreateWithChild(NodeKind.ReflectionMetadataFieldDescriptor, + PopNode(NodeKind.Type)); + case 'A': + return CreateWithChild(NodeKind.ReflectionMetadataAssocTypeDescriptor, + PopProtocolConformance()); + case 'C': + { + Node Ty = PopNode(NodeKind.Type); + if (Ty == null || !IsAnyGeneric(Ty.Children[0].Kind)) + return null; + return CreateWithChild(NodeKind.ReflectionMetadataSuperclassDescriptor, + Ty.Children[0]); + } + case 'V': + return CreateWithChild(NodeKind.PropertyDescriptor, + PopNode(IsEntity)); + case 'X': + return DemanglePrivateContextDescriptor(); + default: + return null; + } + } + + Node DemanglePrivateContextDescriptor() + { + switch (NextChar()) + { + case 'E': + { + var extension = PopContext(); + if (extension == null) + return null; + return CreateWithChild(NodeKind.ExtensionDescriptor, extension); + } + case 'M': + { + var module = PopModule(); + if (module == null) + return null; + return CreateWithChild(NodeKind.ModuleDescriptor, module); + } + case 'Y': + { + var discriminator = PopNode(); + if (discriminator == null) + return null; + var context = PopContext(); + if (context == null) + return null; + + var node = new Node(NodeKind.AnonymousDescriptor); + node.AddChild(context); + node.AddChild(discriminator); + return node; + } + case 'X': + { + var context = PopContext(); + if (context == null) + return null; + return CreateWithChild(NodeKind.AnonymousDescriptor, context); + } + case 'A': + { + var path = PopAssocTypePath(); + if (path == null) + return null; + var @base = PopNode(NodeKind.Type); + if (@base == null) + return null; + return CreateWithChildren(NodeKind.AssociatedTypeGenericParamRef, + @base, path); + } + default: + return null; + } + } + + Node DemangleArchetype() + { + switch (NextChar()) + { + case 'a': + { + var ident = PopNode(NodeKind.Identifier); + var archeTy = PopTypeAndGetChild(); + var assocTy = CreateType(CreateWithChildren(NodeKind.AssociatedTypeRef, archeTy, ident)); + AddSubstitution(assocTy); + return assocTy; + } + case 'y': + { + var t = DemangleAssociatedTypeSimple(DemangleGenericParamIndex()); + AddSubstitution(t); + return t; + } + case 'z': + { + var t = DemangleAssociatedTypeSimple(GetDependentGenericParamType(0, 0)); + AddSubstitution(t); + return t; + } + case 'Y': + { + var t = DemangleAssociatedTypeCompound(DemangleGenericParamIndex()); + AddSubstitution(t); + return t; + } + case 'Z': + { + var t = DemangleAssociatedTypeCompound(GetDependentGenericParamType(0, 0)); + AddSubstitution(t); + return t; + } + default: + return null; + } + } + + Node DemangleAssociatedTypeSimple(Node genericParamIdx) + { + var GPI = CreateType(genericParamIdx); + var ATName = PopAssocTypeName(); + return CreateType(CreateWithChildren(NodeKind.DependentMemberType, GPI, ATName)); + } + + Node DemangleAssociatedTypeCompound(Node genericParamIdx) + { + var assocTyNames = new List(); + bool firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker) != null); + var assocTyName = PopAssocTypeName(); + if (assocTyName == null) + return null; + assocTyNames.Add(assocTyName); + } while (!firstElem); + + var @base = genericParamIdx; + + + for (int i = assocTyNames.Count - 1; i >= 0; --i) + { + var assocTy = assocTyNames[i]; + var depTy = new Node(NodeKind.DependentMemberType); + depTy = AddChild(depTy, CreateType(@base)); + @base = AddChild(depTy, assocTy); + } + return CreateType(@base); + } + + Node PopAssocTypeName() + { + var proto = PopNode(NodeKind.Type); + if (proto != null && !IsProtocolNode(proto)) + return null; + + // If we haven't seen a protocol, check for a symbolic reference. + if (proto == null) + proto = PopNode(NodeKind.ProtocolSymbolicReference); + + var id = PopNode(NodeKind.Identifier); + var assocTy = ChangeKind(id, NodeKind.DependentAssociatedTypeRef); + AddChild(assocTy, proto); + return assocTy; + } + + Node PopAssocTypePath() + { + var assocTypePath = new Node(NodeKind.AssocTypePath); + bool firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker) != null); + var assocTy = PopAssocTypeName(); + if (assocTy == null) + return null; + assocTypePath.AddChild(assocTy); + } while (!firstElem); + assocTypePath.ReverseChildren(); + return assocTypePath; + } + + Node GetDependentGenericParamType(int depth, int index) + { + if (depth < 0 || index < 0) + return null; + + StringBuilder name = new StringBuilder(); + int idxChar = index; + do + { + name.Append((char)('A' + (idxChar % 26))); + idxChar /= 26; + } while (idxChar > 0); + if (depth != 0) + name.Append(depth); + + var paramTy = new Node(NodeKind.DependentGenericParamType, name.ToString()); + paramTy.AddChild(new Node(NodeKind.Index, depth)); + paramTy.AddChild(new Node(NodeKind.Index, index)); + return paramTy; + } + + Node DemangleGenericParamIndex() + { + if (NextIf('d')) + { + int depth = DemangleIndex() + 1; + int index = DemangleIndex(); + return GetDependentGenericParamType(depth, index); + } + if (NextIf('z')) + { + return GetDependentGenericParamType(0, 0); + } + return GetDependentGenericParamType(0, DemangleIndex() + 1); + } + + Node PopProtocolConformance() + { + var genSig = PopNode(NodeKind.DependentGenericSignature); + var module = PopModule(); + var proto = PopProtocol(); + var type = PopNode(NodeKind.Type); + Node Ident = null; + if (type == null) + { + // Property behavior conformance + Ident = PopNode(NodeKind.Identifier); + type = PopNode(NodeKind.Type); + } + if (genSig != null) + { + type = CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, type)); + } + var Conf = CreateWithChildren(NodeKind.ProtocolConformance, type, proto, module); + AddChild(Conf, Ident); + return Conf; + } + + Node DemangleThunkOrSpecialization() + { + var c = NextChar(); + switch (c) + { + case 'c': return CreateWithChild(NodeKind.CurryThunk, PopNode(IsEntity)); + case 'j': return CreateWithChild(NodeKind.DispatchThunk, PopNode(IsEntity)); + case 'q': return CreateWithChild(NodeKind.MethodDescriptor, PopNode(IsEntity)); + case 'o': return new Node(NodeKind.ObjCAttribute); + case 'O': return new Node(NodeKind.NonObjCAttribute); + case 'D': return new Node(NodeKind.DynamicAttribute); + case 'd': return new Node(NodeKind.DirectMethodReferenceAttribute); + case 'a': return new Node(NodeKind.PartialApplyObjCForwarder); + case 'A': return new Node(NodeKind.PartialApplyForwarder); + case 'm': return new Node(NodeKind.MergedFunction); + case 'X': return new Node(NodeKind.DynamicallyReplaceableFunctionVar); + case 'x': return new Node(NodeKind.DynamicallyReplaceableFunctionKey); + case 'I': return new Node(NodeKind.DynamicallyReplaceableFunctionImpl); + case 'C': + { + var type = PopNode(NodeKind.Type); + return CreateWithChild(NodeKind.CoroutineContinuationPrototype, type); + } + case 'V': + { + var @base = PopNode(IsEntity); + var derived = PopNode(IsEntity); + return CreateWithChildren(NodeKind.VTableThunk, derived, @base); + } + case 'W': + { + var entity = PopNode(IsEntity); + var conf = PopProtocolConformance(); + return CreateWithChildren(NodeKind.ProtocolWitness, conf, entity); + } + case 'S': + return CreateWithChild(NodeKind.ProtocolSelfConformanceWitness, + PopNode(IsEntity)); + case 'R': + case 'r': + { + var thunk = new Node(c == 'R' ? + NodeKind.ReabstractionThunkHelper : + NodeKind.ReabstractionThunk); + Node genSig; + if ((genSig = PopNode(NodeKind.DependentGenericSignature)) != null) + AddChild(thunk, genSig); + var Ty2 = PopNode(NodeKind.Type); + thunk = AddChild(thunk, PopNode(NodeKind.Type)); + return AddChild(thunk, Ty2); + } + case 'g': + return DemangleGenericSpecialization(NodeKind.GenericSpecialization); + case 'G': + return DemangleGenericSpecialization(NodeKind.GenericSpecializationNotReAbstracted); + case 'i': + return DemangleGenericSpecialization(NodeKind.InlinedGenericFunction); + case 'p': + { + var spec = DemangleSpecAttributes(NodeKind.GenericPartialSpecialization); + var param = CreateWithChild(NodeKind.GenericSpecializationParam, PopNode(NodeKind.Type)); + return AddChild(spec, param); + } + case 'P': + { + var spec = DemangleSpecAttributes(NodeKind.GenericPartialSpecializationNotReAbstracted); + var param = CreateWithChild(NodeKind.GenericSpecializationParam, PopNode(NodeKind.Type)); + return AddChild(spec, param); + } + case 'f': + return DemangleFunctionSpecialization(); + case 'K': + case 'k': + { + var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper + : NodeKind.KeyPathSetterThunkHelper; + var types = new List(); + var node = PopNode(); + if (node == null || node.Kind != NodeKind.Type) + return null; + do + { + types.Add(node); + node = PopNode(); + } while (node != null && node.Kind == NodeKind.Type); + + Node result; + if (node != null) + { + if (node.Kind == NodeKind.DependentGenericSignature) + { + var decl = PopNode(); + if (decl == null) + return null; + result = CreateWithChildren(nodeKind, decl, /*sig*/ node); + } + else + { + result = CreateWithChild(nodeKind, /*decl*/ node); + } + } + else + { + return null; + } + foreach (var i in types) + { + result.AddChild(i); + } + return result; + } + case 'l': + { + var assocTypeName = PopAssocTypeName(); + if (assocTypeName == null) + return null; + + return CreateWithChild(NodeKind.AssociatedTypeDescriptor, + assocTypeName); + } + case 'L': + return CreateWithChild(NodeKind.ProtocolRequirementsBaseDescriptor, + PopProtocol()); + case 'M': + return CreateWithChild(NodeKind.DefaultAssociatedTypeMetadataAccessor, + PopAssocTypeName()); + + case 'n': + { + var requirementTy = PopProtocol(); + var conformingType = PopAssocTypePath(); + var protoTy = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.AssociatedConformanceDescriptor, + protoTy, conformingType, requirementTy); + } + + case 'N': + { + var requirementTy = PopProtocol(); + var assocTypePath = PopAssocTypePath(); + var protoTy = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.DefaultAssociatedConformanceAccessor, + protoTy, assocTypePath, requirementTy); + } + + case 'b': + { + var requirementTy = PopProtocol(); + var protoTy = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.BaseConformanceDescriptor, + protoTy, requirementTy); + } + + case 'H': + case 'h': + { + var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper + : NodeKind.KeyPathHashThunkHelper; + Node genericSig = null; + var types = new List(); + + var node = PopNode(); + if (node != null) + { + if (node.Kind == NodeKind.DependentGenericSignature) + { + genericSig = node; + } + else if (node.Kind == NodeKind.Type) + { + types.Add(node); + } + else + { + return null; + } + } + else + { + return null; + } + + Node node1; + while ((node1 = PopNode()) != null) + { + if (node1.Kind != NodeKind.Type) + { + return null; + } + types.Add(node); + } + + var result = new Node(nodeKind); + foreach (var i in types) + { + result.AddChild(i); + } + if (genericSig != null) + result.AddChild(genericSig); + return result; + } + case 'v': + { + int idx = DemangleIndex(); + if (idx < 0) + return null; + return new Node(NodeKind.OutlinedVariable, idx); + } + case 'e': + { + string @params = DemangleBridgedMethodParams(); + if (string.IsNullOrEmpty(@params)) + return null; + return new Node(NodeKind.OutlinedBridgedMethod, @params); + } + default: + return null; + } + } + + string DemangleBridgedMethodParams() + { + if (NextIf('_')) + return ""; + + StringBuilder Str = new StringBuilder(); + + var kind = NextChar(); + switch (kind) + { + default: + return ""; + case 'p': + case 'a': + case 'm': + Str.Append(kind); + break; + } + + while (!NextIf('_')) + { + var c = NextChar(); + if (c != 0 && c != 'n' && c != 'b') + return ""; + Str.Append(c); + } + return Str.ToString(); + } + + Node DemangleGenericSpecialization(NodeKind SpecKind) + { + var Spec = DemangleSpecAttributes(SpecKind); + if (Spec == null) + return null; + var TyList = PopTypeList(); + if (TyList == null) + return null; + foreach (var Ty in TyList.Children) + { + Spec.AddChild(CreateWithChild(NodeKind.GenericSpecializationParam, Ty)); + } + return Spec; + } + + + Node DemangleFunctionSpecialization() + { + var spec = DemangleSpecAttributes(NodeKind.FunctionSignatureSpecialization); + ulong paramIdx = 0; + while (spec != null && !NextIf('_')) + { + spec = AddChild(spec, DemangleFuncSpecParam(paramIdx)); + paramIdx++; + } + if (!NextIf('n')) + spec = AddChild(spec, DemangleFuncSpecParam((~(ulong)0))); + + if (spec == null) + return null; + + // Add the required parameters in reverse order. + for (int idx = 0, num = spec.Children.Count; idx < num; ++idx) + { + var param = spec.Children[num - idx - 1]; + if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) + continue; + + if (param.Children.Count == 0) + continue; + var kindNd = param.Children[0]; + var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; + switch (paramKind) + { + case FunctionSigSpecializationParamKind.ConstantPropFunction: + case FunctionSigSpecializationParamKind.ConstantPropGlobal: + case FunctionSigSpecializationParamKind.ConstantPropString: + case FunctionSigSpecializationParamKind.ClosureProp: + { + var fixedChildren = param.Children.Count; + Node ty; + while ((ty = PopNode(NodeKind.Type)) != null) + { + if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) + return null; + param = AddChild(param, ty); + } + var name = PopNode(NodeKind.Identifier); + if (name == null) + return null; + string nameText = name.Text; + if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && !String.IsNullOrEmpty(nameText) + && nameText[0] == '_') + { + // A '_' escapes a leading digit or '_' of a string constant. + nameText = nameText.Substring(1); + } + AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, nameText)); + param.ReverseChildren(fixedChildren); + break; + } + default: + break; + } + } + return spec; + } + + Node DemangleFuncSpecParam(ulong paramIdx) + { + var param = new Node(NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); + switch (NextChar()) + { + case 'n': + return param; + case 'c': + // Consumes an identifier and multiple type parameters. + // The parameters will be added later. + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ClosureProp)); + case 'p': + { + switch (NextChar()) + { + case 'f': + // Consumes an identifier parameter, which will be added later. + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (long)(FunctionSigSpecializationParamKind.ConstantPropFunction))); + case 'g': + // Consumes an identifier parameter, which will be added later. + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); + case 'i': + return AddFuncSpecParamNumber(param, FunctionSigSpecializationParamKind.ConstantPropInteger); + case 'd': + return AddFuncSpecParamNumber(param, FunctionSigSpecializationParamKind.ConstantPropFloat); + case 's': + { + // Consumes an identifier parameter (the string constant), + // which will be added later. + string encoding = null; + switch (NextChar()) + { + case 'b': encoding = "u8"; break; + case 'w': encoding = "u16"; break; + case 'c': encoding = "objc"; break; + default: return null; + } + AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (long)FunctionSigSpecializationParamKind.ConstantPropString)); + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); + } + default: + return null; + } + } + case 'e': + { + uint value = (uint)FunctionSigSpecializationParamKind.ExistentialToGeneric; + if (NextIf('D')) + value |= (uint)FunctionSigSpecializationParamKind.Dead; + if (NextIf('G')) + value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf('O')) + value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'd': + { + uint value = (uint)FunctionSigSpecializationParamKind.Dead; + if (NextIf('G')) + value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf('O')) + value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'g': + { + uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; + if (NextIf('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'o': + { + uint value = (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; + if (NextIf('X')) + value |= (uint)FunctionSigSpecializationParamKind.SROA; + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); + } + case 'x': + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.SROA)); + case 'i': + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.BoxToValue)); + case 's': + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, + (uint)FunctionSigSpecializationParamKind.BoxToStack)); + default: + return null; + } + } + + Node AddFuncSpecParamNumber(Node param, FunctionSigSpecializationParamKind kind) + { + param.AddChild(new Node(NodeKind.FunctionSignatureSpecializationParamKind, (uint)kind)); + var str = new StringBuilder(); + while (Char.IsDigit(PeekChar())) + { + str.Append(NextChar()); + } + if (str.Length == 0) + return null; + return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString())); + } + + Node DemangleSpecAttributes(NodeKind SpecKind) + { + bool isFragile = NextIf('q'); + + int passID = (int)NextChar() - '0'; + if (passID < 0 || passID > 9) + return null; + + var specNd = new Node(SpecKind); + if (isFragile) + specNd.AddChild(new Node(NodeKind.SpecializationIsFragile)); + + specNd.AddChild(new Node(NodeKind.SpecializationPassID, passID)); + return specNd; + } + + Node DemangleWitness() + { + switch (NextChar()) + { + case 'C': + return CreateWithChild(NodeKind.EnumCase, PopNode(IsEntity)); + case 'V': + return CreateWithChild(NodeKind.ValueWitnessTable, PopNode(NodeKind.Type)); + case 'v': + { + uint directness; + switch (NextChar()) + { + case 'd': directness = (uint)Directness.Direct; break; + case 'i': directness = (uint)Directness.Indirect; break; + default: return null; + } + return CreateWithChildren(NodeKind.FieldOffset, new Node(NodeKind.Directness, directness), + PopNode(IsEntity)); + } + case 'S': + return CreateWithChild(NodeKind.ProtocolSelfConformanceWitnessTable, PopProtocol()); + case 'P': + return CreateWithChild(NodeKind.ProtocolWitnessTable, PopProtocolConformance()); + case 'p': + return CreateWithChild(NodeKind.ProtocolWitnessTablePattern, PopProtocolConformance()); + case 'G': + return CreateWithChild(NodeKind.GenericProtocolWitnessTable, PopProtocolConformance()); + case 'I': + return CreateWithChild(NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance()); + + case 'r': + return CreateWithChild(NodeKind.ResilientProtocolWitnessTable, PopProtocolConformance()); + + case 'l': + { + var conf = PopProtocolConformance(); + var type = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.LazyProtocolWitnessTableAccessor, type, conf); + } + case 'L': + { + var conf = PopProtocolConformance(); + var type = PopNode(NodeKind.Type); + return CreateWithChildren(NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); + } + case 'a': + return CreateWithChild(NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance()); + case 't': + { + var name = PopNode(IsDeclName); + var conf = PopProtocolConformance(); + return CreateWithChildren(NodeKind.AssociatedTypeMetadataAccessor, conf, name); + } + case 'T': + { + var protoTy = PopNode(NodeKind.Type); + var conformingType = PopAssocTypePath(); + var conf = PopProtocolConformance(); + return CreateWithChildren(NodeKind.AssociatedTypeWitnessTableAccessor, conf, conformingType, protoTy); + } + case 'b': + { + var protoTy = PopNode(NodeKind.Type); + var conf = PopProtocolConformance(); + return CreateWithChildren(NodeKind.BaseWitnessTableAccessor, conf, protoTy); + } + case 'O': + { + switch (NextChar()) + { + case 'y': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedCopy, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedCopy, PopNode(NodeKind.Type)); + } + case 'e': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedConsume, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedConsume, PopNode(NodeKind.Type)); + } + case 'r': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedRetain, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedRetain, PopNode(NodeKind.Type)); + } + case 's': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedRelease, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedRelease, PopNode(NodeKind.Type)); + } + case 'b': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedInitializeWithTake, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedInitializeWithTake, PopNode(NodeKind.Type)); + } + case 'c': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedInitializeWithCopy, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedInitializeWithCopy, PopNode(NodeKind.Type)); + } + case 'd': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedAssignWithTake, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedAssignWithTake, PopNode(NodeKind.Type)); + } + case 'f': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedAssignWithCopy, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedAssignWithCopy, PopNode(NodeKind.Type)); + } + case 'h': + { + Node sig; + if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) + return CreateWithChildren(NodeKind.OutlinedDestroy, PopNode(NodeKind.Type), sig); + return CreateWithChild(NodeKind.OutlinedDestroy, PopNode(NodeKind.Type)); + } + default: + return null; + } + } + default: + return null; + } + } + + Node DemangleSpecialType() + { + char specialChar; + switch (specialChar = NextChar()) + { + case 'E': + return PopFunctionType(NodeKind.NoEscapeFunctionType); + case 'A': + return PopFunctionType(NodeKind.EscapingAutoClosureType); + case 'f': + return PopFunctionType(NodeKind.ThinFunctionType); + case 'K': + return PopFunctionType(NodeKind.AutoClosureType); + case 'U': + return PopFunctionType(NodeKind.UncurriedFunctionType); + case 'B': + return PopFunctionType(NodeKind.ObjCBlock); + case 'C': + return PopFunctionType(NodeKind.CFunctionPointer); + case 'o': + return CreateType(CreateWithChild(NodeKind.Unowned, PopNode(NodeKind.Type))); + case 'u': + return CreateType(CreateWithChild(NodeKind.Unmanaged, PopNode(NodeKind.Type))); + case 'w': + return CreateType(CreateWithChild(NodeKind.Weak, PopNode(NodeKind.Type))); + case 'b': + return CreateType(CreateWithChild(NodeKind.SILBoxType, PopNode(NodeKind.Type))); + case 'D': + return CreateType(CreateWithChild(NodeKind.DynamicSelf, PopNode(NodeKind.Type))); + case 'M': + { + var MTR = DemangleMetatypeRepresentation(); + var type = PopNode(NodeKind.Type); + return CreateType(CreateWithChildren(NodeKind.Metatype, MTR, type)); + } + case 'm': + { + var MTR = DemangleMetatypeRepresentation(); + var type = PopNode(NodeKind.Type); + return CreateType(CreateWithChildren(NodeKind.ExistentialMetatype, MTR, type)); + } + case 'p': + return CreateType(CreateWithChild(NodeKind.ExistentialMetatype, PopNode(NodeKind.Type))); + case 'c': + { + var Superclass = PopNode(NodeKind.Type); + var Protocols = DemangleProtocolList(); + return CreateType(CreateWithChildren(NodeKind.ProtocolListWithClass, Protocols, Superclass)); + } + case 'l': + { + var Protocols = DemangleProtocolList(); + return CreateType(CreateWithChild(NodeKind.ProtocolListWithAnyObject, Protocols)); + } + case 'X': + case 'x': + { + // SIL box types. + Node signature = null, genericArgs = null; + if (specialChar == 'X') + { + signature = PopNode(NodeKind.DependentGenericSignature); + if (signature == null) + return null; + genericArgs = PopTypeList(); + if (genericArgs == null) + return null; + } + + var fieldTypes = PopTypeList(); + if (fieldTypes == null) + return null; + // Build layout. + var layout = new Node(NodeKind.SILBoxLayout); + for (int i = 0, e = fieldTypes.Children.Count; i < e; ++i) + { + var fieldType = fieldTypes.Children[i]; + bool isMutable = false; + // 'inout' typelist mangling is used to represent mutable fields. + if (fieldType.Children[0].Kind == NodeKind.InOut) + { + isMutable = true; + fieldType = CreateType(fieldType.Children[0].Children[0]); + } + var field = new Node(isMutable + ? NodeKind.SILBoxMutableField + : NodeKind.SILBoxImmutableField); + field.AddChild(fieldType); + layout.AddChild(field); + } + var boxTy = new Node(NodeKind.SILBoxTypeWithLayout); + boxTy.AddChild(layout); + if (signature != null) + { + boxTy.AddChild(signature); + boxTy.AddChild(genericArgs); + } + return CreateType(boxTy); + } + case 'Y': + return DemangleAnyGenericType(NodeKind.OtherNominalType); + case 'Z': + { + var types = PopTypeList(); + var name = PopNode(NodeKind.Identifier); + var parent = PopContext(); + var anon = new Node(NodeKind.AnonymousContext); + anon = AddChild(anon, name); + anon = AddChild(anon, parent); + anon = AddChild(anon, types); + return anon; + } + case 'e': + return CreateType(new Node(NodeKind.ErrorType)); + default: + return null; + } + } + + Node DemangleMetatypeRepresentation() + { + switch (NextChar()) + { + case 't': + return new Node(NodeKind.MetatypeRepresentation, "@thin"); + case 'T': + return new Node(NodeKind.MetatypeRepresentation, "@thick"); + case 'o': + return new Node(NodeKind.MetatypeRepresentation, "@objc_metatype"); + default: + return null; + } + } + + Node DemangleAccessor(Node childNode) + { + NodeKind kind; + switch (NextChar()) + { + case 'm': kind = NodeKind.MaterializeForSet; break; + case 's': kind = NodeKind.Setter; break; + case 'g': kind = NodeKind.Getter; break; + case 'G': kind = NodeKind.GlobalGetter; break; + case 'w': kind = NodeKind.WillSet; break; + case 'W': kind = NodeKind.DidSet; break; + case 'r': kind = NodeKind.ReadAccessor; break; + case 'M': kind = NodeKind.ModifyAccessor; break; + case 'a': + switch (NextChar()) + { + case 'O': kind = NodeKind.OwningMutableAddressor; break; + case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; + case 'P': kind = NodeKind.NativePinningMutableAddressor; break; + case 'u': kind = NodeKind.UnsafeMutableAddressor; break; + default: return null; + } + break; + case 'l': + switch (NextChar()) + { + case 'O': kind = NodeKind.OwningAddressor; break; + case 'o': kind = NodeKind.NativeOwningAddressor; break; + case 'p': kind = NodeKind.NativePinningAddressor; break; + case 'u': kind = NodeKind.UnsafeAddressor; break; + default: return null; + } + break; + case 'p': // Pseudo-accessor referring to the variable/subscript itself + return childNode; + default: return null; + } + var entity = CreateWithChild(kind, childNode); + return entity; + } + + enum Args + { + None, + TypeAndMaybePrivateName, + TypeAndIndex, + Index + } + + Node DemangleFunctionEntity() + { + var args = Args.None; + NodeKind Kind = NodeKind.EmptyList; + switch (NextChar()) + { + case 'D': args = Args.None; Kind = NodeKind.Deallocator; break; + case 'd': args = Args.None; Kind = NodeKind.Destructor; break; + case 'E': args = Args.None; Kind = NodeKind.IVarDestroyer; break; + case 'e': args = Args.None; Kind = NodeKind.IVarInitializer; break; + case 'i': args = Args.None; Kind = NodeKind.Initializer; break; + case 'C': + args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Allocator; break; + case 'c': + args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Constructor; break; + case 'U': args = Args.TypeAndIndex; Kind = NodeKind.ExplicitClosure; break; + case 'u': args = Args.TypeAndIndex; Kind = NodeKind.ImplicitClosure; break; + case 'A': args = Args.Index; Kind = NodeKind.DefaultArgumentInitializer; break; + case 'p': return DemangleEntity(NodeKind.GenericTypeParamDecl); + default: return null; + } + + Node nameOrIndex = null, paramType = null, labelList = null; + switch (args) + { + case Args.None: + break; + case Args.TypeAndMaybePrivateName: + nameOrIndex = PopNode(NodeKind.PrivateDeclName); + paramType = PopNode(NodeKind.Type); + labelList = PopFunctionParamLabels(paramType); + break; + case Args.TypeAndIndex: + nameOrIndex = DemangleIndexAsNode(); + paramType = PopNode(NodeKind.Type); + break; + case Args.Index: + nameOrIndex = DemangleIndexAsNode(); + break; + } + var entity = CreateWithChild(Kind, PopContext()); + switch (args) + { + case Args.None: + break; + case Args.Index: + entity = AddChild(entity, nameOrIndex); + break; + case Args.TypeAndMaybePrivateName: + AddChild(entity, labelList); + entity = AddChild(entity, paramType); + AddChild(entity, nameOrIndex); + break; + case Args.TypeAndIndex: + entity = AddChild(entity, nameOrIndex); + entity = AddChild(entity, paramType); + break; + } + return entity; + } + + Node DemangleEntity(NodeKind Kind) + { + var type = PopNode(NodeKind.Type); + var labelList = PopFunctionParamLabels(type); + var name = PopNode(IsDeclName); + var context = PopContext(); + return labelList != null ? CreateWithChildren(Kind, context, name, labelList, type) + : CreateWithChildren(Kind, context, name, type); + } + + Node DemangleVariable() + { + var variable = DemangleEntity(NodeKind.Variable); + return DemangleAccessor(variable); + } + + Node DemangleSubscript() + { + var privateName = PopNode(NodeKind.PrivateDeclName); + var type = PopNode(NodeKind.Type); + var labelList = PopFunctionParamLabels(type); + var context = PopContext(); + + var subscript = new Node(NodeKind.Subscript); + subscript = AddChild(subscript, context); + AddChild(subscript, labelList); + subscript = AddChild(subscript, type); + AddChild(subscript, privateName); + + return DemangleAccessor(subscript); + } + + Node DemangleProtocolList() + { + var typeList = new Node(NodeKind.TypeList); + var protoList = CreateWithChild(NodeKind.ProtocolList, typeList); + if (PopNode(NodeKind.EmptyList) == null) + { + bool firstElem = false; + do + { + firstElem = (PopNode(NodeKind.FirstElementMarker) != null); + var proto = PopProtocol(); + if (proto == null) + return null; + typeList.AddChild(proto); + } while (!firstElem); + + typeList.ReverseChildren(); + } + return protoList; + } + + Node DemangleProtocolListType() + { + var protoList = DemangleProtocolList(); + return CreateType(protoList); + } + + Node DemangleGenericSignature(bool hasParamCounts) + { + var Sig = new Node(NodeKind.DependentGenericSignature); + if (hasParamCounts) + { + while (!NextIf('l')) + { + int count = 0; + if (!NextIf('z')) + count = DemangleIndex() + 1; + if (count < 0) + return null; + Sig.AddChild(new Node(NodeKind.DependentGenericParamCount, count)); + } + } + else + { + Sig.AddChild(new Node(NodeKind.DependentGenericParamCount, 1)); + } + var NumCounts = Sig.Children.Count; + Node Req; + while ((Req = PopNode(IsRequirement)) != null) + { + Sig.AddChild(Req); + } + Sig.ReverseChildren(NumCounts); + return Sig; + } + + enum TypeKind + { + Generic, + Assoc, + CompoundAssoc, + Substitution + } + + enum ConstraintKind + { + Protocol, + BaseClass, + SameType, + Layout + } + + Node DemangleGenericRequirement() + { + TypeKind typeKind; + ConstraintKind constraintKind; + + switch (NextChar()) + { + case 'c': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Assoc; break; + case 'C': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.CompoundAssoc; break; + case 'b': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Generic; break; + case 'B': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Substitution; break; + case 't': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Assoc; break; + case 'T': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.CompoundAssoc; break; + case 's': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Generic; break; + case 'S': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Substitution; break; + case 'm': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Assoc; break; + case 'M': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.CompoundAssoc; break; + case 'l': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Generic; break; + case 'L': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Substitution; break; + case 'p': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Assoc; break; + case 'P': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.CompoundAssoc; break; + case 'Q': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Substitution; break; + default: constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Generic; PushBack(); break; + } + + Node ConstrTy = null; + + switch (typeKind) + { + case TypeKind.Generic: + ConstrTy = CreateType(DemangleGenericParamIndex()); + break; + case TypeKind.Assoc: + ConstrTy = DemangleAssociatedTypeSimple(DemangleGenericParamIndex()); + AddSubstitution(ConstrTy); + break; + case TypeKind.CompoundAssoc: + ConstrTy = DemangleAssociatedTypeCompound(DemangleGenericParamIndex()); + AddSubstitution(ConstrTy); + break; + case TypeKind.Substitution: + ConstrTy = PopNode(NodeKind.Type); + break; + } + + switch (constraintKind) + { + case ConstraintKind.Protocol: + return CreateWithChildren(NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopProtocol()); + case ConstraintKind.BaseClass: + return CreateWithChildren(NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopNode(NodeKind.Type)); + case ConstraintKind.SameType: + return CreateWithChildren(NodeKind.DependentGenericSameTypeRequirement, ConstrTy, PopNode(NodeKind.Type)); + case ConstraintKind.Layout: + { + var c = NextChar(); + Node size = null; + Node alignment = null; + string name = null; + if (c == 'U') + { + name = "U"; + } + else if (c == 'R') + { + name = "R"; + } + else if (c == 'N') + { + name = "N"; + } + else if (c == 'C') + { + name = "C"; + } + else if (c == 'D') + { + name = "D"; + } + else if (c == 'T') + { + name = "T"; + } + else if (c == 'E') + { + size = DemangleIndexAsNode(); + if (size == null) + return null; + alignment = DemangleIndexAsNode(); + name = "E"; + } + else if (c == 'e') + { + size = DemangleIndexAsNode(); + if (size == null) + return null; + name = "e"; + } + else if (c == 'M') + { + size = DemangleIndexAsNode(); + if (size == null) + return null; + alignment = DemangleIndexAsNode(); + name = "M"; + } + else if (c == 'm') + { + size = DemangleIndexAsNode(); + if (size == null) + return null; + name = "m"; + } + else + { + // Unknown layout constraint. + return null; + } + + var NameNode = new Node(NodeKind.Identifier, name); + var LayoutRequirement = CreateWithChildren(NodeKind.DependentGenericLayoutRequirement, ConstrTy, NameNode); + if (size != null) + AddChild(LayoutRequirement, size); + if (alignment != null) + AddChild(LayoutRequirement, alignment); + return LayoutRequirement; + } + } + return null; + } + + Node DemangleGenericType() + { + var genSig = PopNode(NodeKind.DependentGenericSignature); + var ty = PopNode(NodeKind.Type); + return CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, ty)); + } + + int DecodeValueWitnessKind(string codeStr) + { + switch (codeStr) + { + case "al": return (int)ValueWitnessKind.AllocateBuffer; + case "ca": return (int)ValueWitnessKind.AssignWithCopy; + case "ta": return (int)ValueWitnessKind.AssignWithTake; + case "de": return (int)ValueWitnessKind.DeallocateBuffer; + case "xx": return (int)ValueWitnessKind.Destroy; + case "XX": return (int)ValueWitnessKind.DestroyBuffer; + case "Xx": return (int)ValueWitnessKind.DestroyArray; + case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; + case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; + case "cp": return (int)ValueWitnessKind.InitializeWithCopy; + case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; + case "tk": return (int)ValueWitnessKind.InitializeWithTake; + case "pr": return (int)ValueWitnessKind.ProjectBuffer; + case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; + case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; + case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; + case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; + case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; + case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; + case "ug": return (int)ValueWitnessKind.GetEnumTag; + case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; + case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; + case "et": return (int)ValueWitnessKind.GetEnumTagSinglePayload; + case "st": return (int)ValueWitnessKind.StoreEnumTagSinglePayload; + default: + return -1; + } + } + + Node DemangleValueWitness() + { + char[] code = new char[2]; + code[0] = NextChar(); + code[1] = NextChar(); + int kind = DecodeValueWitnessKind(new string(code)); + if (kind < 0) + return null; + var vw = new Node(NodeKind.ValueWitness, (uint)kind); + return AddChild(vw, PopNode(NodeKind.Type)); + } + + Node DemangleObjCTypeName() + { + var ty = new Node(NodeKind.Type); + var global = AddChild(new Node(NodeKind.Global), AddChild(new Node(NodeKind.TypeMangling), ty)); + Node nominal = null; + bool isProto = false; + if (NextIf('C')) + { + nominal = new Node(NodeKind.Class); + AddChild(ty, nominal); + } + else if (NextIf('P')) + { + isProto = true; + nominal = new Node(NodeKind.Protocol); + AddChild(ty, AddChild(new Node(NodeKind.ProtocolList), + AddChild(new Node(NodeKind.TypeList), + AddChild(new Node(NodeKind.Type), nominal)))); + } + else + { + return null; + } + + if (NextIf('s')) + { + nominal.AddChild(new Node(NodeKind.Module, "Swift")); + } + else + { + var Module = DemangleIdentifier(); + if (Module == null) + return null; + nominal.AddChild(ChangeKind(Module, NodeKind.Module)); + } + + var ident = DemangleIdentifier(); + if (ident == null) + return null; + nominal.AddChild(ident); + + if (isProto && !NextIf('_')) + return null; + + if (!slice.IsAtEnd) + return null; + + return global; + } + + } } diff --git a/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs b/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs index 45b26be66384..d102da65d299 100644 --- a/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs +++ b/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs @@ -6,2060 +6,2133 @@ using System.Linq; using SwiftRuntimeLibrary; -namespace SwiftReflector.Demangling { - public class Swift5NodeToTLDefinition { - static List nominalNodeKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol - }; - - static List nominalNodeAndModuleKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol, NodeKind.Module - }; - - static List identifierOrOperatorOrPrivateDecl = new List { - NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator, NodeKind.PrivateDeclName - }; - - static List boundGenericNominalNodeKinds = new List { - NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure - }; - - string mangledName; - ulong offset; - - RuleRunner ruleRunner; - List rules; - - public Swift5NodeToTLDefinition (string mangledName, ulong offset = 0) - { - this.mangledName = mangledName; - this.offset = offset; - rules = BuildMatchRules (); - ruleRunner = new RuleRunner (rules); - } - - List BuildMatchRules () - { - return new List () { - new MatchRule { - Name = "TypeAlias", - NodeKind = NodeKind.TypeAlias, - Reducer = ConvertToTypeAlias - }, - new MatchRule { - Name = "ReturnType", - NodeKind = NodeKind.ReturnType, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "ArgumentTuple", - NodeKind = NodeKind.ArgumentTuple, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "AutoClosure", - NodeKind = NodeKind.AutoClosureType, - Reducer = ConvertToFunctionType - }, - new MatchRule { - Name = "Tuple", - NodeKind = NodeKind.Tuple, - Reducer = ConvertToTuple - }, - new MatchRule { - Name = "Structure", - NodeKind = NodeKind.Structure, - Reducer = ConvertToStruct - }, - new MatchRule { - Name = "ClassEnum", - NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "Getter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToGetter, - ChildRules = new List () { - new MatchRule () { - Name = "GetterChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "Setter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSetter, - ChildRules = new List () { - new MatchRule () { - Name = "SetterChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "DispatchThunk", - NodeKind = NodeKind.DispatchThunk, - Reducer = ConvertToDispatchThunk, - ChildRules = new List () { } - }, - new MatchRule { - Name = "DynamicSelf", - NodeKind = NodeKind.DynamicSelf, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "SubscriptModifier", - NodeKind = NodeKind.ModifyAccessor, - Reducer = ConvertToSubscriptModifier, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptModifierChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "SubscriptGetter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToSubscriptGetter, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptSetterChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "SubscriptSetter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSubscriptSetter, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptSetterChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "DidSet", - NodeKind = NodeKind.DidSet, - Reducer = ConvertToDidSet, - ChildRules = new List { - new MatchRule { - Name = "DidSetChild", - NodeKind = NodeKind.Variable, - }, - } - }, - new MatchRule { - Name = "WillSet", - NodeKind = NodeKind.WillSet, - Reducer = ConvertToWillSet, - ChildRules = new List { - new MatchRule { - Name = "DidSetChild", - NodeKind = NodeKind.Variable, - }, - } - }, - new MatchRule { - Name = "ModifyAccessor", - NodeKind = NodeKind.ModifyAccessor, - Reducer = ConvertToModifyAccessor, - ChildRules = new List () { - new MatchRule () { - Name = "ModifyAccessorChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "CFunctionPointerType", - NodeKind = NodeKind.CFunctionPointer, - Reducer = ConvertToCFunctionPointerType, - ChildRules = new List { - new MatchRule { - Name = "CFunctionPointerChildArgumentTuple", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule { - Name = "CFunctionPointerChildReturnType", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule { - Name = "ProtocolList", - NodeKind = NodeKind.ProtocolList, - Reducer = ConvertToProtocolList, - ChildRules = new List { - new MatchRule { - Name = "TypeList", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "ProtocolListWithAnyObject", - NodeKind = NodeKind.ProtocolListWithAnyObject, - Reducer = ConvertToProtocolListAnyObject, - }, - new MatchRule { - Name = "Protocol", - NodeKind = NodeKind.Protocol, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "TupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToTupleElement, - ChildRules = new List { - new MatchRule { - Name = "TupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "NamedTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToTupleElement, - ChildRules = new List { - new MatchRule { - Name = "TupleElementName", - NodeKind = NodeKind.TupleElementName - }, - new MatchRule { - Name = "TupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "VariadicTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToVariadicTupleElement, - ChildRules = new List { - new MatchRule { - Name = "VariadicElementType", - NodeKind = NodeKind.VariadicMarker, - }, - new MatchRule { - Name = "NamedTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "DependentGenericParameter", - NodeKind = NodeKind.DependentGenericParamType, - Reducer = ConvertToGenericReference, - ChildRules = new List { - new MatchRule { - Name = "Depth", - NodeKind = NodeKind.Index - }, - new MatchRule { - Name = "Index", - NodeKind = NodeKind.Index - } - } - }, - new MatchRule { - Name = "DependentMemberType", - NodeKind = NodeKind.DependentMemberType, - Reducer = ConvertToDependentMember, - ChildRules = new List { - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule { - Name = "Static", - NodeKind = NodeKind.Static, - Reducer = ConvertToStatic, - }, - new MatchRule { - Name = "BoundGenericNominal", - NodeKindList = boundGenericNominalNodeKinds, - Reducer = ConvertToBoundGeneric, - ChildRules = new List { - new MatchRule { - Name = "TypeChild", - NodeKind = NodeKind.Type - }, - new MatchRule { - Name = "TypeListChild", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "ConstructorList", - NodeKind = NodeKind.Constructor, - Reducer = ConvertToNonAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ConstructorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorExtensionLableList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "ConstructorNoTypeList", - NodeKind = NodeKind.Constructor, - Reducer = ConvertToNonAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ConstructorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorExtensionsNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "Destructor", - NodeKind = NodeKind.Destructor, - Reducer = ConvertToDestructor, - ChildRules = new List { - new MatchRule { - Name = "DestructorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "Deallocator", - NodeKind = NodeKind.Deallocator, - Reducer = ConvertToDeallocator, - ChildRules = new List { - new MatchRule { - Name = "DeallocatorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "InOutType", - NodeKind = NodeKind.Type, - Reducer = ConvertToReferenceType, - ChildRules = new List { - new MatchRule { - Name = "InOutChild", - NodeKind = NodeKind.InOut - } - } - }, - new MatchRule { - Name = "ProtocolWitnessTable", - NodeKindList = new List { - NodeKind.ProtocolWitnessTable, - NodeKind.ProtocolWitnessTableAccessor - }, - Reducer = ConvertToProtocolWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChild", - NodeKind = NodeKind.ProtocolConformance, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChildTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildProtocolTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildModuleChild", - NodeKind = NodeKind.Module - } - } - } - } - }, - new MatchRule { - Name = "ValueWitnessTable", - NodeKind = NodeKind.ValueWitnessTable, - Reducer = ConvertToValueWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ValueWitnessTableChild", - NodeKind = NodeKind.Type - } - } - }, +namespace SwiftReflector.Demangling +{ + public class Swift5NodeToTLDefinition + { + static List nominalNodeKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol + }; + + static List nominalNodeAndModuleKinds = new List { + NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol, NodeKind.Module + }; + + static List identifierOrOperatorOrPrivateDecl = new List { + NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator, NodeKind.PrivateDeclName + }; + + static List boundGenericNominalNodeKinds = new List { + NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure + }; + + string mangledName; + ulong offset; + + RuleRunner ruleRunner; + List rules; + + public Swift5NodeToTLDefinition(string mangledName, ulong offset = 0) + { + this.mangledName = mangledName; + this.offset = offset; + rules = BuildMatchRules(); + ruleRunner = new RuleRunner(rules); + } + + List BuildMatchRules() + { + return new List() { + new MatchRule { + Name = "TypeAlias", + NodeKind = NodeKind.TypeAlias, + Reducer = ConvertToTypeAlias + }, + new MatchRule { + Name = "ReturnType", + NodeKind = NodeKind.ReturnType, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "ArgumentTuple", + NodeKind = NodeKind.ArgumentTuple, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "AutoClosure", + NodeKind = NodeKind.AutoClosureType, + Reducer = ConvertToFunctionType + }, + new MatchRule { + Name = "Tuple", + NodeKind = NodeKind.Tuple, + Reducer = ConvertToTuple + }, + new MatchRule { + Name = "Structure", + NodeKind = NodeKind.Structure, + Reducer = ConvertToStruct + }, + new MatchRule { + Name = "ClassEnum", + NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "Getter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToGetter, + ChildRules = new List () { + new MatchRule () { + Name = "GetterChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "Setter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSetter, + ChildRules = new List () { + new MatchRule () { + Name = "SetterChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "DispatchThunk", + NodeKind = NodeKind.DispatchThunk, + Reducer = ConvertToDispatchThunk, + ChildRules = new List () { } + }, + new MatchRule { + Name = "DynamicSelf", + NodeKind = NodeKind.DynamicSelf, + Reducer = ConvertFirstChildToSwiftType + }, + new MatchRule { + Name = "SubscriptModifier", + NodeKind = NodeKind.ModifyAccessor, + Reducer = ConvertToSubscriptModifier, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptModifierChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "SubscriptGetter", + NodeKind = NodeKind.Getter, + Reducer = ConvertToSubscriptGetter, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptSetterChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "SubscriptSetter", + NodeKind = NodeKind.Setter, + Reducer = ConvertToSubscriptSetter, + ChildRules = new List () { + new MatchRule () { + Name = "SubscriptSetterChild", + NodeKind = NodeKind.Subscript + } + } + }, + new MatchRule { + Name = "DidSet", + NodeKind = NodeKind.DidSet, + Reducer = ConvertToDidSet, + ChildRules = new List { + new MatchRule { + Name = "DidSetChild", + NodeKind = NodeKind.Variable, + }, + } + }, + new MatchRule { + Name = "WillSet", + NodeKind = NodeKind.WillSet, + Reducer = ConvertToWillSet, + ChildRules = new List { + new MatchRule { + Name = "DidSetChild", + NodeKind = NodeKind.Variable, + }, + } + }, + new MatchRule { + Name = "ModifyAccessor", + NodeKind = NodeKind.ModifyAccessor, + Reducer = ConvertToModifyAccessor, + ChildRules = new List () { + new MatchRule () { + Name = "ModifyAccessorChild", + NodeKind = NodeKind.Variable + } + } + + }, + new MatchRule { + Name = "CFunctionPointerType", + NodeKind = NodeKind.CFunctionPointer, + Reducer = ConvertToCFunctionPointerType, + ChildRules = new List { + new MatchRule { + Name = "CFunctionPointerChildArgumentTuple", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule { + Name = "CFunctionPointerChildReturnType", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule { + Name = "ProtocolList", + NodeKind = NodeKind.ProtocolList, + Reducer = ConvertToProtocolList, + ChildRules = new List { + new MatchRule { + Name = "TypeList", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "ProtocolListWithAnyObject", + NodeKind = NodeKind.ProtocolListWithAnyObject, + Reducer = ConvertToProtocolListAnyObject, + }, + new MatchRule { + Name = "Protocol", + NodeKind = NodeKind.Protocol, + Reducer = ConvertToClass + }, + new MatchRule { + Name = "TupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToTupleElement, + ChildRules = new List { + new MatchRule { + Name = "TupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "NamedTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToTupleElement, + ChildRules = new List { + new MatchRule { + Name = "TupleElementName", + NodeKind = NodeKind.TupleElementName + }, + new MatchRule { + Name = "TupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "VariadicTupleElement", + NodeKind = NodeKind.TupleElement, + Reducer = ConvertToVariadicTupleElement, + ChildRules = new List { + new MatchRule { + Name = "VariadicElementType", + NodeKind = NodeKind.VariadicMarker, + }, + new MatchRule { + Name = "NamedTupleElementType", + NodeKind = NodeKind.Type + } + } + }, + new MatchRule { + Name = "DependentGenericParameter", + NodeKind = NodeKind.DependentGenericParamType, + Reducer = ConvertToGenericReference, + ChildRules = new List { + new MatchRule { + Name = "Depth", + NodeKind = NodeKind.Index + }, + new MatchRule { + Name = "Index", + NodeKind = NodeKind.Index + } + } + }, + new MatchRule { + Name = "DependentMemberType", + NodeKind = NodeKind.DependentMemberType, + Reducer = ConvertToDependentMember, + ChildRules = new List { + new MatchRule { + Name = "Type", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule { + Name = "Static", + NodeKind = NodeKind.Static, + Reducer = ConvertToStatic, + }, + new MatchRule { + Name = "BoundGenericNominal", + NodeKindList = boundGenericNominalNodeKinds, + Reducer = ConvertToBoundGeneric, + ChildRules = new List { + new MatchRule { + Name = "TypeChild", + NodeKind = NodeKind.Type + }, + new MatchRule { + Name = "TypeListChild", + NodeKind = NodeKind.TypeList + } + } + }, + new MatchRule { + Name = "ConstructorList", + NodeKind = NodeKind.Constructor, + Reducer = ConvertToNonAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ConstructorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorExtensionLableList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ExtensionChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "FunctionLabelListChild", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "ConstructorNoTypeList", + NodeKind = NodeKind.Constructor, + Reducer = ConvertToNonAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "ConstructorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKindList = nominalNodeKinds, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "AllocatorExtensionsNoTypeList", + NodeKind = NodeKind.Allocator, + Reducer = ConvertToAllocatingConstructor, + ChildRules = new List { + new MatchRule { + Name = "AllocatorNominalChild", + NodeKind = NodeKind.Extension, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.FunctionType + } + } + }, + } + }, + new MatchRule { + Name = "Destructor", + NodeKind = NodeKind.Destructor, + Reducer = ConvertToDestructor, + ChildRules = new List { + new MatchRule { + Name = "DestructorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "Deallocator", + NodeKind = NodeKind.Deallocator, + Reducer = ConvertToDeallocator, + ChildRules = new List { + new MatchRule { + Name = "DeallocatorNominalChild", + NodeKindList = nominalNodeKinds, + } + } + }, + new MatchRule { + Name = "InOutType", + NodeKind = NodeKind.Type, + Reducer = ConvertToReferenceType, + ChildRules = new List { + new MatchRule { + Name = "InOutChild", + NodeKind = NodeKind.InOut + } + } + }, + new MatchRule { + Name = "ProtocolWitnessTable", + NodeKindList = new List { + NodeKind.ProtocolWitnessTable, + NodeKind.ProtocolWitnessTableAccessor + }, + Reducer = ConvertToProtocolWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChild", + NodeKind = NodeKind.ProtocolConformance, + ChildRules = new List { + new MatchRule { + Name = "ProtocolWitnessChildTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildProtocolTypeChild", + NodeKind = NodeKind.Type, + }, + new MatchRule { + Name = "ProtocolWitnessChildModuleChild", + NodeKind = NodeKind.Module + } + } + } + } + }, + new MatchRule { + Name = "ValueWitnessTable", + NodeKind = NodeKind.ValueWitnessTable, + Reducer = ConvertToValueWitnessTable, + ChildRules = new List { + new MatchRule { + Name = "ValueWitnessTableChild", + NodeKind = NodeKind.Type + } + } + }, // a Function is: // Context Identifier [LabelList] Type FunctionType new MatchRule () { - Name = "FunctionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTLContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "FunctionTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule () { - Name = "FunctionTLType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionExtensionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionExtension", - NodeKind = NodeKind.Extension, - }, - new MatchRule () { - Name = "FunctionExtTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionExtTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule () { - Name = "FunctionExtTLType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule { - Name = "GenericFunctionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule () { - Name = "GenFunctionTLContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "GenFunctionTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.DependentGenericType, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - } - } - }, - } - }, - new MatchRule { - Name = "DependentGenericFunctionType", - NodeKind = NodeKind.DependentGenericType, - Reducer = ConvertToGenericFunction, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - }, - new MatchRule () { - Name = "FunctionNoTypeList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "FunctionName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionExtensionNoTypeList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionExtension", - NodeKind = NodeKind.Extension, - }, - new MatchRule () { - Name = "FunctionName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "FunctionThrows", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeThrows", - NodeKind = NodeKind.ThrowsAnnotation - }, - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "NoEscapeFunctionType", - NodeKind = NodeKind.NoEscapeFunctionType, - Reducer = ConvertToNoEscapeFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "NoEscapeFunctionTypeThrows", - NodeKind = NodeKind.NoEscapeFunctionType, - Reducer = ConvertToNoEscapeFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeThrows", - NodeKind = NodeKind.ThrowsAnnotation - }, - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "Metatype", - NodeKind = NodeKind.Metatype, - Reducer = ConvertToMetatype, - }, - new MatchRule () { - Name = "ExistentialMetatype", - NodeKind = NodeKind.ExistentialMetatype, - Reducer = ConvertToExistentialMetatype, - MatchChildCount = false - }, + Name = "FunctionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTLContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "FunctionTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule () { + Name = "FunctionTLType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionExtensionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionExtension", + NodeKind = NodeKind.Extension, + }, + new MatchRule () { + Name = "FunctionExtTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionExtTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule () { + Name = "FunctionExtTLType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule { + Name = "GenericFunctionWithLabelList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List { + new MatchRule () { + Name = "GenFunctionTLContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "GenFunctionTLName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionTLLabelList", + NodeKind = NodeKind.LabelList, + }, + new MatchRule { + Name = "FunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "FunctionTypeChildChild", + NodeKind = NodeKind.DependentGenericType, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + } + } + }, + } + }, + new MatchRule { + Name = "DependentGenericFunctionType", + NodeKind = NodeKind.DependentGenericType, + Reducer = ConvertToGenericFunction, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericSignature", + NodeKind = NodeKind.DependentGenericSignature + }, + new MatchRule { + Name = "DependentGenericFunctionTypeChild", + NodeKind = NodeKind.Type, + ChildRules = new List { + new MatchRule { + Name = "DependentGenericFunctionChild", + NodeKind = NodeKind.FunctionType + } + } + } + } + }, + new MatchRule () { + Name = "FunctionNoTypeList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionContext", + NodeKindList = nominalNodeAndModuleKinds, + }, + new MatchRule () { + Name = "FunctionName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionExtensionNoTypeList", + NodeKind = NodeKind.Function, + Reducer = ConvertToFunction, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionExtension", + NodeKind = NodeKind.Extension, + }, + new MatchRule () { + Name = "FunctionName", + NodeKindList = identifierOrOperatorOrPrivateDecl + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.Type + }, + } + }, + new MatchRule () { + Name = "FunctionType", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "FunctionThrows", + NodeKind = NodeKind.FunctionType, + Reducer = ConvertToFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeThrows", + NodeKind = NodeKind.ThrowsAnnotation + }, + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "NoEscapeFunctionType", + NodeKind = NodeKind.NoEscapeFunctionType, + Reducer = ConvertToNoEscapeFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "NoEscapeFunctionTypeThrows", + NodeKind = NodeKind.NoEscapeFunctionType, + Reducer = ConvertToNoEscapeFunctionType, + ChildRules = new List () { + new MatchRule () { + Name = "FunctionTypeThrows", + NodeKind = NodeKind.ThrowsAnnotation + }, + new MatchRule () { + Name = "FunctionTypeArgs", + NodeKind = NodeKind.ArgumentTuple + }, + new MatchRule () { + Name = "FunctionTypeReturn", + NodeKind = NodeKind.ReturnType + } + } + }, + new MatchRule () { + Name = "Metatype", + NodeKind = NodeKind.Metatype, + Reducer = ConvertToMetatype, + }, + new MatchRule () { + Name = "ExistentialMetatype", + NodeKind = NodeKind.ExistentialMetatype, + Reducer = ConvertToExistentialMetatype, + MatchChildCount = false + }, // Probably should be last new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type, - Reducer = ConvertFirstChildToSwiftType, - MatchChildCount = false - }, - }; - } - - public TLDefinition Convert (Node node) - { - Exceptions.ThrowOnNull (node, nameof (node)); - - - switch (node.Kind) { - case NodeKind.Type: - return Convert (node.Children [0]); - case NodeKind.Static: - return ConvertStatic (node); - case NodeKind.Function: - return ConvertFunction (node, isMethodDescriptor: false, isEnumCase: false); - case NodeKind.MethodDescriptor: - return ConvertFunction (node.Children [0], isMethodDescriptor: true, isEnumCase: false); - case NodeKind.EnumCase: - return ConvertFunction (node.Children [0], isMethodDescriptor: false, isEnumCase: true); - case NodeKind.Constructor: - case NodeKind.Allocator: - return ConvertFunctionConstructor (node); - case NodeKind.Destructor: - case NodeKind.Deallocator: - return ConvertFunctionDestructor (node); - case NodeKind.Getter: - case NodeKind.Setter: - case NodeKind.DidSet: - case NodeKind.MaterializeForSet: - case NodeKind.WillSet: - case NodeKind.ModifyAccessor: - return ConvertFunctionProp (node); - case NodeKind.DispatchThunk: - return ConvertDispatchThunk (node); - case NodeKind.Variable: - return ConvertVariable (node, false); - case NodeKind.PropertyDescriptor: - return ConvertPropertyDescriptor (node); - case NodeKind.TypeMetadataAccessFunction: - return ConvertCCtor (node); - case NodeKind.TypeMetadata: - return ConvertMetadata (node); - case NodeKind.NominalTypeDescriptor: - return ConvertNominalTypeDescriptor (node); - case NodeKind.ProtocolConformanceDescriptor: - return ConvertProtocolConformanceDescriptor (node); - case NodeKind.ProtocolDescriptor: - return ConvertProtocolDescriptor (node); - case NodeKind.Initializer: - return ConvertInitializer (node); - case NodeKind.TypeMetadataLazyCache: - return ConvertLazyCacheVariable (node); - case NodeKind.ProtocolWitnessTable: - case NodeKind.ProtocolWitnessTableAccessor: - case NodeKind.ValueWitnessTable: - return ConvertProtocolWitnessTable (node); - case NodeKind.FieldOffset: - return ConvertFieldOffset (node); - case NodeKind.DefaultArgumentInitializer: - return ConvertDefaultArgumentInitializer (node); - case NodeKind.Metaclass: - return ConvertMetaclass (node); - case NodeKind.UnsafeMutableAddressor: - return ConvertUnsafeMutableAddressor (node); - case NodeKind.CurryThunk: - return ConvertCurryThunk (node); - case NodeKind.GenericTypeMetadataPattern: - return ConvertTypeMetadataPattern (node); - case NodeKind.Global: - return Convert (node); - case NodeKind.ModuleDescriptor: - return ConvertModuleDescriptor (node); - case NodeKind.ReflectionMetadataFieldDescriptor: - return ConvertMetadataFieldDescriptor (node, false); - case NodeKind.ReflectionMetadataBuiltinDescriptor: - return ConvertMetadataFieldDescriptor (node, true); - case NodeKind.ProtocolRequirementsBaseDescriptor: - return ConvertProtocolRequirementsBaseDescriptor (node); - case NodeKind.BaseConformanceDescriptor: - return ConvertBaseConformanceDescriptor (node); - case NodeKind.AssociatedTypeDescriptor: - return ConvertAssocatedTypeDescriptor (node); - case NodeKind.ClassMetadataBaseOffset: - return ConvertMetadataBaseOffset (node); - case NodeKind.MethodLookupFunction: - return ConvertMethodLookupFunction (node); - default: - return null; - } - } - - - TLDefinition ConvertDispatchThunk (Node node) - { - switch (node.Children [0].Kind) { - case NodeKind.Getter: - case NodeKind.Setter: - case NodeKind.DidSet: - case NodeKind.MaterializeForSet: - case NodeKind.WillSet: - case NodeKind.ModifyAccessor: - return ConvertFunctionProp (node); - case NodeKind.Static: - return ConvertStaticDispatchThunk (node); - case NodeKind.Function: - case NodeKind.Allocator: - return ConvertFunction (node, isMethodDescriptor: false, isEnumCase: false); - default: - return null; - } - } - - TLDefinition ConvertStaticDispatchThunk (Node node) - { - if (node.Children [0].Children [0].Kind == NodeKind.Variable) { - return ConvertStaticDispatchThunkVariable (node); - } - else { - return ConvertStatic (node); - } - } - - TLDefinition ConvertStaticDispatchThunkVariable (Node node) - { - return null; - } - - - TLFunction ConvertFunction (Node node, bool isMethodDescriptor, bool isEnumCase) - { - var swiftType = ConvertToSwiftType (node, false, null); - var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) { - // method - var context = uncurriedFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = new SwiftName (context.Last (), false); - return isMethodDescriptor ? - new TLMethodDescriptor (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset) : - isEnumCase ? - new TLEnumCase (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset) : - new TLFunction (mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset); - } - - var plainFunction = swiftType as SwiftFunctionType; - if (plainFunction != null) { - var context = plainFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context [context.Length - 2] [0] == '|') { - Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); - } - var functionName = new SwiftName (context.Last (), false); - return isMethodDescriptor ? - new TLMethodDescriptor (mangledName, module, functionName, null, plainFunction, offset, operatorType) : - new TLFunction (mangledName, module, functionName, null, plainFunction, offset, operatorType); - } - return null; - } - - TLDefinition ConvertStatic (Node node) - { - if (node.Children [0].Kind == NodeKind.Variable) { - return ConvertVariable (node.Children [0], true); - } - var swiftType = ConvertToSwiftType (node, false, null); - var propType = swiftType as SwiftPropertyType; - if (propType != null) { - var context = propType.DiscretionaryString.Split ('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); - } - - var staticFunction = swiftType as SwiftStaticFunctionType; - if (staticFunction != null) { - var context = staticFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context [context.Length - 2] [0] == '|') { - Enum.TryParse (context [context.Length - 2].Substring (1), out operatorType); - } - var functionName = new SwiftName (context.Last (), false); - return new TLFunction (mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); - } - return null; - } - - TLFunction ConvertFunctionConstructor (Node node) - { - var swiftType = ConvertToSwiftType (node, false, null); - var constructor = swiftType as SwiftConstructorType; - if (constructor != null) { - var context = constructor.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = constructor.Name; - var metaType = constructor.UncurriedParameter as SwiftMetaClassType; - return new TLFunction (mangledName, module, functionName, metaType.Class, constructor, offset); - } - return null; - } - - TLFunction ConvertFunctionDestructor (Node node) - { - var swiftType = ConvertToSwiftType (node, false, null); - var destructor = swiftType as SwiftDestructorType; - if (destructor != null) { - var context = destructor.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var functionName = destructor.Name; - var className = destructor.Parameters as SwiftClassType; - if (className == null) - throw new NotSupportedException ($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType ().Name}"); - return new TLFunction (mangledName, module, functionName, className, destructor, offset); - } - return null; - } - - TLFunction ConvertFunctionProp (Node node) - { - var propType = ConvertToSwiftType (node, false, null) as SwiftPropertyType; - if (propType == null) - return null; - var context = propType.DiscretionaryString.Split ('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction (mangledName, new SwiftName (context [0], false), propType.Name, uncurriedParam, propType, offset); - } - - TLVariable ConvertVariable (Node node, bool isStatic) - { - // Variable - // - if (node.Children.Count != 3 && node.Children.Count != 4) - throw new ArgumentOutOfRangeException (nameof (node), $"Expected 3 or 4 children in a variable node, but got {node.Children.Count}"); - - if (node.Kind == NodeKind.Subscript) { - var subFunc = ConvertToSubscriptEtter (node, false, null, PropertyType.Getter) as SwiftPropertyType; - var module = subFunc.DiscretionaryString.Split ('.') [0]; - return new TLVariable (mangledName, new SwiftName (module, false), subFunc.UncurriedParameter as SwiftClassType, - new SwiftName ("subscript", false), subFunc.OfType, isStatic, offset); - } - - if (node.Children [2].Kind == NodeKind.LabelList && node.Children [3].Kind == NodeKind.Type && - node.Children [3].Children [0].Kind == NodeKind.FunctionType) { - var functionNode = new Node (NodeKind.Function); - functionNode.Children.AddRange (node.Children); - var function = ConvertFunction (functionNode, isMethodDescriptor: false, isEnumCase: false); - SwiftClassType classOn = null; - if (function.Signature is SwiftUncurriedFunctionType ucf) { - classOn = ucf.UncurriedParameter as SwiftClassType; - } - return new TLVariable (mangledName, function.Module, classOn, function.Name, function.Signature, isStatic, offset); - } else { - var isExtension = node.Children [0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType context = null; - - - if (isExtension) { - module = new SwiftName (node.Children [0].Children [0].Text, false); - extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); - if (extensionOn == null) - return null; - } else { - var nesting = new List (); - var nestingNames = new List (); - module = BuildMemberNesting (node.Children [0], nesting, nestingNames); - context = nesting.Count > 0 ? new SwiftClassType (new SwiftClassName (module, nesting, nestingNames), false) : null; - } - - var name = new SwiftName (node.Children [1].Text, false); - var variableType = ConvertToSwiftType (node.Children [2], false, null); - return new TLVariable (mangledName, module, context, name, variableType, isStatic, offset, extensionOn); - } - } - - TLPropertyDescriptor ConvertPropertyDescriptor (Node node) - { - var tlvar = ConvertVariable (node.Children [0], false); - if (tlvar == null) - return null; - return new TLPropertyDescriptor (tlvar.MangledName, tlvar.Module, tlvar.Class, tlvar.Name, tlvar.OfType, false, tlvar.Offset, tlvar.ExtensionOn); - } - - TLFunction ConvertCCtor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var metaType = new SwiftMetaClassType (classType, false); - var cctor = new SwiftClassConstructorType (metaType, false); - return new TLFunction (mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, - cctor, offset); - } - - TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer (Node node) - { - if (node.Children.Count != 2) - return null; - var baseFunction = ConvertToSwiftType (node.Children [0], false, null) as SwiftBaseFunctionType; - if (baseFunction == null) - return null; - var context = baseFunction.DiscretionaryString.Split ('.'); - var module = new SwiftName (context [0], false); - var argumentIndex = (int)node.Children [1].Index; - return new TLDefaultArgumentInitializer (mangledName, module, baseFunction, argumentIndex, offset); - } - - TLFieldOffset ConvertFieldOffset (Node node) - { - if (node.Children.Count != 2 || node.Children [0].Kind != NodeKind.Directness) - return null; - var variable = ConvertVariable (node.Children [1], false) as TLVariable; - if (variable == null) - return null; - - return new TLFieldOffset (mangledName, variable.Module, variable.Class, node.Children [0].Index == 0, variable.Name, - variable.OfType, offset); - } - - TLDirectMetadata ConvertMetadata (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLDirectMetadata (mangledName, classType.ClassName.Module, classType, offset); - } - - TLNominalTypeDescriptor ConvertNominalTypeDescriptor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLNominalTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); - } - - TLProtocolConformanceDescriptor ConvertProtocolConformanceDescriptor (Node node) - { - node = node.Children [0]; - if (node.Kind != NodeKind.ProtocolConformance) - return null; - if (node.Children.Count != 3) - return null; - var implementingType = ConvertToSwiftType (node.Children [0], false, null); - if (implementingType == null) - return null; - var forProtocol = ConvertToSwiftType (node.Children [1], false, null) as SwiftClassType; - if (forProtocol == null) - return null; - var module = new SwiftName (node.Children [2].Text, false); - return new TLProtocolConformanceDescriptor (mangledName, module, implementingType, forProtocol, offset); - } - - TLProtocolTypeDescriptor ConvertProtocolDescriptor (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLProtocolTypeDescriptor (mangledName, classType.ClassName.Module, classType, offset); - } - - TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor (Node node) - { - if (node.Children [0].Kind != NodeKind.Variable) - throw new ArgumentOutOfRangeException ($"Expected a Variable child but got a {node.Children [0].Kind}"); - var variable = ConvertVariable (node.Children [0], false); - return new TLUnsafeMutableAddressor (mangledName, variable.Module, null, variable.Name, variable.OfType, variable.Offset); - } - - TLMetaclass ConvertMetaclass (Node node) - { - if (node.Children [0].Kind != NodeKind.Type) - return null; - var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; - if (classType == null) - return null; - var module = classType.ClassName.Module; - return new TLMetaclass (mangledName, module, classType, offset); - } - - TLGenericMetadataPattern ConvertTypeMetadataPattern (Node node) - { - var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLGenericMetadataPattern (mangledName, type.ClassName.Module, type, offset); - } - - TLFunction ConvertInitializer (Node node) - { - var variable = node.Children [0]; - var context = ConvertToSwiftType (variable.Children [0], false, null) as SwiftClassType; - if (context == null) - return null; - var privatePublicName = PrivateNamePublicName (variable.Children [1]); - var name = new SwiftName (privatePublicName.Item2, false); - var typeIndex = variable.Children [2].Kind == NodeKind.LabelList ? 3 : 2; - var type = ConvertToSwiftType (variable.Children [typeIndex], false, null); - var initializer = new SwiftInitializerType (InitializerType.Variable, type, context, name); - return new TLFunction (mangledName, context.ClassName.Module, name, initializer.Owner, initializer, offset); - } - - TLLazyCacheVariable ConvertLazyCacheVariable (Node node) - { - var classType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - return new TLLazyCacheVariable (mangledName, classType.ClassName.Module, classType, offset); - } - - TLFunction ConvertProtocolWitnessTable (Node node) - { - var witnessTable = ConvertToSwiftType (node, false, null) as SwiftWitnessTableType; - - var rebuiltWitnessTable = new SwiftWitnessTableType (witnessTable.WitnessType, witnessTable.ProtocolType, witnessTable.UncurriedParameter as SwiftClassType); - - return new TLFunction (mangledName, new SwiftName (witnessTable.DiscretionaryString, false), null, - witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); - } - - TLThunk ConvertCurryThunk (Node node) - { - TLFunction func = ConvertFunction (node.Children [0], isMethodDescriptor: false, isEnumCase: false); - return new TLThunk (ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); - } - - TLModuleDescriptor ConvertModuleDescriptor (Node node) - { - var firstChild = node.Children [0]; - if (firstChild.Kind != NodeKind.Module) - return null; - return new TLModuleDescriptor (mangledName, new SwiftName (firstChild.Text, false), offset); - } - - TLMetadataDescriptor ConvertMetadataFieldDescriptor (Node node, bool isBuiltIn) - { - var ofType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (ofType == null) - return null; - return new TLMetadataDescriptor (ofType, isBuiltIn, mangledName, ofType.ClassName.Module, offset); - } - - TLProtocolRequirementsBaseDescriptor ConvertProtocolRequirementsBaseDescriptor (Node node) - { - var ofType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (ofType == null) - return null; - return new TLProtocolRequirementsBaseDescriptor (mangledName, ofType.ClassName.Module, ofType, offset); - } - - TLBaseConformanceDescriptor ConvertBaseConformanceDescriptor (Node node) - { - var protocol = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (protocol == null) - return null; - var requirement = ConvertToSwiftType (node.Children [1], false, null) as SwiftClassType; - if (requirement == null) - return null; - return new TLBaseConformanceDescriptor (mangledName, protocol.ClassName.Module, protocol, requirement, offset); - } - - TLAssociatedTypeDescriptor ConvertAssocatedTypeDescriptor (Node node) - { - var name = new SwiftName (node.Children [0].Text, false); - var protocol = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; - if (protocol == null) - return null; - return new TLAssociatedTypeDescriptor (mangledName, protocol.ClassName.Module, protocol, name, offset); - } - - TLMetadataBaseOffset ConvertMetadataBaseOffset (Node node) - { - var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLMetadataBaseOffset (mangledName, type.ClassName.Module, type, offset); - } - - TLMethodLookupFunction ConvertMethodLookupFunction (Node node) - { - var type = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLMethodLookupFunction (mangledName, type.ClassName.Module, type, offset); - } - - - // ConvertToFunctions are usually called from rules. - - SwiftType ConvertToReferenceType (Node node, bool isReference, SwiftName name) - { - return ConvertToSwiftType (node.Children [0].Children [0], true, name); - } - - SwiftType ConvertToSwiftType (Node node, bool isReference, SwiftName name) - { - return ruleRunner.RunRules (node, isReference, name); - } - - SwiftType ConvertFirstChildToSwiftType (Node node, bool isReference, SwiftName name) - { - if (node.Children.Count == 0) - throw new ArgumentOutOfRangeException (nameof (node)); - return ConvertToSwiftType (node.Children [0], isReference, name); - } - - SwiftType ConvertToGeneralFunctionType (Node node, bool isReference, SwiftName name, bool isEscaping) - { - var throws = node.Children [0].Kind == NodeKind.ThrowsAnnotation; - var startIndex = throws ? 1 : 0; - var args = ConvertToSwiftType (node.Children [startIndex + 0], false, null); - var returnType = ConvertToSwiftType (node.Children [startIndex + 1], false, null); - return new SwiftFunctionType (args, returnType, isReference, throws, name, isEscaping: isEscaping); - } - - SwiftType ConvertToFunctionType (Node node, bool isReference, SwiftName name) - { - return ConvertToGeneralFunctionType (node, isReference, name, true); - } - - SwiftType ConvertToNoEscapeFunctionType (Node node, bool isReference, SwiftName name) - { - return ConvertToGeneralFunctionType (node, isReference, name, false); - } - - OperatorType ToOperatorType (NodeKind kind) - { - switch (kind) { - default: - case NodeKind.Identifier: - return OperatorType.None; - case NodeKind.PrefixOperator: - return OperatorType.Prefix; - case NodeKind.InfixOperator: - return OperatorType.Infix; - case NodeKind.PostfixOperator: - return OperatorType.Postfix; - } - } - - SwiftType ConvertToAllocatingConstructor (Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor (node, isReference, name, true); - } - - SwiftType ConvertToNonAllocatingConstructor (Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor (node, isReference, name, false); - } - - SwiftType ConvertToConstructor (Node node, bool isReference, SwiftName name, bool isAllocating) - { - var isExtension = node.Children [0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType instanceType = null; - - if (isExtension) { - module = new SwiftName (node.Children [0].Children [0].Text, false); - extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); - if (extensionOn == null) - return null; - if (extensionOn is SwiftBuiltInType builtIn) { - extensionOn = new SwiftClassType (SwiftClassName.FromFullyQualifiedName ($"Swift.{builtIn.BuiltInType}", OperatorType.None, "V"), false); - } - instanceType = extensionOn as SwiftClassType; - } else { - instanceType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - module = instanceType.ClassName.Module; - } - - var metadata = new SwiftMetaClassType (instanceType, false, null); - var labels = node.Children [1].Kind == NodeKind.LabelList ? ToLabelList (node.Children [1]) : null; - var typeIndex = labels == null ? 1 : 2; - var functionType = node.Children [typeIndex].Children [0]; - var functionThrows = functionType.Children.Count == 3 && functionType.Children [0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; - var args = ConvertToSwiftType (functionType.Children [0 + functionThrows], false, null); - args = labels != null && labels.Count > 0 ? RenameFunctionParameters (args, labels) : args; - var ret = ConvertToSwiftType (functionType.Children [1 + functionThrows], false, null); - var constructor = new SwiftConstructorType (isAllocating, metadata, args, ret, isReference, functionThrows != 0, extensionOn); - - constructor.DiscretionaryString = $"{module.Name}.{instanceType.ClassName.ToFullyQualifiedName (false)}"; - return constructor; - } - - SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor (node, isReference, name, false); - } - - SwiftType ConvertToDeallocator (Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor (node, isReference, name, true); - } - - SwiftType ConvertToDestructor (Node node, bool isReference, SwiftName name, bool isDeallocating) - { - var instanceType = ConvertToSwiftType (node.Children [0], false, null); - var sct = instanceType as SwiftClassType; - if (sct == null) - throw new NotSupportedException ($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType ().Name}."); - var destructor = new SwiftDestructorType (isDeallocating, sct, isReference, false); - destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName (true); - return destructor; - } - SwiftType ConvertToStruct (Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName (node); - var bit = TryAsBuiltInType (node, className, isReference, name); - return (SwiftType)bit ?? new SwiftClassType (className, isReference, name); - } - - SwiftType ConvertToTypeAlias (Node node, bool isReference, SwiftName name) - { - if (node.Children[0].Kind == NodeKind.Module && node.Children [0].Text == "__C") { - var shamNode = new Node (NodeKind.Structure); - shamNode.Children.AddRange (node.Children); - var className = ToSwiftClassName (shamNode); - className = RemapTypeAlias (className); - return new SwiftClassType (className, isReference, name); - } else { - return null; - } - } - - SwiftType ConvertToClass (Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName (node); - return new SwiftClassType (className, isReference, name); - } - - SwiftClassName ToSwiftClassName (Node node) - { - var memberNesting = new List (); - var nestingNames = new List (); - var moduleName = BuildMemberNesting (node, memberNesting, nestingNames); - - return PatchClassName (moduleName, memberNesting, nestingNames); - } - - SwiftType ConvertToDependentMember (Node node, bool isReference, SwiftName name) - { - // format should be - // DependentReferenceType - // Type - // GenericReference (depth, index) - // AssocPathItem (name) - // For multuple path elements, these get nested with the head being deepest. - // Weird flex, but OK. - var genericReference = ConvertFirstChildToSwiftType (node, isReference, name) as SwiftGenericArgReferenceType; - if (genericReference == null) - return null; - if (node.Children.Count < 2) - return genericReference; - var assocChild = node.Children [1]; - genericReference.AssociatedTypePath.Add (assocChild.Text); - return genericReference; - } - - SwiftType ConvertToCFunctionPointerType (Node node, bool isReference, SwiftName name) - { - var args = ConvertToSwiftType (node.Children [0], false, null); - var ret = ConvertToSwiftType (node.Children [1], false, null); - var function = new SwiftCFunctionPointerType (args, ret, isReference, false, name); - return function; - } - - SwiftType ConvertToTuple (Node node, bool isReference, SwiftName name) - { - var types = new List (); - if (node.Children.Count == 0) { - return SwiftTupleType.Empty; - } - if (node.Children.Count == 1) { - var onlyChild = ConvertFirstChildToSwiftType (node, false, null); - return new SwiftTupleType (isReference, name, onlyChild); - } - foreach (var child in node.Children) { - var type = ConvertToSwiftType (child, false, null); - if (type == null) - return null; - types.Add (type); - } - return new SwiftTupleType (types, isReference, name); - } - - SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name) - { - return ConvertToProtocolList (node, isReference, name, NodeKind.Type); - } - - SwiftType ConvertToProtocolListAnyObject (Node node, bool isReference, SwiftName name) - { - return ConvertToProtocolList (node.Children [0], isReference, name, node.Kind); - } - - SwiftType ConvertToProtocolList (Node node, bool isReference, SwiftName name, NodeKind nodeKind) - { - if (node.Children.Count != 1) - throw new NotSupportedException ("ProtocolList node with more than 1 child not supported"); - if (node.Children [0].Kind != NodeKind.TypeList) - throw new NotSupportedException ($"Given a ProtocolList node with child type {node.Children [0].Kind.ToString ()} and {node.Children [0].Children.Count} children, but expected a TypeList with exactly 1 child."); - // If the number of elements is 0, it means that this is an "Any" type in swift. - // I'm assuming it's lodged here as a protocol list is that an empty protocol list is - // represented by an existential container which is also used to represent a protocol list. - if (node.Children [0].Children.Count == 0) { - var anyName = nodeKind == NodeKind.ProtocolListWithAnyObject ? "Swift.AnyObject" : "Swift.Any"; - var anyProtocolType = nodeKind == NodeKind.ProtocolListWithAnyObject ? 'C' : 'P'; - var className = SwiftClassName.FromFullyQualifiedName (anyName, OperatorType.None, anyProtocolType); - var classType = new SwiftClassType (className, isReference, name); - return classType; - } - var typeList = ConvertTypeList (node.Children [0]).Select (t => t as SwiftClassType); - var protoListType = new SwiftProtocolListType (typeList, isReference, name); - if (protoListType.Protocols.Count == 1) - return protoListType.Protocols [0].RenamedCloneOf (name); - return protoListType; - } - - SwiftType ConvertToProtocolWitnessTable (Node node, bool isReference, SwiftName name) - { - var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? - WitnessType.Protocol : WitnessType.ProtocolAccessor; - var classType = ConvertToSwiftType (node.Children [0].Children [0], false, null) as SwiftClassType; - var protoType = ConvertToSwiftType (node.Children [0].Children [1], false, null) as SwiftClassType; - var protoWitness = new SwiftWitnessTableType (witnessType, protoType, classType); - protoWitness.DiscretionaryString = node.Children [0].Children [2].Text; - return protoWitness; - } - - SwiftType ConvertToValueWitnessTable (Node node, bool isReference, SwiftName name) - { - var valueType = ConvertToSwiftType (node.Children [0], false, null) as SwiftClassType; - var valueWitnessTable = new SwiftWitnessTableType (WitnessType.Value, null, valueType); - valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; - return valueWitnessTable; - } - - SwiftType ConvertToEtter (Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - var isExtension = node.Children [0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType context = null; - SwiftClassName className = null; - - if (isExtension) { - module = new SwiftName (node.Children [0].Children [0].Text, false); - extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); - if (extensionOn == null) - return null; - } else { - var nestings = new List (); - var names = new List (); - - module = BuildMemberNesting (node.Children [0], nestings, names); - if (module == null) - return null; - className = nestings.Count > 0 ? new SwiftClassName (module, nestings, names) : null; - context = className != null ? new SwiftClassType (className, false) : null; - } - - - var privatePublicName = PrivateNamePublicName (node.Children [1]); - var propName = new SwiftName (privatePublicName.Item2, false); - var privateName = privatePublicName.Item1 != null ? new SwiftName (privatePublicName.Item1, false) : null; - - var funcChildIndex = node.Children [2].Kind == NodeKind.LabelList ? 3 : 2; - - var getterType = ConvertToSwiftType (node.Children [funcChildIndex], false, propertyType == PropertyType.Setter ? new SwiftName ("newValue", false) : null); - var prop = new SwiftPropertyType (context, propertyType, propName, privateName, - getterType, false, isReference, extensionOn); - prop.DiscretionaryString = context != null ? context.ClassName.ToFullyQualifiedName (true) - : $"{module.Name}.{propName.Name}"; - return prop; - - } - - SwiftType ConvertToGetter (Node node, bool isReference, SwiftName name) - { - // Getter - // Variable - // Context - // Type - return ConvertToEtter (node.Children [0], isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSetter (Node node, bool isReference, SwiftName name) - { - return ConvertToEtter (node.Children [0], isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToWillSet (Node node, bool isReference, SwiftName name) - { - return ConvertToEtter (node.Children [0], isReference, name, PropertyType.WillSet); - } - - SwiftType ConvertToDidSet (Node node, bool isReference, SwiftName name) - { - return ConvertToEtter (node.Children [0], isReference, name, PropertyType.DidSet); - } - - SwiftType ConvertToModifyAccessor (Node node, bool isReference, SwiftName name) - { - return ConvertToEtter (node.Children [0], isReference, name, PropertyType.ModifyAccessor); - } - - SwiftType ConvertToSubscriptEtter (Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - var functionNode = new Node (NodeKind.Function); - functionNode.Children.AddRange (node.Children); - functionNode.Children.Insert (1, new Node (NodeKind.Identifier, "subscript")); - var theFunc = ConvertToFunction (functionNode, isReference, name) as SwiftBaseFunctionType; - if (theFunc == null) - return null; - - var uncurriedFunctionType = theFunc as SwiftUncurriedFunctionType; - - // if this is normal subscript, uncurriedFunctionType will be non-null - // if this is an extension, uncurriedFunctionType will be null. - - SwiftFunctionType accessor = null; - switch (propertyType) { - case PropertyType.Setter: - // oh hooray! - // If I define an indexer in swift like this: - // public subscript(T index) -> U { - // get { return getSomeUValue(index); } - // set (someUValue) { setSomeUValue(index, someUValue); } - // } - // This signature of the function attached to both properties is: - // T -> U - // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but - // the setter is (T, U) -> void - // - // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect - // what's really happening. - - // need to change this so that the tail parameters get names? Maybe just the head? - var newParameters = theFunc.ParameterCount == 1 ? - new SwiftTupleType (false, null, theFunc.ReturnType, - theFunc.Parameters.RenamedCloneOf (new SwiftName (theFunc.ReturnType.Name == null || - theFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) - : new SwiftTupleType (Enumerable.Concat (theFunc.ReturnType.Yield (), theFunc.EachParameter), false, null); - accessor = new SwiftFunctionType (newParameters, SwiftTupleType.Empty, false, theFunc.CanThrow, theFunc.Name, theFunc.ExtensionOn); - break; - default: - // Because I decided to get clever and reuse existing code to demangle the underlying function, - // I get back either a SwiftFunctionType for an extension for a SwiftUncurriedFunctionType for - // an instance subscript. These types share a common base class, but are otherwise unrelated. - // I need a SwiftFunctionType, so here we are. - accessor = new SwiftFunctionType (theFunc.Parameters, theFunc.ReturnType, false, theFunc.IsReference, theFunc.Name, theFunc.ExtensionOn); - break; - } - - - var propType = theFunc.ReturnType; - var propName = theFunc.Name; - var prop = new SwiftPropertyType (uncurriedFunctionType?.UncurriedParameter, propertyType, propName, null, accessor, false, isReference); - prop.ExtensionOn = accessor.ExtensionOn; - prop.DiscretionaryString = theFunc.DiscretionaryString; - return prop; - } - - SwiftType ConvertToSubscriptGetter (Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSubscriptSetter (Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToSubscriptModifier (Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter (node.Children [0], isReference, name, PropertyType.ModifyAccessor); - } - - SwiftType ConvertToDispatchThunk (Node node, bool isReference, SwiftName name) - { - var thunkType = ConvertFirstChildToSwiftType (node, isReference, name); - if (thunkType == null) - return null; - if (thunkType is SwiftBaseFunctionType funcType) - return funcType.AsThunk (); - return null; - } - - SwiftType ConvertToTupleElement (Node node, bool isReference, SwiftName name) - { - name = node.Children [0].Kind == NodeKind.TupleElementName ? new SwiftName (node.Children [0].Text, false) : name; - var index = node.Children [0].Kind == NodeKind.TupleElementName ? 1 : 0; - return ConvertToSwiftType (node.Children [index], isReference, name); - } - - SwiftType ConvertToVariadicTupleElement (Node node, bool isReference, SwiftName name) - { - var type = ConvertToSwiftType (node.Children [1], false, null); - if (type == null) - return null; - - // in the past, this came through as an array with the variadic marker set. - // no longer is the case, so we synthesize the array and set the variadic marker. - var nesting = new List () { MemberNesting.Struct }; - var names = new List () { new SwiftName ("Array", false) }; - var arrayName = new SwiftClassName (new SwiftName ("Swift", false), nesting, names); - var container = new SwiftBoundGenericType (new SwiftClassType (arrayName, false), new List () { type }, isReference, name); - container.IsVariadic = true; - return container; - } - - SwiftType ConvertToGenericReference (Node node, bool isReference, SwiftName name) - { - long depth = node.Children [0].Index; - long index = node.Children [1].Index; - return new SwiftGenericArgReferenceType ((int)depth, (int)index, isReference, name); - } - - SwiftType ConvertToBoundGeneric (Node node, bool isReference, SwiftName name) - { - var baseType = ConvertToSwiftType (node.Children [0], false, null); - var boundTypes = ConvertTypeList (node.Children [1]); - return new SwiftBoundGenericType (baseType, boundTypes, isReference, name); - } - - List ConvertTypeList (Node node) - { - var typeList = new List (node.Children.Count); - foreach (var childNode in node.Children) { - typeList.Add (ConvertToSwiftType (childNode, false, null)); - } - return typeList; - } - - SwiftType ConvertToFunction (Node node, bool isReference, SwiftName name) - { - var isExtension = node.Children [0].Kind == NodeKind.Extension; - SwiftType extensionOn = null; - SwiftName module = null; - var nesting = new List (); - var names = new List (); - - if (isExtension) { - module = new SwiftName (node.Children [0].Children [0].Text, false); - extensionOn = ConvertToSwiftType (node.Children [0].Children [1], false, null); - } else { - module = BuildMemberNesting (node.Children [0], nesting, names); - } - - var operatorType = ToOperatorType (node.Children [1].Kind); - var funcName = operatorType == OperatorType.None ? PrivateNamePublicName (node.Children [1]).Item2 : node.Children [1].Text; - var labelsList = node.Children [2].Kind == NodeKind.LabelList ? ToLabelList (node.Children [2]) : new List (); - var typeIndex = node.Children [2].Kind == NodeKind.LabelList ? 3 : 2; - var functionType = ConvertToSwiftType (node.Children [typeIndex], isReference, new SwiftName (funcName, false)) as SwiftFunctionType; - if (functionType == null) - return null; - - var args = labelsList.Count > 0 ? RenameFunctionParameters (functionType.Parameters, labelsList) : functionType.Parameters; - if (nesting.Count > 0) { - var classType = new SwiftClassType (new SwiftClassName (module, nesting, names), false); - var methodName = classType.ClassName.ToFullyQualifiedName (true) + - (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + - "." + funcName; - var uncurried = new SwiftUncurriedFunctionType (classType, args, functionType.ReturnType, - functionType.IsReference, functionType.CanThrow, new SwiftName (funcName, false)); - uncurried.DiscretionaryString = methodName; - uncurried.GenericArguments.AddRange (functionType.GenericArguments); - return uncurried; - } - var functionName = module + - (operatorType != OperatorType.None ? $".|{operatorType.ToString ()}" : "") + - "." + funcName; - var generics = functionType.GenericArguments; - functionType = new SwiftFunctionType (args, functionType.ReturnType, functionType.IsReference, functionType.CanThrow, new SwiftName (funcName, false), extensionOn); - functionType.GenericArguments.AddRange (generics); - functionType.DiscretionaryString = functionName; - return functionType; - } - - SwiftType ConvertToStatic (Node node, bool isReference, SwiftName name) - { - var functionType = ConvertToSwiftType (node.Children [0], isReference, name); - if (functionType == null) - return null; - var propType = functionType as SwiftPropertyType; - if (propType != null) { - return propType.RecastAsStatic (); - } - var uncurriedFunction = functionType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) { - var staticFunction = new SwiftStaticFunctionType (uncurriedFunction.Parameters, uncurriedFunction.ReturnType, - uncurriedFunction.IsReference, uncurriedFunction.CanThrow, - uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); - staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; - return staticFunction; - } - var baseFunctionType = functionType as SwiftBaseFunctionType; - if (baseFunctionType != null) { - var staticFunction = new SwiftStaticFunctionType (baseFunctionType.Parameters, baseFunctionType.ReturnType, - baseFunctionType.IsReference, baseFunctionType.CanThrow, - null, baseFunctionType.Name); - staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; - staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; - return staticFunction; - } - var initializerType = functionType as SwiftInitializerType; - if (initializerType != null) { - return initializerType; // this doesn't need a static recast? - } - throw new ArgumentOutOfRangeException ($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType ().Name}"); - } - - List ToLabelList(Node node) - { - var result = new List (); - foreach (var child in node.Children) { - if (child.Kind == NodeKind.Identifier) { - result.Add (new SwiftName (child.Text, false)); - } else { - result.Add (new SwiftName ("_", false)); - } - } - return result; - } - - SwiftType ConvertToExistentialMetatype (Node node, bool isReference, SwiftName name) - { - var child = ConvertFirstChildToSwiftType (node, false, name); - var childType = child as SwiftProtocolListType; - if (child is SwiftClassType classType) { - childType = new SwiftProtocolListType (classType, classType.IsReference, classType.Name); - } - if (childType == null) - return null; - return new SwiftExistentialMetaType (childType, isReference, null); - } - - SwiftType ConvertToMetatype (Node node, bool isReference, SwiftName name) - { - var child = ConvertFirstChildToSwiftType (node, false, name); - if (child is SwiftClassType cl) { - return new SwiftMetaClassType (cl, isReference, name); - } else if (child is SwiftGenericArgReferenceType classReference) { - return new SwiftMetaClassType (classReference, isReference, name); - } else { - return null; - } - } - - SwiftType ConvertToGenericFunction (Node node, bool isReference, SwiftName name) - { - List args = GetGenericArguments (node); - var theFunction = ConvertToSwiftType (node.Children [1], isReference, name) as SwiftBaseFunctionType; - theFunction.GenericArguments.AddRange (args); - return theFunction; - } - - List GetGenericArguments (Node node) - { - var paramCountNode = node.Children [0].Children [0]; - if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) - throw new NotSupportedException ($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString ()}"); - - var paramCount = (int)paramCountNode.Index; - List args = new List (paramCount); - for (int i = 0; i < paramCount; i++) { - args.Add (new GenericArgument (0, i)); - } - if (node.Children [0].Children.Count > 1) { - var dependentGenericSignature = node.Children [0]; - // the 0th child is the number of generic parameters (see above) - for (int i = 1; i < dependentGenericSignature.Children.Count; i++) { - var genericParamReference = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [0], false, null) as SwiftGenericArgReferenceType; - var genericConstraintType = ConvertToSwiftType (dependentGenericSignature.Children [i].Children [1], false, null) as SwiftClassType; - MarkGenericConstraint (args, genericParamReference, genericConstraintType); - } - } - return args; - } - - static void MarkGenericConstraint (List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) - { - foreach (var genArg in args) { - if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) { - genArg.Constraints.Add (constraintType); - return; - } - } - } - - static SwiftBuiltInType TryAsBuiltInType (Node node, SwiftClassName className, bool isReference, SwiftName name) - { - switch (className.ToFullyQualifiedName ()) { - case "Swift.Int": - return new SwiftBuiltInType (CoreBuiltInType.Int, isReference, name); - case "Swift.Float": - return new SwiftBuiltInType (CoreBuiltInType.Float, isReference, name); - case "Swift.Bool": - return new SwiftBuiltInType (CoreBuiltInType.Bool, isReference, name); - case "Swift.UInt": - return new SwiftBuiltInType (CoreBuiltInType.UInt, isReference, name); - case "Swift.Double": - return new SwiftBuiltInType (CoreBuiltInType.Double, isReference, name); - default: - return null; - } - } - - static SwiftName BuildMemberNesting (Node node, List nestings, List names) - { - if (node.Children.Count > 0 && node.Children [0].Kind == NodeKind.Extension) - node = node.Children [0].Children [1]; - var nesting = MemberNesting.Class; - switch (node.Kind) { - case NodeKind.Class: - break; - case NodeKind.Structure: - nesting = MemberNesting.Struct; - break; - case NodeKind.Enum: - nesting = MemberNesting.Enum; - break; - case NodeKind.Protocol: - nesting = MemberNesting.Protocol; - break; - case NodeKind.Module: - return new SwiftName (node.Text, false); - default: - throw new ArgumentOutOfRangeException (nameof (node), $"Expected a nominal type node kind but got {node.Kind.ToString ()}"); - } - - var privatePublicName = PrivateNamePublicName (node.Children [1]); - var className = new SwiftName (privatePublicName.Item2, false); - SwiftName moduleName = null; - if (node.Children [0].Kind == NodeKind.Identifier || node.Children [0].Kind == NodeKind.Module) { - moduleName = new SwiftName (node.Children [0].Text, false); - } else { - // recurse before adding names. - moduleName = BuildMemberNesting (node.Children [0], nestings, names); - } - names.Add (className); - nestings.Add (nesting); - return moduleName; - } - - - static Tuple PrivateNamePublicName (Node node) - { - if (node.Kind == NodeKind.Identifier) - return new Tuple (null, node.Text); - if (node.Kind == NodeKind.PrivateDeclName) - return new Tuple (node.Children [1].Text, node.Children [0].Text); - throw new ArgumentOutOfRangeException (nameof (node)); - } - - static SwiftType RenameFunctionParameters (SwiftType parameters, List labels) - { - if (labels.Count < 1) - throw new ArgumentOutOfRangeException (nameof (parameters)); - - var oldTuple = parameters as SwiftTupleType; - if (oldTuple == null) - throw new NotSupportedException ($"{parameters} is not a tuple, it's a {parameters.GetType ().Name}"); - - var newTuple = new SwiftTupleType (oldTuple.Contents.Select ((elem, index) => RenamedCloneOf (elem, labels [index])), - oldTuple.IsReference, oldTuple.Name); - return newTuple; - } - - static SwiftType RenamedCloneOf (SwiftType st, SwiftName newName) - { - return st.RenamedCloneOf (newName.Name == "_" ? new SwiftName ("", false) : newName); - } - - - // Swift does...weird...things with some of the core types from C. - // The mangler doesn't put in the appropriate swift module, but instead lumps them all - // together into the module __C. - // The mangler also puts a number of Foundation types into the namespace __ObjC. - // Why? No idea. - // I determined this list of __ObjC types by running the following command on all the Apple built libraries: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq - // which also includes a number of inner types which we don't care about (yet). - - // The command to do this for the __C namespace is: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq - - struct ModuleOrType { - public ModuleOrType (string replacementModule) - { - ReplacementModule = replacementModule; - ReplacementFullClassName = null; - ReplacementNesting = null; - } - - public ModuleOrType (string replacementFullClassName, string replacementNesting) - { - ReplacementFullClassName = replacementFullClassName; - ReplacementNesting = replacementNesting; - ReplacementModule = null; - } - - public string ReplacementModule; - public string ReplacementFullClassName; - public string ReplacementNesting; - } - - - static Dictionary classNameOntoModuleOrType = new Dictionary { - { "AVError", new ModuleOrType ("AVFoundation") }, - { "AudioBuffer", new ModuleOrType ("AudioToolbox") }, - { "AudioBufferList", new ModuleOrType ("AudioToolbox") }, - { "CATransform3D", new ModuleOrType ("CoreAnimation") }, - { "CGAffineTransform", new ModuleOrType ("CoreGraphics") }, - { "CGColorSapceModel", new ModuleOrType ("CoreGraphics") }, - { "CGPoint", new ModuleOrType ("CoreGraphics") }, - { "CGRect", new ModuleOrType ("CoreGraphics") }, - { "CGSize", new ModuleOrType ("CoreGraphics") }, - { "CGVector", new ModuleOrType ("CoreGraphics") }, - { "CLError", new ModuleOrType ("CoreLocation") }, - { "CMTime", new ModuleOrType ("CoreMedia") }, - { "CMTimeFlags", new ModuleOrType ("CoreMedia") }, - { "CMTimeMapping", new ModuleOrType ("CoreMedia") }, - { "CMTimeRange", new ModuleOrType ("CoreMedia") }, - { "NSComparisonResult", new ModuleOrType ("Foundation") }, - { "NSDecimal", new ModuleOrType ("Foundation") }, - { "NSEnumerationOptions", new ModuleOrType ("Foundation") }, - { "NSKeyValueChange", new ModuleOrType ("Foundation") }, - { "NSKeyValueObservingOptions", new ModuleOrType ("Foundation") }, - { "NSFastEnumerationState", new ModuleOrType ("Foundation") }, - { "NSKeyValueChangeKey", new ModuleOrType ("Foundation") }, - { "NSBundle", new ModuleOrType ("Foundation.Bundle", "C") }, - { "NSURL", new ModuleOrType ("Foundation") }, - { "StringTransform", new ModuleOrType ("Foundation") }, - { "URLFileResourceType", new ModuleOrType ("Foundation") }, - { "URLResourceKey", new ModuleOrType ("Foundation") }, - { "URLThumbnailDictionaryItem", new ModuleOrType ("Foundation") }, - { "URLUbiquitousItemDownloadingStatus", new ModuleOrType ("Foundation") }, - { "URLUbiquitousSharedItemPermissions", new ModuleOrType ("Foundation") }, - { "URLUbiquitousSharedItemRole", new ModuleOrType ("Foundation") }, - { "MKCoordinateSpan", new ModuleOrType ("MapKit") }, - { "NSAnimationEffect", new ModuleOrType ("AppKit") }, - { "SCNGeometryPrimitiveType", new ModuleOrType ("SceneKit") }, - { "SCNVector3", new ModuleOrType ("SceneKit") }, - { "SCNVector4", new ModuleOrType ("SceneKit") }, - { "UIContentSizeCategory", new ModuleOrType ("UIKit") }, - { "UIControlState", new ModuleOrType ("UIKit.UIControl.State", "CV") }, - { "UIDeviceOrientation", new ModuleOrType ("UIKit") }, - { "UIEdgeInsets", new ModuleOrType ("UIKit") }, - { "UIInterfaceOrientation", new ModuleOrType ("UIKit") }, - { "UIControlEvents", new ModuleOrType ("UIKit.UIControl.Event", "CV") }, - { "UIViewAnimationOptions", new ModuleOrType ("UIKit.UIView.AnimationOptions", "CV") }, - { "UIOffset", new ModuleOrType ("UIKit") }, - { "UIBlurEffectStyle", new ModuleOrType ("UIKit.UIBlurEffect.Style","CV") }, - { "UIColor", new ModuleOrType ("UIKit")}, - { "UIImage", new ModuleOrType ("UIImage") }, - { "UITableViewStyle", new ModuleOrType ("UIKit.UITableView.Style", "CV") }, - { "UIView", new ModuleOrType ("UIKit") }, - { "UIViewControllerConditioning", new ModuleOrType ("UIKit") }, - { "UIVisualEffectView", new ModuleOrType ("UIKit") }, - { "CKError", new ModuleOrType ("CloudKit") }, - { "CNError", new ModuleOrType ("Contacts") }, - { "MTLSamplePosition", new ModuleOrType ("Metal") }, - { "XCUIKeyboardKey", new ModuleOrType ("XCTest") }, - { "BNNSActivationFunction", new ModuleOrType ("Accelerate") }, - { "BNNSDataType", new ModuleOrType ("Accelerate") }, - { "simd_double2x2", new ModuleOrType ("Accelerate") }, - { "simd_double2x3", new ModuleOrType ("Accelerate") }, - { "simd_double2x4", new ModuleOrType ("Accelerate") }, - { "simd_double3x2", new ModuleOrType ("Accelerate") }, - { "simd_double3x3", new ModuleOrType ("Accelerate") }, - { "simd_double3x4", new ModuleOrType ("Accelerate") }, - { "simd_double4x2", new ModuleOrType ("Accelerate") }, - { "simd_double4x3", new ModuleOrType ("Accelerate") }, - { "simd_double4x4", new ModuleOrType ("Accelerate") }, - { "simd_float2x2", new ModuleOrType ("Accelerate") }, - { "simd_float2x3", new ModuleOrType ("Accelerate") }, - { "simd_float2x4", new ModuleOrType ("Accelerate") }, - { "simd_float3x2", new ModuleOrType ("Accelerate") }, - { "simd_float3x3", new ModuleOrType ("Accelerate") }, - { "simd_float3x4", new ModuleOrType ("Accelerate") }, - { "simd_float4x2", new ModuleOrType ("Accelerate") }, - { "simd_float4x3", new ModuleOrType ("Accelerate") }, - { "simd_float4x4", new ModuleOrType ("Accelerate") }, - { "simd_quatd", new ModuleOrType ("Accelerate") }, - { "simd_quatf", new ModuleOrType ("Accelerate") }, - }; - - static SwiftClassName PatchClassName (SwiftName moduleName, List nesting, List nestingNames) - { - // surprise! - // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version - // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough - // bottleneck to alias it. - if (moduleName.Name == "__ObjC") - moduleName = new SwiftName ("Foundation", false); - if (moduleName.Name != "__C" || nestingNames.Count != 1) - return new SwiftClassName (moduleName, nesting, nestingNames); - if (classNameOntoModuleOrType.ContainsKey (nestingNames[0].Name)) { - var moduleOrType = classNameOntoModuleOrType [nestingNames [0].Name]; - if (moduleOrType.ReplacementModule == null) { - return SwiftClassName.FromFullyQualifiedName (moduleOrType.ReplacementFullClassName, OperatorType.None, moduleOrType.ReplacementNesting); - } else { - moduleName = new SwiftName (moduleOrType.ReplacementModule, false); - } - } - return new SwiftClassName (moduleName, nesting, nestingNames); - } - - static Dictionary aliasNameOntoClassName = new Dictionary { - { "__C.NSOperatingSystemVersion", SwiftClassName.FromFullyQualifiedName ("Foundation.OperatingSystemVersion", OperatorType.None, 'V') }, - }; - - static SwiftClassName RemapTypeAlias (SwiftClassName className) - { - SwiftClassName newName = null; - return aliasNameOntoClassName.TryGetValue (className.ToFullyQualifiedName (true), out newName) ? newName : className; - } - } + Name = "Type", + NodeKind = NodeKind.Type, + Reducer = ConvertFirstChildToSwiftType, + MatchChildCount = false + }, + }; + } + + public TLDefinition Convert(Node node) + { + Exceptions.ThrowOnNull(node, nameof(node)); + + + switch (node.Kind) + { + case NodeKind.Type: + return Convert(node.Children[0]); + case NodeKind.Static: + return ConvertStatic(node); + case NodeKind.Function: + return ConvertFunction(node, isMethodDescriptor: false, isEnumCase: false); + case NodeKind.MethodDescriptor: + return ConvertFunction(node.Children[0], isMethodDescriptor: true, isEnumCase: false); + case NodeKind.EnumCase: + return ConvertFunction(node.Children[0], isMethodDescriptor: false, isEnumCase: true); + case NodeKind.Constructor: + case NodeKind.Allocator: + return ConvertFunctionConstructor(node); + case NodeKind.Destructor: + case NodeKind.Deallocator: + return ConvertFunctionDestructor(node); + case NodeKind.Getter: + case NodeKind.Setter: + case NodeKind.DidSet: + case NodeKind.MaterializeForSet: + case NodeKind.WillSet: + case NodeKind.ModifyAccessor: + return ConvertFunctionProp(node); + case NodeKind.DispatchThunk: + return ConvertDispatchThunk(node); + case NodeKind.Variable: + return ConvertVariable(node, false); + case NodeKind.PropertyDescriptor: + return ConvertPropertyDescriptor(node); + case NodeKind.TypeMetadataAccessFunction: + return ConvertCCtor(node); + case NodeKind.TypeMetadata: + return ConvertMetadata(node); + case NodeKind.NominalTypeDescriptor: + return ConvertNominalTypeDescriptor(node); + case NodeKind.ProtocolConformanceDescriptor: + return ConvertProtocolConformanceDescriptor(node); + case NodeKind.ProtocolDescriptor: + return ConvertProtocolDescriptor(node); + case NodeKind.Initializer: + return ConvertInitializer(node); + case NodeKind.TypeMetadataLazyCache: + return ConvertLazyCacheVariable(node); + case NodeKind.ProtocolWitnessTable: + case NodeKind.ProtocolWitnessTableAccessor: + case NodeKind.ValueWitnessTable: + return ConvertProtocolWitnessTable(node); + case NodeKind.FieldOffset: + return ConvertFieldOffset(node); + case NodeKind.DefaultArgumentInitializer: + return ConvertDefaultArgumentInitializer(node); + case NodeKind.Metaclass: + return ConvertMetaclass(node); + case NodeKind.UnsafeMutableAddressor: + return ConvertUnsafeMutableAddressor(node); + case NodeKind.CurryThunk: + return ConvertCurryThunk(node); + case NodeKind.GenericTypeMetadataPattern: + return ConvertTypeMetadataPattern(node); + case NodeKind.Global: + return Convert(node); + case NodeKind.ModuleDescriptor: + return ConvertModuleDescriptor(node); + case NodeKind.ReflectionMetadataFieldDescriptor: + return ConvertMetadataFieldDescriptor(node, false); + case NodeKind.ReflectionMetadataBuiltinDescriptor: + return ConvertMetadataFieldDescriptor(node, true); + case NodeKind.ProtocolRequirementsBaseDescriptor: + return ConvertProtocolRequirementsBaseDescriptor(node); + case NodeKind.BaseConformanceDescriptor: + return ConvertBaseConformanceDescriptor(node); + case NodeKind.AssociatedTypeDescriptor: + return ConvertAssocatedTypeDescriptor(node); + case NodeKind.ClassMetadataBaseOffset: + return ConvertMetadataBaseOffset(node); + case NodeKind.MethodLookupFunction: + return ConvertMethodLookupFunction(node); + default: + return null; + } + } + + + TLDefinition ConvertDispatchThunk(Node node) + { + switch (node.Children[0].Kind) + { + case NodeKind.Getter: + case NodeKind.Setter: + case NodeKind.DidSet: + case NodeKind.MaterializeForSet: + case NodeKind.WillSet: + case NodeKind.ModifyAccessor: + return ConvertFunctionProp(node); + case NodeKind.Static: + return ConvertStaticDispatchThunk(node); + case NodeKind.Function: + case NodeKind.Allocator: + return ConvertFunction(node, isMethodDescriptor: false, isEnumCase: false); + default: + return null; + } + } + + TLDefinition ConvertStaticDispatchThunk(Node node) + { + if (node.Children[0].Children[0].Kind == NodeKind.Variable) + { + return ConvertStaticDispatchThunkVariable(node); + } + else + { + return ConvertStatic(node); + } + } + + TLDefinition ConvertStaticDispatchThunkVariable(Node node) + { + return null; + } + + + TLFunction ConvertFunction(Node node, bool isMethodDescriptor, bool isEnumCase) + { + var swiftType = ConvertToSwiftType(node, false, null); + var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) + { + // method + var context = uncurriedFunction.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var functionName = new SwiftName(context.Last(), false); + return isMethodDescriptor ? + new TLMethodDescriptor(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset) : + isEnumCase ? + new TLEnumCase(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset) : + new TLFunction(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, + uncurriedFunction, offset); + } + + var plainFunction = swiftType as SwiftFunctionType; + if (plainFunction != null) + { + var context = plainFunction.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context[context.Length - 2][0] == '|') + { + Enum.TryParse(context[context.Length - 2].Substring(1), out operatorType); + } + var functionName = new SwiftName(context.Last(), false); + return isMethodDescriptor ? + new TLMethodDescriptor(mangledName, module, functionName, null, plainFunction, offset, operatorType) : + new TLFunction(mangledName, module, functionName, null, plainFunction, offset, operatorType); + } + return null; + } + + TLDefinition ConvertStatic(Node node) + { + if (node.Children[0].Kind == NodeKind.Variable) + { + return ConvertVariable(node.Children[0], true); + } + var swiftType = ConvertToSwiftType(node, false, null); + var propType = swiftType as SwiftPropertyType; + if (propType != null) + { + var context = propType.DiscretionaryString.Split('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction(mangledName, new SwiftName(context[0], false), propType.Name, uncurriedParam, propType, offset); + } + + var staticFunction = swiftType as SwiftStaticFunctionType; + if (staticFunction != null) + { + var context = staticFunction.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var operatorType = OperatorType.None; + if (context.Length > 2 && context[context.Length - 2][0] == '|') + { + Enum.TryParse(context[context.Length - 2].Substring(1), out operatorType); + } + var functionName = new SwiftName(context.Last(), false); + return new TLFunction(mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); + } + return null; + } + + TLFunction ConvertFunctionConstructor(Node node) + { + var swiftType = ConvertToSwiftType(node, false, null); + var constructor = swiftType as SwiftConstructorType; + if (constructor != null) + { + var context = constructor.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var functionName = constructor.Name; + var metaType = constructor.UncurriedParameter as SwiftMetaClassType; + return new TLFunction(mangledName, module, functionName, metaType.Class, constructor, offset); + } + return null; + } + + TLFunction ConvertFunctionDestructor(Node node) + { + var swiftType = ConvertToSwiftType(node, false, null); + var destructor = swiftType as SwiftDestructorType; + if (destructor != null) + { + var context = destructor.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var functionName = destructor.Name; + var className = destructor.Parameters as SwiftClassType; + if (className == null) + throw new NotSupportedException($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType().Name}"); + return new TLFunction(mangledName, module, functionName, className, destructor, offset); + } + return null; + } + + TLFunction ConvertFunctionProp(Node node) + { + var propType = ConvertToSwiftType(node, false, null) as SwiftPropertyType; + if (propType == null) + return null; + var context = propType.DiscretionaryString.Split('.'); + var uncurriedParam = propType.UncurriedParameter as SwiftClassType; + return new TLFunction(mangledName, new SwiftName(context[0], false), propType.Name, uncurriedParam, propType, offset); + } + + TLVariable ConvertVariable(Node node, bool isStatic) + { + // Variable + // + if (node.Children.Count != 3 && node.Children.Count != 4) + throw new ArgumentOutOfRangeException(nameof(node), $"Expected 3 or 4 children in a variable node, but got {node.Children.Count}"); + + if (node.Kind == NodeKind.Subscript) + { + var subFunc = ConvertToSubscriptEtter(node, false, null, PropertyType.Getter) as SwiftPropertyType; + var module = subFunc.DiscretionaryString.Split('.')[0]; + return new TLVariable(mangledName, new SwiftName(module, false), subFunc.UncurriedParameter as SwiftClassType, + new SwiftName("subscript", false), subFunc.OfType, isStatic, offset); + } + + if (node.Children[2].Kind == NodeKind.LabelList && node.Children[3].Kind == NodeKind.Type && + node.Children[3].Children[0].Kind == NodeKind.FunctionType) + { + var functionNode = new Node(NodeKind.Function); + functionNode.Children.AddRange(node.Children); + var function = ConvertFunction(functionNode, isMethodDescriptor: false, isEnumCase: false); + SwiftClassType classOn = null; + if (function.Signature is SwiftUncurriedFunctionType ucf) + { + classOn = ucf.UncurriedParameter as SwiftClassType; + } + return new TLVariable(mangledName, function.Module, classOn, function.Name, function.Signature, isStatic, offset); + } + else + { + var isExtension = node.Children[0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType context = null; + + + if (isExtension) + { + module = new SwiftName(node.Children[0].Children[0].Text, false); + extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); + if (extensionOn == null) + return null; + } + else + { + var nesting = new List(); + var nestingNames = new List(); + module = BuildMemberNesting(node.Children[0], nesting, nestingNames); + context = nesting.Count > 0 ? new SwiftClassType(new SwiftClassName(module, nesting, nestingNames), false) : null; + } + + var name = new SwiftName(node.Children[1].Text, false); + var variableType = ConvertToSwiftType(node.Children[2], false, null); + return new TLVariable(mangledName, module, context, name, variableType, isStatic, offset, extensionOn); + } + } + + TLPropertyDescriptor ConvertPropertyDescriptor(Node node) + { + var tlvar = ConvertVariable(node.Children[0], false); + if (tlvar == null) + return null; + return new TLPropertyDescriptor(tlvar.MangledName, tlvar.Module, tlvar.Class, tlvar.Name, tlvar.OfType, false, tlvar.Offset, tlvar.ExtensionOn); + } + + TLFunction ConvertCCtor(Node node) + { + var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + var metaType = new SwiftMetaClassType(classType, false); + var cctor = new SwiftClassConstructorType(metaType, false); + return new TLFunction(mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, + cctor, offset); + } + + TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer(Node node) + { + if (node.Children.Count != 2) + return null; + var baseFunction = ConvertToSwiftType(node.Children[0], false, null) as SwiftBaseFunctionType; + if (baseFunction == null) + return null; + var context = baseFunction.DiscretionaryString.Split('.'); + var module = new SwiftName(context[0], false); + var argumentIndex = (int)node.Children[1].Index; + return new TLDefaultArgumentInitializer(mangledName, module, baseFunction, argumentIndex, offset); + } + + TLFieldOffset ConvertFieldOffset(Node node) + { + if (node.Children.Count != 2 || node.Children[0].Kind != NodeKind.Directness) + return null; + var variable = ConvertVariable(node.Children[1], false) as TLVariable; + if (variable == null) + return null; + + return new TLFieldOffset(mangledName, variable.Module, variable.Class, node.Children[0].Index == 0, variable.Name, + variable.OfType, offset); + } + + TLDirectMetadata ConvertMetadata(Node node) + { + var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + return new TLDirectMetadata(mangledName, classType.ClassName.Module, classType, offset); + } + + TLNominalTypeDescriptor ConvertNominalTypeDescriptor(Node node) + { + var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + return new TLNominalTypeDescriptor(mangledName, classType.ClassName.Module, classType, offset); + } + + TLProtocolConformanceDescriptor ConvertProtocolConformanceDescriptor(Node node) + { + node = node.Children[0]; + if (node.Kind != NodeKind.ProtocolConformance) + return null; + if (node.Children.Count != 3) + return null; + var implementingType = ConvertToSwiftType(node.Children[0], false, null); + if (implementingType == null) + return null; + var forProtocol = ConvertToSwiftType(node.Children[1], false, null) as SwiftClassType; + if (forProtocol == null) + return null; + var module = new SwiftName(node.Children[2].Text, false); + return new TLProtocolConformanceDescriptor(mangledName, module, implementingType, forProtocol, offset); + } + + TLProtocolTypeDescriptor ConvertProtocolDescriptor(Node node) + { + var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + return new TLProtocolTypeDescriptor(mangledName, classType.ClassName.Module, classType, offset); + } + + TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor(Node node) + { + if (node.Children[0].Kind != NodeKind.Variable) + throw new ArgumentOutOfRangeException($"Expected a Variable child but got a {node.Children[0].Kind}"); + var variable = ConvertVariable(node.Children[0], false); + return new TLUnsafeMutableAddressor(mangledName, variable.Module, null, variable.Name, variable.OfType, variable.Offset); + } + + TLMetaclass ConvertMetaclass(Node node) + { + if (node.Children[0].Kind != NodeKind.Type) + return null; + var classType = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; + if (classType == null) + return null; + var module = classType.ClassName.Module; + return new TLMetaclass(mangledName, module, classType, offset); + } + + TLGenericMetadataPattern ConvertTypeMetadataPattern(Node node) + { + var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLGenericMetadataPattern(mangledName, type.ClassName.Module, type, offset); + } + + TLFunction ConvertInitializer(Node node) + { + var variable = node.Children[0]; + var context = ConvertToSwiftType(variable.Children[0], false, null) as SwiftClassType; + if (context == null) + return null; + var privatePublicName = PrivateNamePublicName(variable.Children[1]); + var name = new SwiftName(privatePublicName.Item2, false); + var typeIndex = variable.Children[2].Kind == NodeKind.LabelList ? 3 : 2; + var type = ConvertToSwiftType(variable.Children[typeIndex], false, null); + var initializer = new SwiftInitializerType(InitializerType.Variable, type, context, name); + return new TLFunction(mangledName, context.ClassName.Module, name, initializer.Owner, initializer, offset); + } + + TLLazyCacheVariable ConvertLazyCacheVariable(Node node) + { + var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + return new TLLazyCacheVariable(mangledName, classType.ClassName.Module, classType, offset); + } + + TLFunction ConvertProtocolWitnessTable(Node node) + { + var witnessTable = ConvertToSwiftType(node, false, null) as SwiftWitnessTableType; + + var rebuiltWitnessTable = new SwiftWitnessTableType(witnessTable.WitnessType, witnessTable.ProtocolType, witnessTable.UncurriedParameter as SwiftClassType); + + return new TLFunction(mangledName, new SwiftName(witnessTable.DiscretionaryString, false), null, + witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); + } + + TLThunk ConvertCurryThunk(Node node) + { + TLFunction func = ConvertFunction(node.Children[0], isMethodDescriptor: false, isEnumCase: false); + return new TLThunk(ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); + } + + TLModuleDescriptor ConvertModuleDescriptor(Node node) + { + var firstChild = node.Children[0]; + if (firstChild.Kind != NodeKind.Module) + return null; + return new TLModuleDescriptor(mangledName, new SwiftName(firstChild.Text, false), offset); + } + + TLMetadataDescriptor ConvertMetadataFieldDescriptor(Node node, bool isBuiltIn) + { + var ofType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (ofType == null) + return null; + return new TLMetadataDescriptor(ofType, isBuiltIn, mangledName, ofType.ClassName.Module, offset); + } + + TLProtocolRequirementsBaseDescriptor ConvertProtocolRequirementsBaseDescriptor(Node node) + { + var ofType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (ofType == null) + return null; + return new TLProtocolRequirementsBaseDescriptor(mangledName, ofType.ClassName.Module, ofType, offset); + } + + TLBaseConformanceDescriptor ConvertBaseConformanceDescriptor(Node node) + { + var protocol = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (protocol == null) + return null; + var requirement = ConvertToSwiftType(node.Children[1], false, null) as SwiftClassType; + if (requirement == null) + return null; + return new TLBaseConformanceDescriptor(mangledName, protocol.ClassName.Module, protocol, requirement, offset); + } + + TLAssociatedTypeDescriptor ConvertAssocatedTypeDescriptor(Node node) + { + var name = new SwiftName(node.Children[0].Text, false); + var protocol = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; + if (protocol == null) + return null; + return new TLAssociatedTypeDescriptor(mangledName, protocol.ClassName.Module, protocol, name, offset); + } + + TLMetadataBaseOffset ConvertMetadataBaseOffset(Node node) + { + var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLMetadataBaseOffset(mangledName, type.ClassName.Module, type, offset); + } + + TLMethodLookupFunction ConvertMethodLookupFunction(Node node) + { + var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + if (type == null) + return null; + return new TLMethodLookupFunction(mangledName, type.ClassName.Module, type, offset); + } + + + // ConvertToFunctions are usually called from rules. + + SwiftType ConvertToReferenceType(Node node, bool isReference, SwiftName name) + { + return ConvertToSwiftType(node.Children[0].Children[0], true, name); + } + + SwiftType ConvertToSwiftType(Node node, bool isReference, SwiftName name) + { + return ruleRunner.RunRules(node, isReference, name); + } + + SwiftType ConvertFirstChildToSwiftType(Node node, bool isReference, SwiftName name) + { + if (node.Children.Count == 0) + throw new ArgumentOutOfRangeException(nameof(node)); + return ConvertToSwiftType(node.Children[0], isReference, name); + } + + SwiftType ConvertToGeneralFunctionType(Node node, bool isReference, SwiftName name, bool isEscaping) + { + var throws = node.Children[0].Kind == NodeKind.ThrowsAnnotation; + var startIndex = throws ? 1 : 0; + var args = ConvertToSwiftType(node.Children[startIndex + 0], false, null); + var returnType = ConvertToSwiftType(node.Children[startIndex + 1], false, null); + return new SwiftFunctionType(args, returnType, isReference, throws, name, isEscaping: isEscaping); + } + + SwiftType ConvertToFunctionType(Node node, bool isReference, SwiftName name) + { + return ConvertToGeneralFunctionType(node, isReference, name, true); + } + + SwiftType ConvertToNoEscapeFunctionType(Node node, bool isReference, SwiftName name) + { + return ConvertToGeneralFunctionType(node, isReference, name, false); + } + + OperatorType ToOperatorType(NodeKind kind) + { + switch (kind) + { + default: + case NodeKind.Identifier: + return OperatorType.None; + case NodeKind.PrefixOperator: + return OperatorType.Prefix; + case NodeKind.InfixOperator: + return OperatorType.Infix; + case NodeKind.PostfixOperator: + return OperatorType.Postfix; + } + } + + SwiftType ConvertToAllocatingConstructor(Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor(node, isReference, name, true); + } + + SwiftType ConvertToNonAllocatingConstructor(Node node, bool isReference, SwiftName name) + { + return ConvertToConstructor(node, isReference, name, false); + } + + SwiftType ConvertToConstructor(Node node, bool isReference, SwiftName name, bool isAllocating) + { + var isExtension = node.Children[0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType instanceType = null; + + if (isExtension) + { + module = new SwiftName(node.Children[0].Children[0].Text, false); + extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); + if (extensionOn == null) + return null; + if (extensionOn is SwiftBuiltInType builtIn) + { + extensionOn = new SwiftClassType(SwiftClassName.FromFullyQualifiedName($"Swift.{builtIn.BuiltInType}", OperatorType.None, "V"), false); + } + instanceType = extensionOn as SwiftClassType; + } + else + { + instanceType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + module = instanceType.ClassName.Module; + } + + var metadata = new SwiftMetaClassType(instanceType, false, null); + var labels = node.Children[1].Kind == NodeKind.LabelList ? ToLabelList(node.Children[1]) : null; + var typeIndex = labels == null ? 1 : 2; + var functionType = node.Children[typeIndex].Children[0]; + var functionThrows = functionType.Children.Count == 3 && functionType.Children[0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; + var args = ConvertToSwiftType(functionType.Children[0 + functionThrows], false, null); + args = labels != null && labels.Count > 0 ? RenameFunctionParameters(args, labels) : args; + var ret = ConvertToSwiftType(functionType.Children[1 + functionThrows], false, null); + var constructor = new SwiftConstructorType(isAllocating, metadata, args, ret, isReference, functionThrows != 0, extensionOn); + + constructor.DiscretionaryString = $"{module.Name}.{instanceType.ClassName.ToFullyQualifiedName(false)}"; + return constructor; + } + + SwiftType ConvertToDestructor(Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor(node, isReference, name, false); + } + + SwiftType ConvertToDeallocator(Node node, bool isReference, SwiftName name) + { + return ConvertToDestructor(node, isReference, name, true); + } + + SwiftType ConvertToDestructor(Node node, bool isReference, SwiftName name, bool isDeallocating) + { + var instanceType = ConvertToSwiftType(node.Children[0], false, null); + var sct = instanceType as SwiftClassType; + if (sct == null) + throw new NotSupportedException($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType().Name}."); + var destructor = new SwiftDestructorType(isDeallocating, sct, isReference, false); + destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName(true); + return destructor; + } + SwiftType ConvertToStruct(Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName(node); + var bit = TryAsBuiltInType(node, className, isReference, name); + return (SwiftType)bit ?? new SwiftClassType(className, isReference, name); + } + + SwiftType ConvertToTypeAlias(Node node, bool isReference, SwiftName name) + { + if (node.Children[0].Kind == NodeKind.Module && node.Children[0].Text == "__C") + { + var shamNode = new Node(NodeKind.Structure); + shamNode.Children.AddRange(node.Children); + var className = ToSwiftClassName(shamNode); + className = RemapTypeAlias(className); + return new SwiftClassType(className, isReference, name); + } + else + { + return null; + } + } + + SwiftType ConvertToClass(Node node, bool isReference, SwiftName name) + { + var className = ToSwiftClassName(node); + return new SwiftClassType(className, isReference, name); + } + + SwiftClassName ToSwiftClassName(Node node) + { + var memberNesting = new List(); + var nestingNames = new List(); + var moduleName = BuildMemberNesting(node, memberNesting, nestingNames); + + return PatchClassName(moduleName, memberNesting, nestingNames); + } + + SwiftType ConvertToDependentMember(Node node, bool isReference, SwiftName name) + { + // format should be + // DependentReferenceType + // Type + // GenericReference (depth, index) + // AssocPathItem (name) + // For multuple path elements, these get nested with the head being deepest. + // Weird flex, but OK. + var genericReference = ConvertFirstChildToSwiftType(node, isReference, name) as SwiftGenericArgReferenceType; + if (genericReference == null) + return null; + if (node.Children.Count < 2) + return genericReference; + var assocChild = node.Children[1]; + genericReference.AssociatedTypePath.Add(assocChild.Text); + return genericReference; + } + + SwiftType ConvertToCFunctionPointerType(Node node, bool isReference, SwiftName name) + { + var args = ConvertToSwiftType(node.Children[0], false, null); + var ret = ConvertToSwiftType(node.Children[1], false, null); + var function = new SwiftCFunctionPointerType(args, ret, isReference, false, name); + return function; + } + + SwiftType ConvertToTuple(Node node, bool isReference, SwiftName name) + { + var types = new List(); + if (node.Children.Count == 0) + { + return SwiftTupleType.Empty; + } + if (node.Children.Count == 1) + { + var onlyChild = ConvertFirstChildToSwiftType(node, false, null); + return new SwiftTupleType(isReference, name, onlyChild); + } + foreach (var child in node.Children) + { + var type = ConvertToSwiftType(child, false, null); + if (type == null) + return null; + types.Add(type); + } + return new SwiftTupleType(types, isReference, name); + } + + SwiftType ConvertToProtocolList(Node node, bool isReference, SwiftName name) + { + return ConvertToProtocolList(node, isReference, name, NodeKind.Type); + } + + SwiftType ConvertToProtocolListAnyObject(Node node, bool isReference, SwiftName name) + { + return ConvertToProtocolList(node.Children[0], isReference, name, node.Kind); + } + + SwiftType ConvertToProtocolList(Node node, bool isReference, SwiftName name, NodeKind nodeKind) + { + if (node.Children.Count != 1) + throw new NotSupportedException("ProtocolList node with more than 1 child not supported"); + if (node.Children[0].Kind != NodeKind.TypeList) + throw new NotSupportedException($"Given a ProtocolList node with child type {node.Children[0].Kind.ToString()} and {node.Children[0].Children.Count} children, but expected a TypeList with exactly 1 child."); + // If the number of elements is 0, it means that this is an "Any" type in swift. + // I'm assuming it's lodged here as a protocol list is that an empty protocol list is + // represented by an existential container which is also used to represent a protocol list. + if (node.Children[0].Children.Count == 0) + { + var anyName = nodeKind == NodeKind.ProtocolListWithAnyObject ? "Swift.AnyObject" : "Swift.Any"; + var anyProtocolType = nodeKind == NodeKind.ProtocolListWithAnyObject ? 'C' : 'P'; + var className = SwiftClassName.FromFullyQualifiedName(anyName, OperatorType.None, anyProtocolType); + var classType = new SwiftClassType(className, isReference, name); + return classType; + } + var typeList = ConvertTypeList(node.Children[0]).Select(t => t as SwiftClassType); + var protoListType = new SwiftProtocolListType(typeList, isReference, name); + if (protoListType.Protocols.Count == 1) + return protoListType.Protocols[0].RenamedCloneOf(name); + return protoListType; + } + + SwiftType ConvertToProtocolWitnessTable(Node node, bool isReference, SwiftName name) + { + var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? + WitnessType.Protocol : WitnessType.ProtocolAccessor; + var classType = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; + var protoType = ConvertToSwiftType(node.Children[0].Children[1], false, null) as SwiftClassType; + var protoWitness = new SwiftWitnessTableType(witnessType, protoType, classType); + protoWitness.DiscretionaryString = node.Children[0].Children[2].Text; + return protoWitness; + } + + SwiftType ConvertToValueWitnessTable(Node node, bool isReference, SwiftName name) + { + var valueType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; + var valueWitnessTable = new SwiftWitnessTableType(WitnessType.Value, null, valueType); + valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; + return valueWitnessTable; + } + + SwiftType ConvertToEtter(Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + var isExtension = node.Children[0].Kind == NodeKind.Extension; + SwiftName module = null; + SwiftType extensionOn = null; + SwiftClassType context = null; + SwiftClassName className = null; + + if (isExtension) + { + module = new SwiftName(node.Children[0].Children[0].Text, false); + extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); + if (extensionOn == null) + return null; + } + else + { + var nestings = new List(); + var names = new List(); + + module = BuildMemberNesting(node.Children[0], nestings, names); + if (module == null) + return null; + className = nestings.Count > 0 ? new SwiftClassName(module, nestings, names) : null; + context = className != null ? new SwiftClassType(className, false) : null; + } + + + var privatePublicName = PrivateNamePublicName(node.Children[1]); + var propName = new SwiftName(privatePublicName.Item2, false); + var privateName = privatePublicName.Item1 != null ? new SwiftName(privatePublicName.Item1, false) : null; + + var funcChildIndex = node.Children[2].Kind == NodeKind.LabelList ? 3 : 2; + + var getterType = ConvertToSwiftType(node.Children[funcChildIndex], false, propertyType == PropertyType.Setter ? new SwiftName("newValue", false) : null); + var prop = new SwiftPropertyType(context, propertyType, propName, privateName, + getterType, false, isReference, extensionOn); + prop.DiscretionaryString = context != null ? context.ClassName.ToFullyQualifiedName(true) + : $"{module.Name}.{propName.Name}"; + return prop; + + } + + SwiftType ConvertToGetter(Node node, bool isReference, SwiftName name) + { + // Getter + // Variable + // Context + // Type + return ConvertToEtter(node.Children[0], isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSetter(Node node, bool isReference, SwiftName name) + { + return ConvertToEtter(node.Children[0], isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToWillSet(Node node, bool isReference, SwiftName name) + { + return ConvertToEtter(node.Children[0], isReference, name, PropertyType.WillSet); + } + + SwiftType ConvertToDidSet(Node node, bool isReference, SwiftName name) + { + return ConvertToEtter(node.Children[0], isReference, name, PropertyType.DidSet); + } + + SwiftType ConvertToModifyAccessor(Node node, bool isReference, SwiftName name) + { + return ConvertToEtter(node.Children[0], isReference, name, PropertyType.ModifyAccessor); + } + + SwiftType ConvertToSubscriptEtter(Node node, bool isReference, SwiftName name, PropertyType propertyType) + { + var functionNode = new Node(NodeKind.Function); + functionNode.Children.AddRange(node.Children); + functionNode.Children.Insert(1, new Node(NodeKind.Identifier, "subscript")); + var theFunc = ConvertToFunction(functionNode, isReference, name) as SwiftBaseFunctionType; + if (theFunc == null) + return null; + + var uncurriedFunctionType = theFunc as SwiftUncurriedFunctionType; + + // if this is normal subscript, uncurriedFunctionType will be non-null + // if this is an extension, uncurriedFunctionType will be null. + + SwiftFunctionType accessor = null; + switch (propertyType) + { + case PropertyType.Setter: + // oh hooray! + // If I define an indexer in swift like this: + // public subscript(T index) -> U { + // get { return getSomeUValue(index); } + // set (someUValue) { setSomeUValue(index, someUValue); } + // } + // This signature of the function attached to both properties is: + // T -> U + // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but + // the setter is (T, U) -> void + // + // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect + // what's really happening. + + // need to change this so that the tail parameters get names? Maybe just the head? + var newParameters = theFunc.ParameterCount == 1 ? + new SwiftTupleType(false, null, theFunc.ReturnType, + theFunc.Parameters.RenamedCloneOf(new SwiftName(theFunc.ReturnType.Name == null || + theFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) + : new SwiftTupleType(Enumerable.Concat(theFunc.ReturnType.Yield(), theFunc.EachParameter), false, null); + accessor = new SwiftFunctionType(newParameters, SwiftTupleType.Empty, false, theFunc.CanThrow, theFunc.Name, theFunc.ExtensionOn); + break; + default: + // Because I decided to get clever and reuse existing code to demangle the underlying function, + // I get back either a SwiftFunctionType for an extension for a SwiftUncurriedFunctionType for + // an instance subscript. These types share a common base class, but are otherwise unrelated. + // I need a SwiftFunctionType, so here we are. + accessor = new SwiftFunctionType(theFunc.Parameters, theFunc.ReturnType, false, theFunc.IsReference, theFunc.Name, theFunc.ExtensionOn); + break; + } + + + var propType = theFunc.ReturnType; + var propName = theFunc.Name; + var prop = new SwiftPropertyType(uncurriedFunctionType?.UncurriedParameter, propertyType, propName, null, accessor, false, isReference); + prop.ExtensionOn = accessor.ExtensionOn; + prop.DiscretionaryString = theFunc.DiscretionaryString; + return prop; + } + + SwiftType ConvertToSubscriptGetter(Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.Getter); + } + + SwiftType ConvertToSubscriptSetter(Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.Setter); + } + + SwiftType ConvertToSubscriptModifier(Node node, bool isReference, SwiftName name) + { + return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.ModifyAccessor); + } + + SwiftType ConvertToDispatchThunk(Node node, bool isReference, SwiftName name) + { + var thunkType = ConvertFirstChildToSwiftType(node, isReference, name); + if (thunkType == null) + return null; + if (thunkType is SwiftBaseFunctionType funcType) + return funcType.AsThunk(); + return null; + } + + SwiftType ConvertToTupleElement(Node node, bool isReference, SwiftName name) + { + name = node.Children[0].Kind == NodeKind.TupleElementName ? new SwiftName(node.Children[0].Text, false) : name; + var index = node.Children[0].Kind == NodeKind.TupleElementName ? 1 : 0; + return ConvertToSwiftType(node.Children[index], isReference, name); + } + + SwiftType ConvertToVariadicTupleElement(Node node, bool isReference, SwiftName name) + { + var type = ConvertToSwiftType(node.Children[1], false, null); + if (type == null) + return null; + + // in the past, this came through as an array with the variadic marker set. + // no longer is the case, so we synthesize the array and set the variadic marker. + var nesting = new List() { MemberNesting.Struct }; + var names = new List() { new SwiftName("Array", false) }; + var arrayName = new SwiftClassName(new SwiftName("Swift", false), nesting, names); + var container = new SwiftBoundGenericType(new SwiftClassType(arrayName, false), new List() { type }, isReference, name); + container.IsVariadic = true; + return container; + } + + SwiftType ConvertToGenericReference(Node node, bool isReference, SwiftName name) + { + long depth = node.Children[0].Index; + long index = node.Children[1].Index; + return new SwiftGenericArgReferenceType((int)depth, (int)index, isReference, name); + } + + SwiftType ConvertToBoundGeneric(Node node, bool isReference, SwiftName name) + { + var baseType = ConvertToSwiftType(node.Children[0], false, null); + var boundTypes = ConvertTypeList(node.Children[1]); + return new SwiftBoundGenericType(baseType, boundTypes, isReference, name); + } + + List ConvertTypeList(Node node) + { + var typeList = new List(node.Children.Count); + foreach (var childNode in node.Children) + { + typeList.Add(ConvertToSwiftType(childNode, false, null)); + } + return typeList; + } + + SwiftType ConvertToFunction(Node node, bool isReference, SwiftName name) + { + var isExtension = node.Children[0].Kind == NodeKind.Extension; + SwiftType extensionOn = null; + SwiftName module = null; + var nesting = new List(); + var names = new List(); + + if (isExtension) + { + module = new SwiftName(node.Children[0].Children[0].Text, false); + extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); + } + else + { + module = BuildMemberNesting(node.Children[0], nesting, names); + } + + var operatorType = ToOperatorType(node.Children[1].Kind); + var funcName = operatorType == OperatorType.None ? PrivateNamePublicName(node.Children[1]).Item2 : node.Children[1].Text; + var labelsList = node.Children[2].Kind == NodeKind.LabelList ? ToLabelList(node.Children[2]) : new List(); + var typeIndex = node.Children[2].Kind == NodeKind.LabelList ? 3 : 2; + var functionType = ConvertToSwiftType(node.Children[typeIndex], isReference, new SwiftName(funcName, false)) as SwiftFunctionType; + if (functionType == null) + return null; + + var args = labelsList.Count > 0 ? RenameFunctionParameters(functionType.Parameters, labelsList) : functionType.Parameters; + if (nesting.Count > 0) + { + var classType = new SwiftClassType(new SwiftClassName(module, nesting, names), false); + var methodName = classType.ClassName.ToFullyQualifiedName(true) + + (operatorType != OperatorType.None ? $".|{operatorType.ToString()}" : "") + + "." + funcName; + var uncurried = new SwiftUncurriedFunctionType(classType, args, functionType.ReturnType, + functionType.IsReference, functionType.CanThrow, new SwiftName(funcName, false)); + uncurried.DiscretionaryString = methodName; + uncurried.GenericArguments.AddRange(functionType.GenericArguments); + return uncurried; + } + var functionName = module + + (operatorType != OperatorType.None ? $".|{operatorType.ToString()}" : "") + + "." + funcName; + var generics = functionType.GenericArguments; + functionType = new SwiftFunctionType(args, functionType.ReturnType, functionType.IsReference, functionType.CanThrow, new SwiftName(funcName, false), extensionOn); + functionType.GenericArguments.AddRange(generics); + functionType.DiscretionaryString = functionName; + return functionType; + } + + SwiftType ConvertToStatic(Node node, bool isReference, SwiftName name) + { + var functionType = ConvertToSwiftType(node.Children[0], isReference, name); + if (functionType == null) + return null; + var propType = functionType as SwiftPropertyType; + if (propType != null) + { + return propType.RecastAsStatic(); + } + var uncurriedFunction = functionType as SwiftUncurriedFunctionType; + if (uncurriedFunction != null) + { + var staticFunction = new SwiftStaticFunctionType(uncurriedFunction.Parameters, uncurriedFunction.ReturnType, + uncurriedFunction.IsReference, uncurriedFunction.CanThrow, + uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); + staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; + return staticFunction; + } + var baseFunctionType = functionType as SwiftBaseFunctionType; + if (baseFunctionType != null) + { + var staticFunction = new SwiftStaticFunctionType(baseFunctionType.Parameters, baseFunctionType.ReturnType, + baseFunctionType.IsReference, baseFunctionType.CanThrow, + null, baseFunctionType.Name); + staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; + staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; + return staticFunction; + } + var initializerType = functionType as SwiftInitializerType; + if (initializerType != null) + { + return initializerType; // this doesn't need a static recast? + } + throw new ArgumentOutOfRangeException($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType().Name}"); + } + + List ToLabelList(Node node) + { + var result = new List(); + foreach (var child in node.Children) + { + if (child.Kind == NodeKind.Identifier) + { + result.Add(new SwiftName(child.Text, false)); + } + else + { + result.Add(new SwiftName("_", false)); + } + } + return result; + } + + SwiftType ConvertToExistentialMetatype(Node node, bool isReference, SwiftName name) + { + var child = ConvertFirstChildToSwiftType(node, false, name); + var childType = child as SwiftProtocolListType; + if (child is SwiftClassType classType) + { + childType = new SwiftProtocolListType(classType, classType.IsReference, classType.Name); + } + if (childType == null) + return null; + return new SwiftExistentialMetaType(childType, isReference, null); + } + + SwiftType ConvertToMetatype(Node node, bool isReference, SwiftName name) + { + var child = ConvertFirstChildToSwiftType(node, false, name); + if (child is SwiftClassType cl) + { + return new SwiftMetaClassType(cl, isReference, name); + } + else if (child is SwiftGenericArgReferenceType classReference) + { + return new SwiftMetaClassType(classReference, isReference, name); + } + else + { + return null; + } + } + + SwiftType ConvertToGenericFunction(Node node, bool isReference, SwiftName name) + { + List args = GetGenericArguments(node); + var theFunction = ConvertToSwiftType(node.Children[1], isReference, name) as SwiftBaseFunctionType; + theFunction.GenericArguments.AddRange(args); + return theFunction; + } + + List GetGenericArguments(Node node) + { + var paramCountNode = node.Children[0].Children[0]; + if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) + throw new NotSupportedException($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString()}"); + + var paramCount = (int)paramCountNode.Index; + List args = new List(paramCount); + for (int i = 0; i < paramCount; i++) + { + args.Add(new GenericArgument(0, i)); + } + if (node.Children[0].Children.Count > 1) + { + var dependentGenericSignature = node.Children[0]; + // the 0th child is the number of generic parameters (see above) + for (int i = 1; i < dependentGenericSignature.Children.Count; i++) + { + var genericParamReference = ConvertToSwiftType(dependentGenericSignature.Children[i].Children[0], false, null) as SwiftGenericArgReferenceType; + var genericConstraintType = ConvertToSwiftType(dependentGenericSignature.Children[i].Children[1], false, null) as SwiftClassType; + MarkGenericConstraint(args, genericParamReference, genericConstraintType); + } + } + return args; + } + + static void MarkGenericConstraint(List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) + { + foreach (var genArg in args) + { + if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) + { + genArg.Constraints.Add(constraintType); + return; + } + } + } + + static SwiftBuiltInType TryAsBuiltInType(Node node, SwiftClassName className, bool isReference, SwiftName name) + { + switch (className.ToFullyQualifiedName()) + { + case "Swift.Int": + return new SwiftBuiltInType(CoreBuiltInType.Int, isReference, name); + case "Swift.Float": + return new SwiftBuiltInType(CoreBuiltInType.Float, isReference, name); + case "Swift.Bool": + return new SwiftBuiltInType(CoreBuiltInType.Bool, isReference, name); + case "Swift.UInt": + return new SwiftBuiltInType(CoreBuiltInType.UInt, isReference, name); + case "Swift.Double": + return new SwiftBuiltInType(CoreBuiltInType.Double, isReference, name); + default: + return null; + } + } + + static SwiftName BuildMemberNesting(Node node, List nestings, List names) + { + if (node.Children.Count > 0 && node.Children[0].Kind == NodeKind.Extension) + node = node.Children[0].Children[1]; + var nesting = MemberNesting.Class; + switch (node.Kind) + { + case NodeKind.Class: + break; + case NodeKind.Structure: + nesting = MemberNesting.Struct; + break; + case NodeKind.Enum: + nesting = MemberNesting.Enum; + break; + case NodeKind.Protocol: + nesting = MemberNesting.Protocol; + break; + case NodeKind.Module: + return new SwiftName(node.Text, false); + default: + throw new ArgumentOutOfRangeException(nameof(node), $"Expected a nominal type node kind but got {node.Kind.ToString()}"); + } + + var privatePublicName = PrivateNamePublicName(node.Children[1]); + var className = new SwiftName(privatePublicName.Item2, false); + SwiftName moduleName = null; + if (node.Children[0].Kind == NodeKind.Identifier || node.Children[0].Kind == NodeKind.Module) + { + moduleName = new SwiftName(node.Children[0].Text, false); + } + else + { + // recurse before adding names. + moduleName = BuildMemberNesting(node.Children[0], nestings, names); + } + names.Add(className); + nestings.Add(nesting); + return moduleName; + } + + + static Tuple PrivateNamePublicName(Node node) + { + if (node.Kind == NodeKind.Identifier) + return new Tuple(null, node.Text); + if (node.Kind == NodeKind.PrivateDeclName) + return new Tuple(node.Children[1].Text, node.Children[0].Text); + throw new ArgumentOutOfRangeException(nameof(node)); + } + + static SwiftType RenameFunctionParameters(SwiftType parameters, List labels) + { + if (labels.Count < 1) + throw new ArgumentOutOfRangeException(nameof(parameters)); + + var oldTuple = parameters as SwiftTupleType; + if (oldTuple == null) + throw new NotSupportedException($"{parameters} is not a tuple, it's a {parameters.GetType().Name}"); + + var newTuple = new SwiftTupleType(oldTuple.Contents.Select((elem, index) => RenamedCloneOf(elem, labels[index])), + oldTuple.IsReference, oldTuple.Name); + return newTuple; + } + + static SwiftType RenamedCloneOf(SwiftType st, SwiftName newName) + { + return st.RenamedCloneOf(newName.Name == "_" ? new SwiftName("", false) : newName); + } + + + // Swift does...weird...things with some of the core types from C. + // The mangler doesn't put in the appropriate swift module, but instead lumps them all + // together into the module __C. + // The mangler also puts a number of Foundation types into the namespace __ObjC. + // Why? No idea. + // I determined this list of __ObjC types by running the following command on all the Apple built libraries: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq + // which also includes a number of inner types which we don't care about (yet). + + // The command to do this for the __C namespace is: + // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq + + struct ModuleOrType + { + public ModuleOrType(string replacementModule) + { + ReplacementModule = replacementModule; + ReplacementFullClassName = null; + ReplacementNesting = null; + } + + public ModuleOrType(string replacementFullClassName, string replacementNesting) + { + ReplacementFullClassName = replacementFullClassName; + ReplacementNesting = replacementNesting; + ReplacementModule = null; + } + + public string ReplacementModule; + public string ReplacementFullClassName; + public string ReplacementNesting; + } + + + static Dictionary classNameOntoModuleOrType = new Dictionary { + { "AVError", new ModuleOrType ("AVFoundation") }, + { "AudioBuffer", new ModuleOrType ("AudioToolbox") }, + { "AudioBufferList", new ModuleOrType ("AudioToolbox") }, + { "CATransform3D", new ModuleOrType ("CoreAnimation") }, + { "CGAffineTransform", new ModuleOrType ("CoreGraphics") }, + { "CGColorSapceModel", new ModuleOrType ("CoreGraphics") }, + { "CGPoint", new ModuleOrType ("CoreGraphics") }, + { "CGRect", new ModuleOrType ("CoreGraphics") }, + { "CGSize", new ModuleOrType ("CoreGraphics") }, + { "CGVector", new ModuleOrType ("CoreGraphics") }, + { "CLError", new ModuleOrType ("CoreLocation") }, + { "CMTime", new ModuleOrType ("CoreMedia") }, + { "CMTimeFlags", new ModuleOrType ("CoreMedia") }, + { "CMTimeMapping", new ModuleOrType ("CoreMedia") }, + { "CMTimeRange", new ModuleOrType ("CoreMedia") }, + { "NSComparisonResult", new ModuleOrType ("Foundation") }, + { "NSDecimal", new ModuleOrType ("Foundation") }, + { "NSEnumerationOptions", new ModuleOrType ("Foundation") }, + { "NSKeyValueChange", new ModuleOrType ("Foundation") }, + { "NSKeyValueObservingOptions", new ModuleOrType ("Foundation") }, + { "NSFastEnumerationState", new ModuleOrType ("Foundation") }, + { "NSKeyValueChangeKey", new ModuleOrType ("Foundation") }, + { "NSBundle", new ModuleOrType ("Foundation.Bundle", "C") }, + { "NSURL", new ModuleOrType ("Foundation") }, + { "StringTransform", new ModuleOrType ("Foundation") }, + { "URLFileResourceType", new ModuleOrType ("Foundation") }, + { "URLResourceKey", new ModuleOrType ("Foundation") }, + { "URLThumbnailDictionaryItem", new ModuleOrType ("Foundation") }, + { "URLUbiquitousItemDownloadingStatus", new ModuleOrType ("Foundation") }, + { "URLUbiquitousSharedItemPermissions", new ModuleOrType ("Foundation") }, + { "URLUbiquitousSharedItemRole", new ModuleOrType ("Foundation") }, + { "MKCoordinateSpan", new ModuleOrType ("MapKit") }, + { "NSAnimationEffect", new ModuleOrType ("AppKit") }, + { "SCNGeometryPrimitiveType", new ModuleOrType ("SceneKit") }, + { "SCNVector3", new ModuleOrType ("SceneKit") }, + { "SCNVector4", new ModuleOrType ("SceneKit") }, + { "UIContentSizeCategory", new ModuleOrType ("UIKit") }, + { "UIControlState", new ModuleOrType ("UIKit.UIControl.State", "CV") }, + { "UIDeviceOrientation", new ModuleOrType ("UIKit") }, + { "UIEdgeInsets", new ModuleOrType ("UIKit") }, + { "UIInterfaceOrientation", new ModuleOrType ("UIKit") }, + { "UIControlEvents", new ModuleOrType ("UIKit.UIControl.Event", "CV") }, + { "UIViewAnimationOptions", new ModuleOrType ("UIKit.UIView.AnimationOptions", "CV") }, + { "UIOffset", new ModuleOrType ("UIKit") }, + { "UIBlurEffectStyle", new ModuleOrType ("UIKit.UIBlurEffect.Style","CV") }, + { "UIColor", new ModuleOrType ("UIKit")}, + { "UIImage", new ModuleOrType ("UIImage") }, + { "UITableViewStyle", new ModuleOrType ("UIKit.UITableView.Style", "CV") }, + { "UIView", new ModuleOrType ("UIKit") }, + { "UIViewControllerConditioning", new ModuleOrType ("UIKit") }, + { "UIVisualEffectView", new ModuleOrType ("UIKit") }, + { "CKError", new ModuleOrType ("CloudKit") }, + { "CNError", new ModuleOrType ("Contacts") }, + { "MTLSamplePosition", new ModuleOrType ("Metal") }, + { "XCUIKeyboardKey", new ModuleOrType ("XCTest") }, + { "BNNSActivationFunction", new ModuleOrType ("Accelerate") }, + { "BNNSDataType", new ModuleOrType ("Accelerate") }, + { "simd_double2x2", new ModuleOrType ("Accelerate") }, + { "simd_double2x3", new ModuleOrType ("Accelerate") }, + { "simd_double2x4", new ModuleOrType ("Accelerate") }, + { "simd_double3x2", new ModuleOrType ("Accelerate") }, + { "simd_double3x3", new ModuleOrType ("Accelerate") }, + { "simd_double3x4", new ModuleOrType ("Accelerate") }, + { "simd_double4x2", new ModuleOrType ("Accelerate") }, + { "simd_double4x3", new ModuleOrType ("Accelerate") }, + { "simd_double4x4", new ModuleOrType ("Accelerate") }, + { "simd_float2x2", new ModuleOrType ("Accelerate") }, + { "simd_float2x3", new ModuleOrType ("Accelerate") }, + { "simd_float2x4", new ModuleOrType ("Accelerate") }, + { "simd_float3x2", new ModuleOrType ("Accelerate") }, + { "simd_float3x3", new ModuleOrType ("Accelerate") }, + { "simd_float3x4", new ModuleOrType ("Accelerate") }, + { "simd_float4x2", new ModuleOrType ("Accelerate") }, + { "simd_float4x3", new ModuleOrType ("Accelerate") }, + { "simd_float4x4", new ModuleOrType ("Accelerate") }, + { "simd_quatd", new ModuleOrType ("Accelerate") }, + { "simd_quatf", new ModuleOrType ("Accelerate") }, + }; + + static SwiftClassName PatchClassName(SwiftName moduleName, List nesting, List nestingNames) + { + // surprise! + // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version + // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough + // bottleneck to alias it. + if (moduleName.Name == "__ObjC") + moduleName = new SwiftName("Foundation", false); + if (moduleName.Name != "__C" || nestingNames.Count != 1) + return new SwiftClassName(moduleName, nesting, nestingNames); + if (classNameOntoModuleOrType.ContainsKey(nestingNames[0].Name)) + { + var moduleOrType = classNameOntoModuleOrType[nestingNames[0].Name]; + if (moduleOrType.ReplacementModule == null) + { + return SwiftClassName.FromFullyQualifiedName(moduleOrType.ReplacementFullClassName, OperatorType.None, moduleOrType.ReplacementNesting); + } + else + { + moduleName = new SwiftName(moduleOrType.ReplacementModule, false); + } + } + return new SwiftClassName(moduleName, nesting, nestingNames); + } + + static Dictionary aliasNameOntoClassName = new Dictionary { + { "__C.NSOperatingSystemVersion", SwiftClassName.FromFullyQualifiedName ("Foundation.OperatingSystemVersion", OperatorType.None, 'V') }, + }; + + static SwiftClassName RemapTypeAlias(SwiftClassName className) + { + SwiftClassName newName = null; + return aliasNameOntoClassName.TryGetValue(className.ToFullyQualifiedName(true), out newName) ? newName : className; + } + } } diff --git a/src/SwiftReflector/Demangling/TLDefinition.cs b/src/SwiftReflector/Demangling/TLDefinition.cs index a1df9c656eca..64a5eaa03d1b 100644 --- a/src/SwiftReflector/Demangling/TLDefinition.cs +++ b/src/SwiftReflector/Demangling/TLDefinition.cs @@ -7,263 +7,289 @@ using System.Text; using SwiftRuntimeLibrary; -namespace SwiftReflector.Demangling { - public class TLDefinition { - protected TLDefinition (CoreCompoundType type, string mangledName, SwiftName module, ulong offset) - { - if (module == null) - throw new ArgumentNullException (nameof(module)); - Type = type; - Module = module; - MangledName = Exceptions.ThrowOnNull (mangledName, nameof(mangledName)); - Offset = offset; - } - - public CoreCompoundType Type { get; private set; } - public SwiftName Module { get; private set; } - public string MangledName { get; private set; } - public ulong Offset { get; private set; } - } - - public class TLModuleDescriptor : TLDefinition { - public TLModuleDescriptor (string mangledName, SwiftName module, ulong offset) - : base (CoreCompoundType.ModuleDescriptor, mangledName, module, offset) - { - } - } - - public class TLMetadataDescriptor : TLDefinition { - public TLMetadataDescriptor (SwiftType ofType, bool isBuiltIn, string mangledName, SwiftName module, ulong offset) - : base (CoreCompoundType.MetadataDescriptor, mangledName, module, offset) - { - OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); - IsBuiltIn = isBuiltIn; - } - public SwiftType OfType { get; private set; } - public bool IsBuiltIn { get; private set; } - } - - public class TLClassElem : TLDefinition { - protected TLClassElem (CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base (type, mangledName, module, offset) - { - Class = classType; - } - public SwiftClassType Class { get; private set; } - } - - public class TLThunk : TLClassElem { - public TLThunk (ThunkType thunkType, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base (CoreCompoundType.Thunk, mangledName, module, classType, offset) - { - Thunk = thunkType; - } - - public ThunkType Thunk { get; private set; } - } - - public class TLVariable : TLClassElem { - public TLVariable (string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn = null) - : this (CoreCompoundType.Variable, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) - { - } - - protected TLVariable (CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn) - : base (type, mangledName, module, classType, offset) - { - Name = Exceptions.ThrowOnNull (ident, nameof (ident)); - OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); - IsStatic = isStatic; - ExtensionOn = extensionOn; - } - public SwiftType OfType { get; private set; } - public SwiftType ExtensionOn { get; private set; } - public SwiftName Name { get; private set; } - public bool IsStatic { get; private set; } - } - - public class TLPropertyDescriptor : TLVariable { - public TLPropertyDescriptor (string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn = null) - : base (CoreCompoundType.PropertyDescriptor, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) - { - } - } - - public class TLUnsafeMutableAddressor : TLClassElem { - public TLUnsafeMutableAddressor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, ulong offset) - : base (CoreCompoundType.UnsafeMutableAddressor, mangledName, module, classType, offset) - { - Name = Exceptions.ThrowOnNull (ident, nameof (ident)); - OfType = Exceptions.ThrowOnNull (ofType, nameof (ofType)); - } - public SwiftType OfType { get; private set; } - public SwiftName Name { get; private set; } - } - - public class TLFieldOffset : TLClassElem { - - public TLFieldOffset (string mangledName, SwiftName module, SwiftClassType classType, bool direct, SwiftName ident, SwiftType type, ulong offset) - : base (CoreCompoundType.FieldOffset, mangledName, module, classType, offset) - { - IsDirect = direct; - Identifier = ident; - FieldType = type; - } - - public bool IsDirect { get; private set; } - - public SwiftName Identifier { get; private set; } - public SwiftType FieldType { get; private set; } - } - - public class TLFunction : TLClassElem { - public TLFunction (string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : this (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.Function) - { - } - - protected TLFunction (string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None, - CoreCompoundType type = CoreCompoundType.Function) - : base (type, mangledName, module, classType, offset) - { - Name = functionName; - Signature = signature; - Operator = oper; - } - - public SwiftName Name { get; private set; } - public SwiftBaseFunctionType Signature { get; private set; } - public OperatorType Operator { get; private set; } - - public bool IsTopLevelFunction { get { return Class == null || Class.ClassName.Nesting.Count == 0; } } - } - - public class TLMethodDescriptor : TLFunction { - public TLMethodDescriptor (string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : base (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) - { - } - } - - public class TLEnumCase : TLFunction { - public TLEnumCase (string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : base (mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) - { - } - } - - public class TLDefaultArgumentInitializer : TLDefinition { - public TLDefaultArgumentInitializer(string mangledName, SwiftName module, SwiftBaseFunctionType function, int index, ulong offset) - : base(CoreCompoundType.ArgumentInitializer, mangledName, module, offset) - { - Signature = Exceptions.ThrowOnNull (function, nameof (function)); - ArgumentIndex = index; - } - public SwiftBaseFunctionType Signature { get; private set; } - public int ArgumentIndex { get; private set; } - } - - public class TLLazyCacheVariable : TLClassElem { - public TLLazyCacheVariable (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.LazyCache, mangledName, module, cl, offset) - { - } - } - - public class TLDirectMetadata : TLClassElem { - public TLDirectMetadata (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) - { - } - } - - public class TLGenericMetadataPattern : TLClassElem { - public TLGenericMetadataPattern (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) - { - } - } - - public class TLMetaclass : TLClassElem { - public TLMetaclass (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.MetaClass, mangledName, module, cl, offset) - { - } - } - - public class TLNominalTypeDescriptor : TLClassElem { - public TLNominalTypeDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.NominalTypeDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLProtocolTypeDescriptor : TLClassElem { - public TLProtocolTypeDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.ProtocolTypeDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLProtocolConformanceDescriptor : TLDefinition { - public TLProtocolConformanceDescriptor (string mangledName, SwiftName module, SwiftType implementingType, - SwiftClassType forProtocol, ulong offset) - : base (CoreCompoundType.ProtocolConformanceDescriptor, mangledName, module, offset) - { - ImplementingType = Exceptions.ThrowOnNull (implementingType, nameof (implementingType)); - Protocol = forProtocol; - } - - public SwiftType ImplementingType { get; private set; } - public SwiftClassType Protocol { get; private set; } - } - - public class TLProtocolRequirementsBaseDescriptor : TLClassElem { - public TLProtocolRequirementsBaseDescriptor (string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base (CoreCompoundType.ProtocolRequirementsBaseDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLBaseConformanceDescriptor : TLClassElem { - public TLBaseConformanceDescriptor (string mangledName, SwiftName module, SwiftClassType protocol, SwiftClassType requirement, ulong offset) - : base (CoreCompoundType.BaseConformanceDescriptor, mangledName, module, protocol, offset) - { - ProtocolRequirement = Exceptions.ThrowOnNull (requirement, nameof (requirement)); - } - public SwiftClassType ProtocolRequirement { get; private set; } - } - - public class TLAssociatedTypeDescriptor : TLClassElem { - public TLAssociatedTypeDescriptor (string mangledName, SwiftName module, SwiftClassType protocol, SwiftName associatedTypeName, ulong offset) - : base (CoreCompoundType.AssociatedTypeDescriptor, mangledName, module, protocol, offset) - { - AssociatedTypeName = associatedTypeName; - } - - public SwiftName AssociatedTypeName { get; private set; } - } - - public class TLMetadataBaseOffset : TLClassElem { - public TLMetadataBaseOffset (string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base (CoreCompoundType.MetadataOffset, mangledName, module, classType, offset) - { - } - } - - public class TLMethodLookupFunction : TLClassElem { - public TLMethodLookupFunction (string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base (CoreCompoundType.MethodLookupFunction, mangledName, module, classType, offset) - { - - } - } +namespace SwiftReflector.Demangling +{ + public class TLDefinition + { + protected TLDefinition(CoreCompoundType type, string mangledName, SwiftName module, ulong offset) + { + if (module == null) + throw new ArgumentNullException(nameof(module)); + Type = type; + Module = module; + MangledName = Exceptions.ThrowOnNull(mangledName, nameof(mangledName)); + Offset = offset; + } + + public CoreCompoundType Type { get; private set; } + public SwiftName Module { get; private set; } + public string MangledName { get; private set; } + public ulong Offset { get; private set; } + } + + public class TLModuleDescriptor : TLDefinition + { + public TLModuleDescriptor(string mangledName, SwiftName module, ulong offset) + : base(CoreCompoundType.ModuleDescriptor, mangledName, module, offset) + { + } + } + + public class TLMetadataDescriptor : TLDefinition + { + public TLMetadataDescriptor(SwiftType ofType, bool isBuiltIn, string mangledName, SwiftName module, ulong offset) + : base(CoreCompoundType.MetadataDescriptor, mangledName, module, offset) + { + OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); + IsBuiltIn = isBuiltIn; + } + public SwiftType OfType { get; private set; } + public bool IsBuiltIn { get; private set; } + } + + public class TLClassElem : TLDefinition + { + protected TLClassElem(CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base(type, mangledName, module, offset) + { + Class = classType; + } + public SwiftClassType Class { get; private set; } + } + + public class TLThunk : TLClassElem + { + public TLThunk(ThunkType thunkType, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base(CoreCompoundType.Thunk, mangledName, module, classType, offset) + { + Thunk = thunkType; + } + + public ThunkType Thunk { get; private set; } + } + + public class TLVariable : TLClassElem + { + public TLVariable(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn = null) + : this(CoreCompoundType.Variable, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) + { + } + + protected TLVariable(CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn) + : base(type, mangledName, module, classType, offset) + { + Name = Exceptions.ThrowOnNull(ident, nameof(ident)); + OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); + IsStatic = isStatic; + ExtensionOn = extensionOn; + } + public SwiftType OfType { get; private set; } + public SwiftType ExtensionOn { get; private set; } + public SwiftName Name { get; private set; } + public bool IsStatic { get; private set; } + } + + public class TLPropertyDescriptor : TLVariable + { + public TLPropertyDescriptor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, + bool isStatic, ulong offset, SwiftType extensionOn = null) + : base(CoreCompoundType.PropertyDescriptor, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) + { + } + } + + public class TLUnsafeMutableAddressor : TLClassElem + { + public TLUnsafeMutableAddressor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, ulong offset) + : base(CoreCompoundType.UnsafeMutableAddressor, mangledName, module, classType, offset) + { + Name = Exceptions.ThrowOnNull(ident, nameof(ident)); + OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); + } + public SwiftType OfType { get; private set; } + public SwiftName Name { get; private set; } + } + + public class TLFieldOffset : TLClassElem + { + + public TLFieldOffset(string mangledName, SwiftName module, SwiftClassType classType, bool direct, SwiftName ident, SwiftType type, ulong offset) + : base(CoreCompoundType.FieldOffset, mangledName, module, classType, offset) + { + IsDirect = direct; + Identifier = ident; + FieldType = type; + } + + public bool IsDirect { get; private set; } + + public SwiftName Identifier { get; private set; } + public SwiftType FieldType { get; private set; } + } + + public class TLFunction : TLClassElem + { + public TLFunction(string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : this(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.Function) + { + } + + protected TLFunction(string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None, + CoreCompoundType type = CoreCompoundType.Function) + : base(type, mangledName, module, classType, offset) + { + Name = functionName; + Signature = signature; + Operator = oper; + } + + public SwiftName Name { get; private set; } + public SwiftBaseFunctionType Signature { get; private set; } + public OperatorType Operator { get; private set; } + + public bool IsTopLevelFunction { get { return Class == null || Class.ClassName.Nesting.Count == 0; } } + } + + public class TLMethodDescriptor : TLFunction + { + public TLMethodDescriptor(string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : base(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) + { + } + } + + public class TLEnumCase : TLFunction + { + public TLEnumCase(string mangledName, SwiftName module, SwiftName functionName, + SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) + : base(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) + { + } + } + + public class TLDefaultArgumentInitializer : TLDefinition + { + public TLDefaultArgumentInitializer(string mangledName, SwiftName module, SwiftBaseFunctionType function, int index, ulong offset) + : base(CoreCompoundType.ArgumentInitializer, mangledName, module, offset) + { + Signature = Exceptions.ThrowOnNull(function, nameof(function)); + ArgumentIndex = index; + } + public SwiftBaseFunctionType Signature { get; private set; } + public int ArgumentIndex { get; private set; } + } + + public class TLLazyCacheVariable : TLClassElem + { + public TLLazyCacheVariable(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.LazyCache, mangledName, module, cl, offset) + { + } + } + + public class TLDirectMetadata : TLClassElem + { + public TLDirectMetadata(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) + { + } + } + + public class TLGenericMetadataPattern : TLClassElem + { + public TLGenericMetadataPattern(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) + { + } + } + + public class TLMetaclass : TLClassElem + { + public TLMetaclass(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.MetaClass, mangledName, module, cl, offset) + { + } + } + + public class TLNominalTypeDescriptor : TLClassElem + { + public TLNominalTypeDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.NominalTypeDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLProtocolTypeDescriptor : TLClassElem + { + public TLProtocolTypeDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.ProtocolTypeDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLProtocolConformanceDescriptor : TLDefinition + { + public TLProtocolConformanceDescriptor(string mangledName, SwiftName module, SwiftType implementingType, + SwiftClassType forProtocol, ulong offset) + : base(CoreCompoundType.ProtocolConformanceDescriptor, mangledName, module, offset) + { + ImplementingType = Exceptions.ThrowOnNull(implementingType, nameof(implementingType)); + Protocol = forProtocol; + } + + public SwiftType ImplementingType { get; private set; } + public SwiftClassType Protocol { get; private set; } + } + + public class TLProtocolRequirementsBaseDescriptor : TLClassElem + { + public TLProtocolRequirementsBaseDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) + : base(CoreCompoundType.ProtocolRequirementsBaseDescriptor, mangledName, module, cl, offset) + { + } + } + + public class TLBaseConformanceDescriptor : TLClassElem + { + public TLBaseConformanceDescriptor(string mangledName, SwiftName module, SwiftClassType protocol, SwiftClassType requirement, ulong offset) + : base(CoreCompoundType.BaseConformanceDescriptor, mangledName, module, protocol, offset) + { + ProtocolRequirement = Exceptions.ThrowOnNull(requirement, nameof(requirement)); + } + public SwiftClassType ProtocolRequirement { get; private set; } + } + + public class TLAssociatedTypeDescriptor : TLClassElem + { + public TLAssociatedTypeDescriptor(string mangledName, SwiftName module, SwiftClassType protocol, SwiftName associatedTypeName, ulong offset) + : base(CoreCompoundType.AssociatedTypeDescriptor, mangledName, module, protocol, offset) + { + AssociatedTypeName = associatedTypeName; + } + + public SwiftName AssociatedTypeName { get; private set; } + } + + public class TLMetadataBaseOffset : TLClassElem + { + public TLMetadataBaseOffset(string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base(CoreCompoundType.MetadataOffset, mangledName, module, classType, offset) + { + } + } + + public class TLMethodLookupFunction : TLClassElem + { + public TLMethodLookupFunction(string mangledName, SwiftName module, SwiftClassType classType, ulong offset) + : base(CoreCompoundType.MethodLookupFunction, mangledName, module, classType, offset) + { + + } + } } diff --git a/src/SwiftReflector/Enums.cs b/src/SwiftReflector/Enums.cs index 092e314194e0..7af4cc480e45 100644 --- a/src/SwiftReflector/Enums.cs +++ b/src/SwiftReflector/Enums.cs @@ -3,180 +3,199 @@ using System; -namespace SwiftReflector { - public enum CoreCompoundType { - ModuleName, - Function, - Class, - Struct, - Array, - Scalar, - Tuple, - BoundGeneric, - MetaClass, - LazyCache, - DirectMetadata, - NominalTypeDescriptor, - Variable, - Thunk, - ProtocolList, - ProtocolTypeDescriptor, - UnboundGeneric, - GenericReference, - FieldOffset, - ArgumentInitializer, - UnsafeMutableAddressor, - ProtocolConformanceDescriptor, - MethodDescriptor, - ModuleDescriptor, - PropertyDescriptor, - MetadataDescriptor, - ProtocolRequirementsBaseDescriptor, - BaseConformanceDescriptor, - AssociatedTypeDescriptor, - MetadataOffset, - MethodLookupFunction, - } - - public enum CoreBuiltInType { - Int, - UInt, - Double, - Float, - Bool, - } - - public enum EntityType { - None, - Class, - Struct, - Enum, - TrivialEnum, - Scalar, - Protocol, - Tuple, - Closure, - ProtocolList, - DynamicSelf, - } - - public enum MemberNesting { - Class, - Struct, - Enum, - Protocol, - } - - public enum MemberType { - Function, - UncurriedFunction, - Allocator, - Constructor, - Destructor, - Deallocator, - Getter, - Setter, - Materializer, - ExplicitClosure, - Addressor, - CFunction, - Initializer, - } - - public enum PropertyType { - Getter, - Setter, - Materializer, - DidSet, - WillSet, - ModifyAccessor, - } - - public enum AddressorType { - OwningMutable, - NativeOwningMutable, - NativePinningMutable, - UnsafeMutable, - Owning, - NativeOwning, - NativePinning, - Unsafe, - } - - public enum InitializerType { - Variable, - } - - public enum ThunkType { - Reabstraction, - ReabstractionHelper, - ProtocolWitness, - Curry, - } - - public enum OperatorType { - None, - Prefix, - Postfix, - Infix, - Unknown, - } - - public enum WitnessType { - Class, - Value, - Protocol, - ProtocolAccessor, - } - - public enum PlatformName { - None, // desktop managed executable - macOS, // Xamarin.Mac app - iOS, - watchOS, - tvOS, - } - - public enum SwiftTypeAttribute { - ObjC, - NonObjC, - Dynamic, - ImplFunction, - DirectMethodReference, - } - - public enum ReflectionStrategy { - None, - [Obsolete ("Compiler reflection is no longer supported.", true)] - Compiler, - Parser, - } - - public enum TargetCpu { - Arm64, - Armv7, - Armv7s, - Arm7vk, - Arm64e, - Arm64_32, - I386, - X86_64, - } - - public enum TargetManufacturer { - Apple, - } - - public enum TargetEnvironment { - Device, - Simulator, - } - - public enum TargetRepresentationKind { - None, - Library, - Framework, - XCFramework, - } +namespace SwiftReflector +{ + public enum CoreCompoundType + { + ModuleName, + Function, + Class, + Struct, + Array, + Scalar, + Tuple, + BoundGeneric, + MetaClass, + LazyCache, + DirectMetadata, + NominalTypeDescriptor, + Variable, + Thunk, + ProtocolList, + ProtocolTypeDescriptor, + UnboundGeneric, + GenericReference, + FieldOffset, + ArgumentInitializer, + UnsafeMutableAddressor, + ProtocolConformanceDescriptor, + MethodDescriptor, + ModuleDescriptor, + PropertyDescriptor, + MetadataDescriptor, + ProtocolRequirementsBaseDescriptor, + BaseConformanceDescriptor, + AssociatedTypeDescriptor, + MetadataOffset, + MethodLookupFunction, + } + + public enum CoreBuiltInType + { + Int, + UInt, + Double, + Float, + Bool, + } + + public enum EntityType + { + None, + Class, + Struct, + Enum, + TrivialEnum, + Scalar, + Protocol, + Tuple, + Closure, + ProtocolList, + DynamicSelf, + } + + public enum MemberNesting + { + Class, + Struct, + Enum, + Protocol, + } + + public enum MemberType + { + Function, + UncurriedFunction, + Allocator, + Constructor, + Destructor, + Deallocator, + Getter, + Setter, + Materializer, + ExplicitClosure, + Addressor, + CFunction, + Initializer, + } + + public enum PropertyType + { + Getter, + Setter, + Materializer, + DidSet, + WillSet, + ModifyAccessor, + } + + public enum AddressorType + { + OwningMutable, + NativeOwningMutable, + NativePinningMutable, + UnsafeMutable, + Owning, + NativeOwning, + NativePinning, + Unsafe, + } + + public enum InitializerType + { + Variable, + } + + public enum ThunkType + { + Reabstraction, + ReabstractionHelper, + ProtocolWitness, + Curry, + } + + public enum OperatorType + { + None, + Prefix, + Postfix, + Infix, + Unknown, + } + + public enum WitnessType + { + Class, + Value, + Protocol, + ProtocolAccessor, + } + + public enum PlatformName + { + None, // desktop managed executable + macOS, // Xamarin.Mac app + iOS, + watchOS, + tvOS, + } + + public enum SwiftTypeAttribute + { + ObjC, + NonObjC, + Dynamic, + ImplFunction, + DirectMethodReference, + } + + public enum ReflectionStrategy + { + None, + [Obsolete("Compiler reflection is no longer supported.", true)] + Compiler, + Parser, + } + + public enum TargetCpu + { + Arm64, + Armv7, + Armv7s, + Arm7vk, + Arm64e, + Arm64_32, + I386, + X86_64, + } + + public enum TargetManufacturer + { + Apple, + } + + public enum TargetEnvironment + { + Device, + Simulator, + } + + public enum TargetRepresentationKind + { + None, + Library, + Framework, + XCFramework, + } } diff --git a/src/SwiftReflector/ErrorHandling.cs b/src/SwiftReflector/ErrorHandling.cs index 88869faf5692..e7e420d5e72c 100644 --- a/src/SwiftReflector/ErrorHandling.cs +++ b/src/SwiftReflector/ErrorHandling.cs @@ -8,97 +8,118 @@ using System.Linq; using System.Runtime.ExceptionServices; -namespace SwiftReflector { - public class ErrorHandling { - object messagesLock = new object (); - List messages; - - public ErrorHandling () - { - messages = new List (); - SkippedTypes = new List (); - SkippedFunctions = new List (); - } - - public IEnumerable Messages { - get { return messages; } - } - - public IEnumerable Errors { - get { return messages.Where ((v) => !v.IsWarning); } - } - - public IEnumerable Warnings { - get { return messages.Where ((v) => v.IsWarning); } - } - - public List SkippedTypes { get; private set; } - public List SkippedFunctions { get; private set; } - - public void Add (ErrorHandling eh) - { - lock (messagesLock) { - lock (eh.messagesLock) { - messages.AddRange (eh.messages); - } - } - } - - public void Add (params ReflectorError [] errors) - { - lock (messagesLock) { - messages.AddRange (errors); - } - } - - public void Add (Exception exception) - { - lock (messagesLock) { +namespace SwiftReflector +{ + public class ErrorHandling + { + object messagesLock = new object(); + List messages; + + public ErrorHandling() + { + messages = new List(); + SkippedTypes = new List(); + SkippedFunctions = new List(); + } + + public IEnumerable Messages + { + get { return messages; } + } + + public IEnumerable Errors + { + get { return messages.Where((v) => !v.IsWarning); } + } + + public IEnumerable Warnings + { + get { return messages.Where((v) => v.IsWarning); } + } + + public List SkippedTypes { get; private set; } + public List SkippedFunctions { get; private set; } + + public void Add(ErrorHandling eh) + { + lock (messagesLock) + { + lock (eh.messagesLock) + { + messages.AddRange(eh.messages); + } + } + } + + public void Add(params ReflectorError[] errors) + { + lock (messagesLock) + { + messages.AddRange(errors); + } + } + + public void Add(Exception exception) + { + lock (messagesLock) + { #if CRASH_ON_EXCEPTION ExceptionDispatchInfo.Capture (exception).Throw (); #else - messages.Add (new ReflectorError (exception)); + messages.Add(new ReflectorError(exception)); #endif - } - } - - public bool AnyMessages { - get { - lock (messagesLock) { - return messages.Count > 0; - } - } - } - - public bool AnyErrors { - get { - lock (messagesLock) { - return messages.Any ((v) => !v.IsWarning); - } - } - } - - public int WarningCount { - get { - lock (messagesLock) { - return messages.Count ((v) => v.IsWarning); - } - } - } - - public int ErrorCount { - get { - lock (messagesLock) { - return messages.Count ((v) => !v.IsWarning); - } - } - } - - public int Show (int verbosity) - { - // ErrorHelper.Verbosity = verbosity; - // return ErrorHelper.Show (messages.Select ((v) => v.Exception)); - return verbosity; - } - } + } + } + + public bool AnyMessages + { + get + { + lock (messagesLock) + { + return messages.Count > 0; + } + } + } + + public bool AnyErrors + { + get + { + lock (messagesLock) + { + return messages.Any((v) => !v.IsWarning); + } + } + } + + public int WarningCount + { + get + { + lock (messagesLock) + { + return messages.Count((v) => v.IsWarning); + } + } + } + + public int ErrorCount + { + get + { + lock (messagesLock) + { + return messages.Count((v) => !v.IsWarning); + } + } + } + + public int Show(int verbosity) + { + // ErrorHelper.Verbosity = verbosity; + // return ErrorHelper.Show (messages.Select ((v) => v.Exception)); + return verbosity; + } + } } diff --git a/src/SwiftReflector/ExceptionTools/ErrorHelper.cs b/src/SwiftReflector/ExceptionTools/ErrorHelper.cs index de1637ae3844..61c57765874e 100644 --- a/src/SwiftReflector/ExceptionTools/ErrorHelper.cs +++ b/src/SwiftReflector/ExceptionTools/ErrorHelper.cs @@ -5,173 +5,187 @@ using System.Collections.Generic; using ProductException = SwiftReflector.ExceptionTools.RuntimeException; -namespace SwiftReflector.ExceptionTools { - static class ErrorHelper { - public enum WarningLevel - { - Error = -1, - Warning = 0, - Disable = 1, - } - public const string Prefix = "BT"; - static Dictionary warning_levels; - public static int Verbosity { get; set; } - - public static WarningLevel GetWarningLevel (int code) - { - WarningLevel level; - - if (warning_levels == null) - return WarningLevel.Warning; - - // code -1: all codes - if (warning_levels.TryGetValue (-1, out level)) - return level; - - if (warning_levels.TryGetValue (code, out level)) - return level; - - return WarningLevel.Warning; - } - - public static void SetWarningLevel (WarningLevel level, int? code = null /* if null, apply to all warnings */) - { - if (warning_levels == null) - warning_levels = new Dictionary (); - if (code.HasValue) { - warning_levels [code.Value] = level; - } else { - warning_levels [-1] = level; // code -1: all codes. - } - } - - public static ProductException CreateError (int code, string message, params object[] args) - { - return new ProductException (code, true, message, args); - } - - public static ProductException CreateError (int code, Exception innerException, string message, params object[] args) - { - return new ProductException (code, true, innerException, message, args); - } - - public static ProductException CreateWarning (int code, string message, params object[] args) - { - return new ProductException (code, false, message, args); - } - - public static ProductException CreateWarning (int code, Exception innerException, string message, params object [] args) - { - return new ProductException (code, false, innerException, message, args); - } - - public static void Error (int code, Exception innerException, string message, params object[] args) - { - throw new ProductException (code, true, innerException, message, args); - } - - public static void Error (int code, string message, params object[] args) - { - throw new ProductException (code, true, message, args); - } - - public static void Warning (int code, string message, params object[] args) - { - Show (new ProductException (code, false, message, args)); - } - - public static void Warning (int code, Exception innerException, string message, params object[] args) - { - Show (new ProductException (code, false, innerException, message, args)); - } - - public static int Show (IEnumerable list) - { - List exceptions = new List (); - bool error = false; - - foreach (var e in list) - CollectExceptions (e, exceptions); - - foreach (var ex in exceptions) - error |= ShowInternal (ex); - - return error ? 1 : 0; - } - - static public int Show (Exception e) - { - List exceptions = new List (); - bool error = false; - - CollectExceptions (e, exceptions); - - foreach (var ex in exceptions) - error |= ShowInternal (ex); - - return error ? 1 : 0; - } - - static void Exit (int exitCode) - { - Environment.Exit (exitCode); - } - - static void CollectExceptions (Exception ex, List exceptions) - { - AggregateException ae = ex as AggregateException; - - if (ae != null && ae.InnerExceptions.Count > 0) { - foreach (var ie in ae.InnerExceptions) - CollectExceptions (ie, exceptions); - } else { - exceptions.Add (ex); - } - } - - static bool ShowInternal (Exception e) - { - ProductException mte = (e as ProductException); - bool error = true; - - if (mte != null) { - error = mte.Error; - - if (!error && GetWarningLevel (mte.Code) == WarningLevel.Disable) - return false; // This is an ignored warning. - - Console.Error.WriteLine (mte.ToString ()); - - if (Verbosity > 1) - ShowInner (e); - - if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) - Console.Error.WriteLine (e.StackTrace); - } else { - Console.Error.WriteLine (e.ToString ()); - if (Verbosity > 1) - ShowInner (e); - if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) - Console.Error.WriteLine (e.StackTrace); - } - - return error; - } - - static void ShowInner (Exception e) - { - Exception ie = e.InnerException; - if (ie == null) - return; - - if (Verbosity > 3) { - Console.Error.WriteLine ("--- inner exception"); - Console.Error.WriteLine (ie); - Console.Error.WriteLine ("---"); - } else { - Console.Error.WriteLine ("\t{0}", ie.Message); - } - ShowInner (ie); - } - } +namespace SwiftReflector.ExceptionTools +{ + static class ErrorHelper + { + public enum WarningLevel + { + Error = -1, + Warning = 0, + Disable = 1, + } + public const string Prefix = "BT"; + static Dictionary warning_levels; + public static int Verbosity { get; set; } + + public static WarningLevel GetWarningLevel(int code) + { + WarningLevel level; + + if (warning_levels == null) + return WarningLevel.Warning; + + // code -1: all codes + if (warning_levels.TryGetValue(-1, out level)) + return level; + + if (warning_levels.TryGetValue(code, out level)) + return level; + + return WarningLevel.Warning; + } + + public static void SetWarningLevel(WarningLevel level, int? code = null /* if null, apply to all warnings */) + { + if (warning_levels == null) + warning_levels = new Dictionary(); + if (code.HasValue) + { + warning_levels[code.Value] = level; + } + else + { + warning_levels[-1] = level; // code -1: all codes. + } + } + + public static ProductException CreateError(int code, string message, params object[] args) + { + return new ProductException(code, true, message, args); + } + + public static ProductException CreateError(int code, Exception innerException, string message, params object[] args) + { + return new ProductException(code, true, innerException, message, args); + } + + public static ProductException CreateWarning(int code, string message, params object[] args) + { + return new ProductException(code, false, message, args); + } + + public static ProductException CreateWarning(int code, Exception innerException, string message, params object[] args) + { + return new ProductException(code, false, innerException, message, args); + } + + public static void Error(int code, Exception innerException, string message, params object[] args) + { + throw new ProductException(code, true, innerException, message, args); + } + + public static void Error(int code, string message, params object[] args) + { + throw new ProductException(code, true, message, args); + } + + public static void Warning(int code, string message, params object[] args) + { + Show(new ProductException(code, false, message, args)); + } + + public static void Warning(int code, Exception innerException, string message, params object[] args) + { + Show(new ProductException(code, false, innerException, message, args)); + } + + public static int Show(IEnumerable list) + { + List exceptions = new List(); + bool error = false; + + foreach (var e in list) + CollectExceptions(e, exceptions); + + foreach (var ex in exceptions) + error |= ShowInternal(ex); + + return error ? 1 : 0; + } + + static public int Show(Exception e) + { + List exceptions = new List(); + bool error = false; + + CollectExceptions(e, exceptions); + + foreach (var ex in exceptions) + error |= ShowInternal(ex); + + return error ? 1 : 0; + } + + static void Exit(int exitCode) + { + Environment.Exit(exitCode); + } + + static void CollectExceptions(Exception ex, List exceptions) + { + AggregateException ae = ex as AggregateException; + + if (ae != null && ae.InnerExceptions.Count > 0) + { + foreach (var ie in ae.InnerExceptions) + CollectExceptions(ie, exceptions); + } + else + { + exceptions.Add(ex); + } + } + + static bool ShowInternal(Exception e) + { + ProductException mte = (e as ProductException); + bool error = true; + + if (mte != null) + { + error = mte.Error; + + if (!error && GetWarningLevel(mte.Code) == WarningLevel.Disable) + return false; // This is an ignored warning. + + Console.Error.WriteLine(mte.ToString()); + + if (Verbosity > 1) + ShowInner(e); + + if (Verbosity > 2 && !string.IsNullOrEmpty(e.StackTrace)) + Console.Error.WriteLine(e.StackTrace); + } + else + { + Console.Error.WriteLine(e.ToString()); + if (Verbosity > 1) + ShowInner(e); + if (Verbosity > 2 && !string.IsNullOrEmpty(e.StackTrace)) + Console.Error.WriteLine(e.StackTrace); + } + + return error; + } + + static void ShowInner(Exception e) + { + Exception ie = e.InnerException; + if (ie == null) + return; + + if (Verbosity > 3) + { + Console.Error.WriteLine("--- inner exception"); + Console.Error.WriteLine(ie); + Console.Error.WriteLine("---"); + } + else + { + Console.Error.WriteLine("\t{0}", ie.Message); + } + ShowInner(ie); + } + } } diff --git a/src/SwiftReflector/ExceptionTools/RuntimeException.cs b/src/SwiftReflector/ExceptionTools/RuntimeException.cs index 6b9a62e31f3b..a60ff34997a1 100644 --- a/src/SwiftReflector/ExceptionTools/RuntimeException.cs +++ b/src/SwiftReflector/ExceptionTools/RuntimeException.cs @@ -4,55 +4,59 @@ using System; using System.Collections.Generic; -namespace SwiftReflector.ExceptionTools { - - public class RuntimeException : Exception { - // Store the stack trace when this exception was created, and return - // it if the base class doesn't have a stack trace (which would happen - // if this exception was never thrown). - string stack_trace; - - public RuntimeException (string message, params object [] args) - : base (string.Format (message, args)) - { - stack_trace = new System.Diagnostics.StackTrace (true).ToString (); - } - - public RuntimeException (int code, string message, params object [] args) : - this (code, false, message, args) - { - } - - public RuntimeException (int code, bool error, string message, params object [] args) : - this (code, error, null, message, args) - { - } - - public RuntimeException (int code, bool error, Exception innerException, string message, params object [] args) : - base (String.Format (message, args), innerException) - { - stack_trace = new System.Diagnostics.StackTrace (true).ToString (); - Code = code; - Error = error; - } - - public int Code { get; private set; } - - public bool Error { get; private set; } - - // http://blogs.msdn.com/b/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx - public override string ToString () - { - return String.Format ("{0} {1:0000}: {2}", Error ? "error" : "warning", Code, Message); - } - - public override string StackTrace { - get { - var thrownTrace = base.StackTrace; - if (string.IsNullOrEmpty (thrownTrace)) - return stack_trace; - return thrownTrace; - } - } - } +namespace SwiftReflector.ExceptionTools +{ + + public class RuntimeException : Exception + { + // Store the stack trace when this exception was created, and return + // it if the base class doesn't have a stack trace (which would happen + // if this exception was never thrown). + string stack_trace; + + public RuntimeException(string message, params object[] args) + : base(string.Format(message, args)) + { + stack_trace = new System.Diagnostics.StackTrace(true).ToString(); + } + + public RuntimeException(int code, string message, params object[] args) : + this(code, false, message, args) + { + } + + public RuntimeException(int code, bool error, string message, params object[] args) : + this(code, error, null, message, args) + { + } + + public RuntimeException(int code, bool error, Exception innerException, string message, params object[] args) : + base(String.Format(message, args), innerException) + { + stack_trace = new System.Diagnostics.StackTrace(true).ToString(); + Code = code; + Error = error; + } + + public int Code { get; private set; } + + public bool Error { get; private set; } + + // http://blogs.msdn.com/b/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx + public override string ToString() + { + return String.Format("{0} {1:0000}: {2}", Error ? "error" : "warning", Code, Message); + } + + public override string StackTrace + { + get + { + var thrownTrace = base.StackTrace; + if (string.IsNullOrEmpty(thrownTrace)) + return stack_trace; + return thrownTrace; + } + } + } } diff --git a/src/SwiftReflector/Extensions.cs b/src/SwiftReflector/Extensions.cs index efa659614982..d5b7fc8b97ff 100644 --- a/src/SwiftReflector/Extensions.cs +++ b/src/SwiftReflector/Extensions.cs @@ -9,230 +9,236 @@ using SyntaxDynamo; using System.Collections; -namespace SwiftReflector { - public static class Extensions { - public static IEnumerable Yield (this T elem) - { - yield return elem; - } - - public static bool IsSwiftEntryPoint (this NListEntry entry) - { - return !String.IsNullOrEmpty (entry.str) && (entry.str.StartsWith ("__T", StringComparison.Ordinal) || - entry.str.StartsWith ("_$s", StringComparison.Ordinal) || entry.str.StartsWith ("_$S", StringComparison.Ordinal)); - } - - public static IEnumerable SwiftEntryPoints (this IEnumerable entries) - { - return entries.Where (IsSwiftEntryPoint); - } - - public static IEnumerable SwiftEntryPointNames (this IEnumerable entries) - { - return entries.SwiftEntryPoints ().Select (nle => nle.str); - } - - public static string DePunyCode (this string s) - { - return PunyCode.PunySingleton.Decode (s); - } - - public static Tuple SplitModuleFromName (this string s) - { - int dotIndex = s.IndexOf ('.'); - if (dotIndex < 0) - return new Tuple (null, s); - if (dotIndex == 0) - return new Tuple (null, s.Substring (1)); - return new Tuple (s.Substring (0, dotIndex), s.Substring (dotIndex + 1)); - } - - public static string ModuleFromName (this string s) - { - return s.SplitModuleFromName ().Item1; - } - - public static string NameWithoutModule (this string s) - { - return s.SplitModuleFromName ().Item2; - } - - public static string [] DecomposeClangTarget (this string s) - { - if (String.IsNullOrEmpty (s)) - throw new ArgumentNullException (nameof (s)); - string [] parts = s.Split ('-'); - // catalyst adds cpu-platform-ios-macabi - if (parts.Length != 3 && parts.Length != 4) - throw new ArgumentOutOfRangeException (nameof (s), s, "target should be in the form cpu-platform-os"); - - var shortestIndex = parts.Length == 3 ? - IndexOfMin (parts [0].Length, parts [1].Length, parts [2].Length) : - IndexOfMin (parts [0].Length, parts [1].Length, parts [2].Length, parts [3].Length); - - if (parts [shortestIndex].Length == 0) { - var missingPart = new string [] { "cpu", "platform", "os", "os" } [shortestIndex]; - throw new ArgumentException ($"target (cpu-platform-os) has an empty {missingPart} component."); - } - - return parts; - } - - static int IndexOfMin (params int [] values) - { - var min = values.Min (); - return Array.IndexOf (values, min); - } - - public static string ClangTargetCpu (this string s) - { - return s.DecomposeClangTarget () [0]; - } - - public static string ClangTargetPlatform (this string s) - { - return s.DecomposeClangTarget () [1]; - } - - public static string ClangTargetOS (this string s) - { - var clangTarget = s.DecomposeClangTarget (); - if (clangTarget.Length == 3) - return clangTarget [2]; - if (clangTarget.Length == 4) - return $"{clangTarget [2]}-{clangTarget [3]}"; - throw new ArgumentException ($"Clang target {s} should have 3 or 4 parts", nameof (s)); - } - - static int IndexOfFirstDigit (string s) - { - int index = 0; - foreach (char c in s) { - if (Char.IsDigit (c)) - return index; - index++; - } - return -1; - } - - public static string ClangOSNoVersion (this string s) - { - var clangTarget = s.DecomposeClangTarget (); - var os = clangTarget [2]; - return OSNoVersion (os); - } - - static string OSNoVersion (string s) - { - var firstNumber = IndexOfFirstDigit (s); - return firstNumber < 0 ? s : s.Substring (0, firstNumber); - } - - public static string ClangOSVersion (this string s) - { - var clangTarget = s.DecomposeClangTarget (); - var os = clangTarget [2]; - var firstNumber = IndexOfFirstDigit (os); - return os.Substring (firstNumber); - } - - public static string MinimumClangVersion (IEnumerable targets) - { - var osVersion = targets.Select (t => new Version (ClangOSVersion (t))).Min (); - return osVersion.ToString (); - } - - public static string ClangSubstituteOSVersion (this string s, string replacementVersion) - { - var clangTarget = s.DecomposeClangTarget (); - var os = OSNoVersion (clangTarget [2]) + replacementVersion; - clangTarget [2] = os; - return clangTarget.InterleaveStrings ("-"); - } - - public static bool ClangTargetIsSimulator (this string s) - { - var parts = s.DecomposeClangTarget (); - if (parts.Length == 4 && parts [3] == "simulator") - return true; - var osNoVersion = OSNoVersion (parts [2]); - if (osNoVersion == "macosx") - return false; - var cpu = parts [0]; - return cpu == "i386" || cpu == "x86-64"; - } - - public static void Merge (this HashSet to, IEnumerable from) - { - Exceptions.ThrowOnNull (from, nameof (from)); - foreach (T val in from) - to.Add (val); - } - - public static void DisposeAll (this IEnumerable coll) where T : IDisposable - { - Exceptions.ThrowOnNull (coll, nameof (coll)); - foreach (T obj in coll) { - if ((IDisposable)obj != null) - obj.Dispose (); - } - } - - public static string InterleaveStrings (this IEnumerable elements, string separator, bool includeSepFirst = false) - { - StringBuilder sb = new StringBuilder (); - foreach (string s in elements.Interleave (separator, includeSepFirst)) - sb.Append (s); - return sb.ToString (); - } - - public static string InterleaveCommas (this IEnumerable elements) - { - return elements.InterleaveStrings (", "); - } - - public static bool IsSwift3(this Version vers) - { - return vers.Major == 3; - } - - public static bool IsSwift4 (this Version vers) - { - return vers.Major == 4; - } - - public static int ErrorCount(this List errors) - { - var count = 0; - foreach (var error in errors) { - if (!error.IsWarning) - ++count; - } - return count; - } - - public static int WarningCount(this List errors) - { - return errors.Count - errors.ErrorCount (); - } - - public static List CloneAndPrepend(this List source, T item) - { - var result = new List (source.Count + 1); - result.Add (item); - result.AddRange (source); - return result; - } - - public static T[] And (this T[] first, T[] second) - { - Exceptions.ThrowOnNull (first, nameof (first)); - Exceptions.ThrowOnNull (second, nameof (second)); - var result = new T [first.Length + second.Length]; - Array.Copy (first, result, first.Length); - Array.Copy (second, 0, result, first.Length, second.Length); - return result; - } - } +namespace SwiftReflector +{ + public static class Extensions + { + public static IEnumerable Yield(this T elem) + { + yield return elem; + } + + public static bool IsSwiftEntryPoint(this NListEntry entry) + { + return !String.IsNullOrEmpty(entry.str) && (entry.str.StartsWith("__T", StringComparison.Ordinal) || + entry.str.StartsWith("_$s", StringComparison.Ordinal) || entry.str.StartsWith("_$S", StringComparison.Ordinal)); + } + + public static IEnumerable SwiftEntryPoints(this IEnumerable entries) + { + return entries.Where(IsSwiftEntryPoint); + } + + public static IEnumerable SwiftEntryPointNames(this IEnumerable entries) + { + return entries.SwiftEntryPoints().Select(nle => nle.str); + } + + public static string DePunyCode(this string s) + { + return PunyCode.PunySingleton.Decode(s); + } + + public static Tuple SplitModuleFromName(this string s) + { + int dotIndex = s.IndexOf('.'); + if (dotIndex < 0) + return new Tuple(null, s); + if (dotIndex == 0) + return new Tuple(null, s.Substring(1)); + return new Tuple(s.Substring(0, dotIndex), s.Substring(dotIndex + 1)); + } + + public static string ModuleFromName(this string s) + { + return s.SplitModuleFromName().Item1; + } + + public static string NameWithoutModule(this string s) + { + return s.SplitModuleFromName().Item2; + } + + public static string[] DecomposeClangTarget(this string s) + { + if (String.IsNullOrEmpty(s)) + throw new ArgumentNullException(nameof(s)); + string[] parts = s.Split('-'); + // catalyst adds cpu-platform-ios-macabi + if (parts.Length != 3 && parts.Length != 4) + throw new ArgumentOutOfRangeException(nameof(s), s, "target should be in the form cpu-platform-os"); + + var shortestIndex = parts.Length == 3 ? + IndexOfMin(parts[0].Length, parts[1].Length, parts[2].Length) : + IndexOfMin(parts[0].Length, parts[1].Length, parts[2].Length, parts[3].Length); + + if (parts[shortestIndex].Length == 0) + { + var missingPart = new string[] { "cpu", "platform", "os", "os" }[shortestIndex]; + throw new ArgumentException($"target (cpu-platform-os) has an empty {missingPart} component."); + } + + return parts; + } + + static int IndexOfMin(params int[] values) + { + var min = values.Min(); + return Array.IndexOf(values, min); + } + + public static string ClangTargetCpu(this string s) + { + return s.DecomposeClangTarget()[0]; + } + + public static string ClangTargetPlatform(this string s) + { + return s.DecomposeClangTarget()[1]; + } + + public static string ClangTargetOS(this string s) + { + var clangTarget = s.DecomposeClangTarget(); + if (clangTarget.Length == 3) + return clangTarget[2]; + if (clangTarget.Length == 4) + return $"{clangTarget[2]}-{clangTarget[3]}"; + throw new ArgumentException($"Clang target {s} should have 3 or 4 parts", nameof(s)); + } + + static int IndexOfFirstDigit(string s) + { + int index = 0; + foreach (char c in s) + { + if (Char.IsDigit(c)) + return index; + index++; + } + return -1; + } + + public static string ClangOSNoVersion(this string s) + { + var clangTarget = s.DecomposeClangTarget(); + var os = clangTarget[2]; + return OSNoVersion(os); + } + + static string OSNoVersion(string s) + { + var firstNumber = IndexOfFirstDigit(s); + return firstNumber < 0 ? s : s.Substring(0, firstNumber); + } + + public static string ClangOSVersion(this string s) + { + var clangTarget = s.DecomposeClangTarget(); + var os = clangTarget[2]; + var firstNumber = IndexOfFirstDigit(os); + return os.Substring(firstNumber); + } + + public static string MinimumClangVersion(IEnumerable targets) + { + var osVersion = targets.Select(t => new Version(ClangOSVersion(t))).Min(); + return osVersion.ToString(); + } + + public static string ClangSubstituteOSVersion(this string s, string replacementVersion) + { + var clangTarget = s.DecomposeClangTarget(); + var os = OSNoVersion(clangTarget[2]) + replacementVersion; + clangTarget[2] = os; + return clangTarget.InterleaveStrings("-"); + } + + public static bool ClangTargetIsSimulator(this string s) + { + var parts = s.DecomposeClangTarget(); + if (parts.Length == 4 && parts[3] == "simulator") + return true; + var osNoVersion = OSNoVersion(parts[2]); + if (osNoVersion == "macosx") + return false; + var cpu = parts[0]; + return cpu == "i386" || cpu == "x86-64"; + } + + public static void Merge(this HashSet to, IEnumerable from) + { + Exceptions.ThrowOnNull(from, nameof(from)); + foreach (T val in from) + to.Add(val); + } + + public static void DisposeAll(this IEnumerable coll) where T : IDisposable + { + Exceptions.ThrowOnNull(coll, nameof(coll)); + foreach (T obj in coll) + { + if ((IDisposable)obj != null) + obj.Dispose(); + } + } + + public static string InterleaveStrings(this IEnumerable elements, string separator, bool includeSepFirst = false) + { + StringBuilder sb = new StringBuilder(); + foreach (string s in elements.Interleave(separator, includeSepFirst)) + sb.Append(s); + return sb.ToString(); + } + + public static string InterleaveCommas(this IEnumerable elements) + { + return elements.InterleaveStrings(", "); + } + + public static bool IsSwift3(this Version vers) + { + return vers.Major == 3; + } + + public static bool IsSwift4(this Version vers) + { + return vers.Major == 4; + } + + public static int ErrorCount(this List errors) + { + var count = 0; + foreach (var error in errors) + { + if (!error.IsWarning) + ++count; + } + return count; + } + + public static int WarningCount(this List errors) + { + return errors.Count - errors.ErrorCount(); + } + + public static List CloneAndPrepend(this List source, T item) + { + var result = new List(source.Count + 1); + result.Add(item); + result.AddRange(source); + return result; + } + + public static T[] And(this T[] first, T[] second) + { + Exceptions.ThrowOnNull(first, nameof(first)); + Exceptions.ThrowOnNull(second, nameof(second)); + var result = new T[first.Length + second.Length]; + Array.Copy(first, result, first.Length); + Array.Copy(second, 0, result, first.Length, second.Length); + return result; + } + } } diff --git a/src/SwiftReflector/IOUtils/ExecAndCollect.cs b/src/SwiftReflector/IOUtils/ExecAndCollect.cs index 37469c532375..b4e6539fdcaa 100644 --- a/src/SwiftReflector/IOUtils/ExecAndCollect.cs +++ b/src/SwiftReflector/IOUtils/ExecAndCollect.cs @@ -8,108 +8,124 @@ using System.Text; using System.Threading; -namespace SwiftReflector.IOUtils { - public class ExecAndCollect { - public static string Run (string path, string args, string workingDirectory = null, bool verbose = false) - { - var output = new StringBuilder (); - var exitCode = RunCommand (path, args, output: output, verbose: verbose, workingDirectory: workingDirectory); - if (exitCode != 0) - throw new Exception ($"Failed to execute (exit code {exitCode}): {path} {string.Join (" ", args)}\n{output.ToString ()}"); - return output.ToString (); - } - - static void ReadStream (Stream stream, StringBuilder sb, ManualResetEvent completed) - { - var encoding = Encoding.UTF8; - var decoder = encoding.GetDecoder (); - var buffer = new byte [1024]; - var characters = new char [encoding.GetMaxCharCount (buffer.Length)]; - - AsyncCallback callback = null; - callback = new AsyncCallback ((IAsyncResult ar) => { - var read = stream.EndRead (ar); - - var chars = decoder.GetChars (buffer, 0, read, characters, 0); - lock (sb) - sb.Append (characters, 0, chars); - - if (read > 0) { - stream.BeginRead (buffer, 0, buffer.Length, callback, null); - } else { - completed.Set (); - } - }); - stream.BeginRead (buffer, 0, buffer.Length, callback, null); - } - - public static int RunCommand (string path, string args, IDictionary env = null, StringBuilder output = null, bool verbose = false, string workingDirectory = null) - { - var info = new ProcessStartInfo (path, args); - info.UseShellExecute = false; - info.RedirectStandardInput = false; - info.RedirectStandardOutput = true; - info.RedirectStandardError = true; - if (workingDirectory != null) - info.WorkingDirectory = workingDirectory; - - if (output == null) - output = new StringBuilder (); - - if (env != null) { - foreach (var kvp in env) { - if (kvp.Value == null) { - if (info.EnvironmentVariables.ContainsKey (kvp.Key)) - info.EnvironmentVariables.Remove (kvp.Key); - } else { - info.EnvironmentVariables [kvp.Key] = kvp.Value; - } - } - } - - if (info.EnvironmentVariables.ContainsKey ("XCODE_DEVELOPER_DIR_PATH")) { - // VSfM adds this key, which confuses Xcode mightily if it doesn't match the value of xcode-select. - // So just remove it, we don't need it for anything. - info.EnvironmentVariables.Remove ("XCODE_DEVELOPER_DIR_PATH"); - } - - - if (verbose) { - var envOut = new StringBuilder (); - foreach (var key in info.EnvironmentVariables.Keys) { - var value = info.EnvironmentVariables [key as string]; - envOut.AppendLine ($"export {key}={value}"); - } - envOut.AppendLine ($"{path} {args}"); - Console.Write (envOut.ToString ()); - Console.WriteLine ("{0} {1}", path, args); - } - - using (var p = Process.Start (info)) { - var error_output = new StringBuilder (); - var stdout_completed = new ManualResetEvent (false); - var stderr_completed = new ManualResetEvent (false); - - ReadStream (p.StandardOutput.BaseStream, output, stdout_completed); - ReadStream (p.StandardError.BaseStream, error_output, stderr_completed); - - p.WaitForExit (); - - stderr_completed.WaitOne (TimeSpan.FromMinutes (1)); - stdout_completed.WaitOne (TimeSpan.FromMinutes (1)); - - if (verbose) { - if (output.Length > 0) - Console.WriteLine (output); - if (error_output.Length > 0) - Console.WriteLine (error_output); - if (p.ExitCode != 0) - Console.Error.WriteLine ($"Process exited with code {p.ExitCode}"); - } - if (p.ExitCode != 0 && error_output.Length > 0) - output.Append (error_output); - return p.ExitCode; - } - } - } +namespace SwiftReflector.IOUtils +{ + public class ExecAndCollect + { + public static string Run(string path, string args, string workingDirectory = null, bool verbose = false) + { + var output = new StringBuilder(); + var exitCode = RunCommand(path, args, output: output, verbose: verbose, workingDirectory: workingDirectory); + if (exitCode != 0) + throw new Exception($"Failed to execute (exit code {exitCode}): {path} {string.Join(" ", args)}\n{output.ToString()}"); + return output.ToString(); + } + + static void ReadStream(Stream stream, StringBuilder sb, ManualResetEvent completed) + { + var encoding = Encoding.UTF8; + var decoder = encoding.GetDecoder(); + var buffer = new byte[1024]; + var characters = new char[encoding.GetMaxCharCount(buffer.Length)]; + + AsyncCallback callback = null; + callback = new AsyncCallback((IAsyncResult ar) => + { + var read = stream.EndRead(ar); + + var chars = decoder.GetChars(buffer, 0, read, characters, 0); + lock (sb) + sb.Append(characters, 0, chars); + + if (read > 0) + { + stream.BeginRead(buffer, 0, buffer.Length, callback, null); + } + else + { + completed.Set(); + } + }); + stream.BeginRead(buffer, 0, buffer.Length, callback, null); + } + + public static int RunCommand(string path, string args, IDictionary env = null, StringBuilder output = null, bool verbose = false, string workingDirectory = null) + { + var info = new ProcessStartInfo(path, args); + info.UseShellExecute = false; + info.RedirectStandardInput = false; + info.RedirectStandardOutput = true; + info.RedirectStandardError = true; + if (workingDirectory != null) + info.WorkingDirectory = workingDirectory; + + if (output == null) + output = new StringBuilder(); + + if (env != null) + { + foreach (var kvp in env) + { + if (kvp.Value == null) + { + if (info.EnvironmentVariables.ContainsKey(kvp.Key)) + info.EnvironmentVariables.Remove(kvp.Key); + } + else + { + info.EnvironmentVariables[kvp.Key] = kvp.Value; + } + } + } + + if (info.EnvironmentVariables.ContainsKey("XCODE_DEVELOPER_DIR_PATH")) + { + // VSfM adds this key, which confuses Xcode mightily if it doesn't match the value of xcode-select. + // So just remove it, we don't need it for anything. + info.EnvironmentVariables.Remove("XCODE_DEVELOPER_DIR_PATH"); + } + + + if (verbose) + { + var envOut = new StringBuilder(); + foreach (var key in info.EnvironmentVariables.Keys) + { + var value = info.EnvironmentVariables[key as string]; + envOut.AppendLine($"export {key}={value}"); + } + envOut.AppendLine($"{path} {args}"); + Console.Write(envOut.ToString()); + Console.WriteLine("{0} {1}", path, args); + } + + using (var p = Process.Start(info)) + { + var error_output = new StringBuilder(); + var stdout_completed = new ManualResetEvent(false); + var stderr_completed = new ManualResetEvent(false); + + ReadStream(p.StandardOutput.BaseStream, output, stdout_completed); + ReadStream(p.StandardError.BaseStream, error_output, stderr_completed); + + p.WaitForExit(); + + stderr_completed.WaitOne(TimeSpan.FromMinutes(1)); + stdout_completed.WaitOne(TimeSpan.FromMinutes(1)); + + if (verbose) + { + if (output.Length > 0) + Console.WriteLine(output); + if (error_output.Length > 0) + Console.WriteLine(error_output); + if (p.ExitCode != 0) + Console.Error.WriteLine($"Process exited with code {p.ExitCode}"); + } + if (p.ExitCode != 0 && error_output.Length > 0) + output.Append(error_output); + return p.ExitCode; + } + } + } } diff --git a/src/SwiftReflector/IOUtils/IFileProvider.cs b/src/SwiftReflector/IOUtils/IFileProvider.cs index 41036297bbc2..8ec5e5db4c66 100644 --- a/src/SwiftReflector/IOUtils/IFileProvider.cs +++ b/src/SwiftReflector/IOUtils/IFileProvider.cs @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SwiftReflector.IOUtils { - public interface IFileProvider { - string ProvideFileFor (T thing); - void NotifyFileDone (T thing, string stm); - } +namespace SwiftReflector.IOUtils +{ + public interface IFileProvider + { + string ProvideFileFor(T thing); + void NotifyFileDone(T thing, string stm); + } } diff --git a/src/SwiftReflector/IOUtils/IXElementConvertible.cs b/src/SwiftReflector/IOUtils/IXElementConvertible.cs index d179c3181b6e..3e8f695527de 100644 --- a/src/SwiftReflector/IOUtils/IXElementConvertible.cs +++ b/src/SwiftReflector/IOUtils/IXElementConvertible.cs @@ -3,9 +3,11 @@ using System.Xml.Linq; -namespace SwiftReflector.IOUtils { - public interface IXElementConvertible { - XElement ToXElement (); - } +namespace SwiftReflector.IOUtils +{ + public interface IXElementConvertible + { + XElement ToXElement(); + } } diff --git a/src/SwiftReflector/IOUtils/OffsetStream.cs b/src/SwiftReflector/IOUtils/OffsetStream.cs index f7479e4c79d4..f2ab332b1366 100644 --- a/src/SwiftReflector/IOUtils/OffsetStream.cs +++ b/src/SwiftReflector/IOUtils/OffsetStream.cs @@ -4,151 +4,170 @@ using System; using System.IO; -namespace SwiftReflector.IOUtils { - public class OffsetStream : Stream { - Stream stm; - long offset; - public OffsetStream (Stream stm, long offset) - { - this.stm = stm; - this.offset = offset; - stm.Seek (offset, SeekOrigin.Begin); - } - - public override bool CanRead { - get { - return stm.CanRead; - } - } - - public override bool CanSeek { - get { - return stm.CanSeek; - } - } - - public override bool CanTimeout { - get { - return stm.CanTimeout; - } - } - - public override bool CanWrite { - get { - return stm.CanWrite; - } - } - - public override void Close () - { - stm.Close (); - base.Close (); - } - - public override IAsyncResult BeginRead (byte [] buffer, int offset, int count, AsyncCallback callback, object state) - { - return stm.BeginRead (buffer, offset, count, callback, state); - } - - public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count, AsyncCallback callback, object state) - { - return stm.BeginWrite (buffer, offset, count, callback, state); - } - - public override System.Threading.Tasks.Task CopyToAsync (Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) - { - return stm.CopyToAsync (destination, bufferSize, cancellationToken); - } - - protected override void Dispose (bool disposing) - { - if (disposing) - stm.Dispose (); - base.Dispose (); - } - - public override int EndRead (IAsyncResult asyncResult) - { - return stm.EndRead (asyncResult); - } - - public override void EndWrite (IAsyncResult asyncResult) - { - stm.EndWrite (asyncResult); - } - - public override void Flush () - { - stm.Flush (); - } - - public override System.Threading.Tasks.Task FlushAsync (System.Threading.CancellationToken cancellationToken) - { - return stm.FlushAsync (cancellationToken); - } - - public override long Length { - get { - return stm.Length - offset; - } - } - - public override long Position { - get { - return stm.Position - offset; - } - set { - stm.Position = value + offset; - } - } - - public override int Read (byte [] buffer, int offset, int count) - { - return stm.Read (buffer, offset, count); - } - - public override System.Threading.Tasks.Task ReadAsync (byte [] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) - { - return stm.ReadAsync (buffer, offset, count, cancellationToken); - } - - public override int ReadByte () - { - return stm.ReadByte (); - } - - public override int ReadTimeout { - get { - return stm.ReadTimeout; - } - set { - stm.ReadTimeout = value; - } - } - - public override long Seek (long offset, SeekOrigin origin) - { - switch (origin) { - case SeekOrigin.Begin: - return stm.Seek (offset + this.offset, origin) - this.offset; - case SeekOrigin.Current: - return stm.Seek (offset, origin) - this.offset; - case SeekOrigin.End: - return stm.Seek (offset, origin) - this.offset; - default: - return 0; - } - } - - public override void SetLength (long value) - { - stm.SetLength (value); - } - - public override void Write (byte [] buffer, int offset, int count) - { - stm.Write (buffer, offset, count); - } - } +namespace SwiftReflector.IOUtils +{ + public class OffsetStream : Stream + { + Stream stm; + long offset; + public OffsetStream(Stream stm, long offset) + { + this.stm = stm; + this.offset = offset; + stm.Seek(offset, SeekOrigin.Begin); + } + + public override bool CanRead + { + get + { + return stm.CanRead; + } + } + + public override bool CanSeek + { + get + { + return stm.CanSeek; + } + } + + public override bool CanTimeout + { + get + { + return stm.CanTimeout; + } + } + + public override bool CanWrite + { + get + { + return stm.CanWrite; + } + } + + public override void Close() + { + stm.Close(); + base.Close(); + } + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return stm.BeginRead(buffer, offset, count, callback, state); + } + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return stm.BeginWrite(buffer, offset, count, callback, state); + } + + public override System.Threading.Tasks.Task CopyToAsync(Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) + { + return stm.CopyToAsync(destination, bufferSize, cancellationToken); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + stm.Dispose(); + base.Dispose(); + } + + public override int EndRead(IAsyncResult asyncResult) + { + return stm.EndRead(asyncResult); + } + + public override void EndWrite(IAsyncResult asyncResult) + { + stm.EndWrite(asyncResult); + } + + public override void Flush() + { + stm.Flush(); + } + + public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) + { + return stm.FlushAsync(cancellationToken); + } + + public override long Length + { + get + { + return stm.Length - offset; + } + } + + public override long Position + { + get + { + return stm.Position - offset; + } + set + { + stm.Position = value + offset; + } + } + + public override int Read(byte[] buffer, int offset, int count) + { + return stm.Read(buffer, offset, count); + } + + public override System.Threading.Tasks.Task ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + { + return stm.ReadAsync(buffer, offset, count, cancellationToken); + } + + public override int ReadByte() + { + return stm.ReadByte(); + } + + public override int ReadTimeout + { + get + { + return stm.ReadTimeout; + } + set + { + stm.ReadTimeout = value; + } + } + + public override long Seek(long offset, SeekOrigin origin) + { + switch (origin) + { + case SeekOrigin.Begin: + return stm.Seek(offset + this.offset, origin) - this.offset; + case SeekOrigin.Current: + return stm.Seek(offset, origin) - this.offset; + case SeekOrigin.End: + return stm.Seek(offset, origin) - this.offset; + default: + return 0; + } + } + + public override void SetLength(long value) + { + stm.SetLength(value); + } + + public override void Write(byte[] buffer, int offset, int count) + { + stm.Write(buffer, offset, count); + } + } } diff --git a/src/SwiftReflector/Inventory/ClassContents.cs b/src/SwiftReflector/Inventory/ClassContents.cs index ded6505dbcab..2378ca2d78bf 100644 --- a/src/SwiftReflector/Inventory/ClassContents.cs +++ b/src/SwiftReflector/Inventory/ClassContents.cs @@ -8,300 +8,348 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class ClassContents { - int sizeofMachinePointer; - public ClassContents (SwiftClassName className, int sizeofMachiinePointer) - { - this.sizeofMachinePointer = sizeofMachiinePointer; - Constructors = new FunctionInventory (sizeofMachinePointer); - ClassConstructor = new FunctionInventory (sizeofMachinePointer); - Methods = new FunctionInventory (sizeofMachinePointer); - Properties = new PropertyInventory (sizeofMachinePointer); - StaticProperties = new PropertyInventory (sizeofMachiinePointer); - PrivateProperties = new PropertyInventory (sizeofMachinePointer); - StaticPrivateProperties = new PropertyInventory (sizeofMachinePointer); - Subscripts = new List (sizeofMachinePointer); - PrivateSubscripts = new List (sizeofMachinePointer); - StaticFunctions = new FunctionInventory (sizeofMachinePointer); - Destructors = new FunctionInventory (sizeofMachinePointer); - EnumCases = new FunctionInventory (sizeofMachiinePointer); - WitnessTable = new WitnessInventory (sizeofMachinePointer); - FunctionsOfUnknownDestination = new List (); - DefinitionsOfUnknownDestination = new List (); - Variables = new VariableInventory (sizeofMachinePointer); - Initializers = new FunctionInventory (sizeofMachinePointer); - Name = className; - ProtocolConformanceDescriptors = new List (); - MethodDescriptors = new FunctionInventory (sizeofMachinePointer); - PropertyDescriptors = new List (); - } +namespace SwiftReflector.Inventory +{ + public class ClassContents + { + int sizeofMachinePointer; + public ClassContents(SwiftClassName className, int sizeofMachiinePointer) + { + this.sizeofMachinePointer = sizeofMachiinePointer; + Constructors = new FunctionInventory(sizeofMachinePointer); + ClassConstructor = new FunctionInventory(sizeofMachinePointer); + Methods = new FunctionInventory(sizeofMachinePointer); + Properties = new PropertyInventory(sizeofMachinePointer); + StaticProperties = new PropertyInventory(sizeofMachiinePointer); + PrivateProperties = new PropertyInventory(sizeofMachinePointer); + StaticPrivateProperties = new PropertyInventory(sizeofMachinePointer); + Subscripts = new List(sizeofMachinePointer); + PrivateSubscripts = new List(sizeofMachinePointer); + StaticFunctions = new FunctionInventory(sizeofMachinePointer); + Destructors = new FunctionInventory(sizeofMachinePointer); + EnumCases = new FunctionInventory(sizeofMachiinePointer); + WitnessTable = new WitnessInventory(sizeofMachinePointer); + FunctionsOfUnknownDestination = new List(); + DefinitionsOfUnknownDestination = new List(); + Variables = new VariableInventory(sizeofMachinePointer); + Initializers = new FunctionInventory(sizeofMachinePointer); + Name = className; + ProtocolConformanceDescriptors = new List(); + MethodDescriptors = new FunctionInventory(sizeofMachinePointer); + PropertyDescriptors = new List(); + } - public void Add (TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) { - if (IsConstructor (tlf.Signature, tlf.Class)) { - AddOrChainInNewThunk (Constructors, tlf, srcStm); - } else if (tlf.Signature is SwiftClassConstructorType) { - if (ClassConstructor.Values.Count () == 0) - AddOrChainInNewThunk (ClassConstructor, tlf, srcStm); - else - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 12, $"multiple type metadata accessors for {tlf.Class.ClassName.ToFullyQualifiedName ()}"); - } else if (IsDestructor (tlf.Signature, tlf.Class)) { - AddOrChainInNewThunk (Destructors, tlf, srcStm); - } else if (tlf is TLEnumCase) { - AddOrChainInNewThunk (EnumCases, tlf, srcStm); - } else if (IsProperty (tlf.Signature, tlf.Class)) { - if (IsSubscript (tlf.Signature, tlf.Class)) { - if (IsPrivateProperty (tlf.Signature, tlf.Class)) - PrivateSubscripts.Add (tlf); - else - Subscripts.Add (tlf); - } else { - if (IsStaticProperty (tlf.Signature, tlf.Class)) { - if (IsPrivateProperty (tlf.Signature, tlf.Class)) - StaticPrivateProperties.Add (tlf, srcStm); - else - StaticProperties.Add (tlf, srcStm); - } else { - if (IsPrivateProperty (tlf.Signature, tlf.Class)) - PrivateProperties.Add (tlf, srcStm); - else - Properties.Add (tlf, srcStm); - } - } - } else if (IsMethodOnClass (tlf.Signature, tlf.Class)) { - if (tlf is TLMethodDescriptor) - MethodDescriptors.Add (tlf, srcStm); - else { - AddOrChainInNewThunk (Methods, tlf, srcStm); - } - } else if (IsStaticMethod (tlf.Signature, tlf.Class)) { - AddOrChainInNewThunk (StaticFunctions, tlf, srcStm); - } else if (IsWitnessTable (tlf.Signature, tlf.Class)) { - WitnessTable.Add (tlf, srcStm); - } else if (IsInitializer (tlf.Signature, tlf.Class)) { - AddOrChainInNewThunk (Initializers, tlf, srcStm); - } else { - FunctionsOfUnknownDestination.Add (tlf); - } - return; - } - var meta = tld as TLDirectMetadata; - if (meta != null) { - if (DirectMetadata != null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 13, $"duplicate direct metadata in class {DirectMetadata.Class.ClassName.ToFullyQualifiedName ()}"); - DirectMetadata = meta; - return; - } - var lazy = tld as TLLazyCacheVariable; - if (lazy != null) { - if (LazyCacheVariable != null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 14, $"duplicate lazy cache variable in class {LazyCacheVariable.Class.ClassName.ToFullyQualifiedName ()}"); - LazyCacheVariable = lazy; - return; - } - var mc = tld as TLMetaclass; - if (mc != null) { - if (Metaclass != null) { - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 15, $"duplicate type meta data descriptor in class {Metaclass.Class.ClassName.ToFullyQualifiedName ()}"); - } - Metaclass = mc; - return; - } - var nom = tld as TLNominalTypeDescriptor; - if (nom != null) { - if (TypeDescriptor != null) { - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 16, $"duplicate nominal type descriptor in class {TypeDescriptor.Class.ClassName.ToFullyQualifiedName ()}"); - } - TypeDescriptor = nom; - return; - } - var tlvar = tld as TLVariable; - if (tlvar != null) { - if (tlvar is TLPropertyDescriptor tlpropDesc) - PropertyDescriptors.Add (tlpropDesc); - else - Variables.Add (tlvar, srcStm); - return; - } - var tlprot = tld as TLProtocolConformanceDescriptor; - if (tlprot != null) { - ProtocolConformanceDescriptors.Add (tlprot); - return; - } - DefinitionsOfUnknownDestination.Add (tld); - } + public void Add(TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) + { + if (IsConstructor(tlf.Signature, tlf.Class)) + { + AddOrChainInNewThunk(Constructors, tlf, srcStm); + } + else if (tlf.Signature is SwiftClassConstructorType) + { + if (ClassConstructor.Values.Count() == 0) + AddOrChainInNewThunk(ClassConstructor, tlf, srcStm); + else + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 12, $"multiple type metadata accessors for {tlf.Class.ClassName.ToFullyQualifiedName()}"); + } + else if (IsDestructor(tlf.Signature, tlf.Class)) + { + AddOrChainInNewThunk(Destructors, tlf, srcStm); + } + else if (tlf is TLEnumCase) + { + AddOrChainInNewThunk(EnumCases, tlf, srcStm); + } + else if (IsProperty(tlf.Signature, tlf.Class)) + { + if (IsSubscript(tlf.Signature, tlf.Class)) + { + if (IsPrivateProperty(tlf.Signature, tlf.Class)) + PrivateSubscripts.Add(tlf); + else + Subscripts.Add(tlf); + } + else + { + if (IsStaticProperty(tlf.Signature, tlf.Class)) + { + if (IsPrivateProperty(tlf.Signature, tlf.Class)) + StaticPrivateProperties.Add(tlf, srcStm); + else + StaticProperties.Add(tlf, srcStm); + } + else + { + if (IsPrivateProperty(tlf.Signature, tlf.Class)) + PrivateProperties.Add(tlf, srcStm); + else + Properties.Add(tlf, srcStm); + } + } + } + else if (IsMethodOnClass(tlf.Signature, tlf.Class)) + { + if (tlf is TLMethodDescriptor) + MethodDescriptors.Add(tlf, srcStm); + else + { + AddOrChainInNewThunk(Methods, tlf, srcStm); + } + } + else if (IsStaticMethod(tlf.Signature, tlf.Class)) + { + AddOrChainInNewThunk(StaticFunctions, tlf, srcStm); + } + else if (IsWitnessTable(tlf.Signature, tlf.Class)) + { + WitnessTable.Add(tlf, srcStm); + } + else if (IsInitializer(tlf.Signature, tlf.Class)) + { + AddOrChainInNewThunk(Initializers, tlf, srcStm); + } + else + { + FunctionsOfUnknownDestination.Add(tlf); + } + return; + } + var meta = tld as TLDirectMetadata; + if (meta != null) + { + if (DirectMetadata != null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 13, $"duplicate direct metadata in class {DirectMetadata.Class.ClassName.ToFullyQualifiedName()}"); + DirectMetadata = meta; + return; + } + var lazy = tld as TLLazyCacheVariable; + if (lazy != null) + { + if (LazyCacheVariable != null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 14, $"duplicate lazy cache variable in class {LazyCacheVariable.Class.ClassName.ToFullyQualifiedName()}"); + LazyCacheVariable = lazy; + return; + } + var mc = tld as TLMetaclass; + if (mc != null) + { + if (Metaclass != null) + { + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 15, $"duplicate type meta data descriptor in class {Metaclass.Class.ClassName.ToFullyQualifiedName()}"); + } + Metaclass = mc; + return; + } + var nom = tld as TLNominalTypeDescriptor; + if (nom != null) + { + if (TypeDescriptor != null) + { + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 16, $"duplicate nominal type descriptor in class {TypeDescriptor.Class.ClassName.ToFullyQualifiedName()}"); + } + TypeDescriptor = nom; + return; + } + var tlvar = tld as TLVariable; + if (tlvar != null) + { + if (tlvar is TLPropertyDescriptor tlpropDesc) + PropertyDescriptors.Add(tlpropDesc); + else + Variables.Add(tlvar, srcStm); + return; + } + var tlprot = tld as TLProtocolConformanceDescriptor; + if (tlprot != null) + { + ProtocolConformanceDescriptors.Add(tlprot); + return; + } + DefinitionsOfUnknownDestination.Add(tld); + } - static void AddOrChainInNewThunk (FunctionInventory inventory, TLFunction newTLF, Stream sourceStream) - { - var oldTLF = inventory.ContainsEquivalentFunction (newTLF); - if (oldTLF == null) - inventory.Add (newTLF, sourceStream); - else { - var newSig = newTLF.Signature; - var oldSig = oldTLF.Signature; - if (oldSig.IsThunk) { - newSig.Thunk = oldSig; - inventory.ReplaceFunction (oldTLF, newTLF); - } else { - oldSig.Thunk = newSig; - } - } - } + static void AddOrChainInNewThunk(FunctionInventory inventory, TLFunction newTLF, Stream sourceStream) + { + var oldTLF = inventory.ContainsEquivalentFunction(newTLF); + if (oldTLF == null) + inventory.Add(newTLF, sourceStream); + else + { + var newSig = newTLF.Signature; + var oldSig = oldTLF.Signature; + if (oldSig.IsThunk) + { + newSig.Thunk = oldSig; + inventory.ReplaceFunction(oldTLF, newTLF); + } + else + { + oldSig.Thunk = newSig; + } + } + } - public bool IsFinal (TLFunction func) - { - string funcMangledSuffix = func.MangledName.Substring (3); // drop the __T + public bool IsFinal(TLFunction func) + { + string funcMangledSuffix = func.MangledName.Substring(3); // drop the __T - foreach (string mangledWitnessEntry in WitnessTable.MangledNames) { - if (mangledWitnessEntry.EndsWith (funcMangledSuffix)) - return false; - } - return true; - } + foreach (string mangledWitnessEntry in WitnessTable.MangledNames) + { + if (mangledWitnessEntry.EndsWith(funcMangledSuffix)) + return false; + } + return true; + } - static bool IsConstructor (SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - SwiftConstructorType des = signature as SwiftConstructorType; - if (des == null) - return false; - return des.Name.Equals (Decomposer.kSwiftAllocatingConstructorName) - || des.Name.Equals (Decomposer.kSwiftNonAllocatingConstructorName); - } + static bool IsConstructor(SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + SwiftConstructorType des = signature as SwiftConstructorType; + if (des == null) + return false; + return des.Name.Equals(Decomposer.kSwiftAllocatingConstructorName) + || des.Name.Equals(Decomposer.kSwiftNonAllocatingConstructorName); + } - static bool IsDestructor (SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - SwiftDestructorType des = signature as SwiftDestructorType; - if (des == null) - return false; - return des.Name.Equals (Decomposer.kSwiftDeallocatingDestructorName) - || des.Name.Equals (Decomposer.kSwiftNonDeallocatingDestructorName); - } + static bool IsDestructor(SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + SwiftDestructorType des = signature as SwiftDestructorType; + if (des == null) + return false; + return des.Name.Equals(Decomposer.kSwiftDeallocatingDestructorName) + || des.Name.Equals(Decomposer.kSwiftNonDeallocatingDestructorName); + } - public static bool IsWitnessTable (SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - return signature is SwiftWitnessTableType; - } + public static bool IsWitnessTable(SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + return signature is SwiftWitnessTableType; + } - public static bool IsInitializer (SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - return signature is SwiftInitializerType; - } + public static bool IsInitializer(SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + return signature is SwiftInitializerType; + } - static bool IsProperty (SwiftType signature, SwiftClassType cl) - { - return signature is SwiftPropertyType; - } + static bool IsProperty(SwiftType signature, SwiftClassType cl) + { + return signature is SwiftPropertyType; + } - static bool IsSubscript (SwiftType signature, SwiftClassType cl) - { - SwiftPropertyType prop = signature as SwiftPropertyType; - return prop != null && prop.IsSubscript; - } + static bool IsSubscript(SwiftType signature, SwiftClassType cl) + { + SwiftPropertyType prop = signature as SwiftPropertyType; + return prop != null && prop.IsSubscript; + } - static bool IsPrivateProperty (SwiftType signature, SwiftClassType cl) - { - SwiftPropertyType pt = signature as SwiftPropertyType; - return pt != null && pt.IsPrivate; - } + static bool IsPrivateProperty(SwiftType signature, SwiftClassType cl) + { + SwiftPropertyType pt = signature as SwiftPropertyType; + return pt != null && pt.IsPrivate; + } - static bool IsStaticProperty(SwiftType signature, SwiftClassType classType) - { - SwiftPropertyType pt = signature as SwiftPropertyType; - return pt != null && pt.IsStatic; - } + static bool IsStaticProperty(SwiftType signature, SwiftClassType classType) + { + SwiftPropertyType pt = signature as SwiftPropertyType; + return pt != null && pt.IsStatic; + } - static bool IsMethodOnClass (SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - if (signature is SwiftWitnessTableType) - return false; - SwiftUncurriedFunctionType ucf = signature as SwiftUncurriedFunctionType; - if (ucf == null) - return false; - return ucf.UncurriedParameter is SwiftClassType && ucf.UncurriedParameter.Equals (cl); - } + static bool IsMethodOnClass(SwiftType signature, SwiftClassType cl) + { + if (cl == null) + return false; + if (signature is SwiftWitnessTableType) + return false; + SwiftUncurriedFunctionType ucf = signature as SwiftUncurriedFunctionType; + if (ucf == null) + return false; + return ucf.UncurriedParameter is SwiftClassType && ucf.UncurriedParameter.Equals(cl); + } - static bool IsStaticMethod (SwiftType signature, SwiftClassType cl) - { - return signature is SwiftStaticFunctionType; - } + static bool IsStaticMethod(SwiftType signature, SwiftClassType cl) + { + return signature is SwiftStaticFunctionType; + } - public IEnumerable AllPropertiesWithName(string name) - { - PropertyContents prop = null; - if (Properties.TryGetValue (name, out prop)) - yield return prop; - if (PrivateProperties.TryGetValue (name, out prop)) - yield return prop; - if (StaticProperties.TryGetValue (name, out prop)) - yield return prop; - if (StaticPrivateProperties.TryGetValue (name, out prop)) - yield return prop; - } + public IEnumerable AllPropertiesWithName(string name) + { + PropertyContents prop = null; + if (Properties.TryGetValue(name, out prop)) + yield return prop; + if (PrivateProperties.TryGetValue(name, out prop)) + yield return prop; + if (StaticProperties.TryGetValue(name, out prop)) + yield return prop; + if (StaticPrivateProperties.TryGetValue(name, out prop)) + yield return prop; + } - public TLFunction SoleMetadataAccessor { - get { - if (ClassConstructor == null || ClassConstructor.Values.Count () == 0) - return null; - var elem = ClassConstructor.Values.ElementAt (0); - if (elem.Functions.Count == 0) - return null; - return elem.Functions [0]; - } - } + public TLFunction SoleMetadataAccessor + { + get + { + if (ClassConstructor == null || ClassConstructor.Values.Count() == 0) + return null; + var elem = ClassConstructor.Values.ElementAt(0); + if (elem.Functions.Count == 0) + return null; + return elem.Functions[0]; + } + } - public SwiftClassName Name { get; private set; } - public FunctionInventory Constructors { get; private set; } - public FunctionInventory ClassConstructor { get; private set; } - public FunctionInventory Destructors { get; private set; } - public FunctionInventory EnumCases { get; private set; } - public PropertyInventory Properties { get; private set; } - public PropertyInventory StaticProperties { get; private set; } - public PropertyInventory PrivateProperties { get; private set; } - public PropertyInventory StaticPrivateProperties { get; private set; } - public List Subscripts { get; private set; } - public List PrivateSubscripts { get; private set; } - public FunctionInventory Methods { get; private set; } - public FunctionInventory StaticFunctions { get; private set; } - public WitnessInventory WitnessTable { get; private set; } - public TLLazyCacheVariable LazyCacheVariable { get; private set; } - public TLDirectMetadata DirectMetadata { get; private set; } - public TLMetaclass Metaclass { get; private set; } - public TLNominalTypeDescriptor TypeDescriptor { get; private set; } - public List FunctionsOfUnknownDestination { get; private set; } - public List DefinitionsOfUnknownDestination { get; private set; } - public VariableInventory Variables { get; private set; } - public List PropertyDescriptors { get; private set; } - public FunctionInventory Initializers { get; private set; } - public List ProtocolConformanceDescriptors { get; private set; } - public FunctionInventory MethodDescriptors { get; private set; } + public SwiftClassName Name { get; private set; } + public FunctionInventory Constructors { get; private set; } + public FunctionInventory ClassConstructor { get; private set; } + public FunctionInventory Destructors { get; private set; } + public FunctionInventory EnumCases { get; private set; } + public PropertyInventory Properties { get; private set; } + public PropertyInventory StaticProperties { get; private set; } + public PropertyInventory PrivateProperties { get; private set; } + public PropertyInventory StaticPrivateProperties { get; private set; } + public List Subscripts { get; private set; } + public List PrivateSubscripts { get; private set; } + public FunctionInventory Methods { get; private set; } + public FunctionInventory StaticFunctions { get; private set; } + public WitnessInventory WitnessTable { get; private set; } + public TLLazyCacheVariable LazyCacheVariable { get; private set; } + public TLDirectMetadata DirectMetadata { get; private set; } + public TLMetaclass Metaclass { get; private set; } + public TLNominalTypeDescriptor TypeDescriptor { get; private set; } + public List FunctionsOfUnknownDestination { get; private set; } + public List DefinitionsOfUnknownDestination { get; private set; } + public VariableInventory Variables { get; private set; } + public List PropertyDescriptors { get; private set; } + public FunctionInventory Initializers { get; private set; } + public List ProtocolConformanceDescriptors { get; private set; } + public FunctionInventory MethodDescriptors { get; private set; } - public int SizeInBytes { - get { - ValueWitnessTable vat = WitnessTable.ValueWitnessTable; - return vat != null ? (int)vat.Size : 0; - } - } - public int StrideInBytes { - get { - ValueWitnessTable vat = WitnessTable.ValueWitnessTable; - return vat != null ? (int)vat.Stride : 0; - } - } - } + public int SizeInBytes + { + get + { + ValueWitnessTable vat = WitnessTable.ValueWitnessTable; + return vat != null ? (int)vat.Size : 0; + } + } + public int StrideInBytes + { + get + { + ValueWitnessTable vat = WitnessTable.ValueWitnessTable; + return vat != null ? (int)vat.Stride : 0; + } + } + } } diff --git a/src/SwiftReflector/Inventory/ClassInventory.cs b/src/SwiftReflector/Inventory/ClassInventory.cs index 588ce06260b3..0fb8c7b3af96 100644 --- a/src/SwiftReflector/Inventory/ClassInventory.cs +++ b/src/SwiftReflector/Inventory/ClassInventory.cs @@ -6,60 +6,69 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class ClassInventory : Inventory { - int sizeofMachinePointer; - public ClassInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } +namespace SwiftReflector.Inventory +{ + public class ClassInventory : Inventory + { + int sizeofMachinePointer; + public ClassInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } - public override void Add (TLDefinition tld, Stream srcStm) - { - // ignoring these - we don't/can't use them - if (tld is TLDefaultArgumentInitializer) - return; - SwiftName className = ToClassName (tld); - SwiftClassName formalName = ToFormalClassName (tld); - lock (valuesLock) { - ClassContents contents = null; - if (!values.TryGetValue (className, out contents)) { - contents = new ClassContents (formalName, sizeofMachinePointer); - values.Add (className, contents); - } - contents.Add (tld, srcStm); - } - } + public override void Add(TLDefinition tld, Stream srcStm) + { + // ignoring these - we don't/can't use them + if (tld is TLDefaultArgumentInitializer) + return; + SwiftName className = ToClassName(tld); + SwiftClassName formalName = ToFormalClassName(tld); + lock (valuesLock) + { + ClassContents contents = null; + if (!values.TryGetValue(className, out contents)) + { + contents = new ClassContents(formalName, sizeofMachinePointer); + values.Add(className, contents); + } + contents.Add(tld, srcStm); + } + } - public static SwiftClassName ToFormalClassName (TLDefinition tld) - { - TLClassElem elem = tld as TLClassElem; - if (elem != null) { - if (elem.Class == null) - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 2, $"Expected a top level definition to have a class name."); - return elem.Class.ClassName; - } - if (tld is TLProtocolConformanceDescriptor protocolDesc) { - if (protocolDesc.ImplementingType is SwiftClassType swiftClass) - return swiftClass.ClassName; - if (protocolDesc.ImplementingType is SwiftBoundGenericType boundGen) { - var baseType = boundGen.BaseType as SwiftClassType; - if (baseType != null) - return baseType.ClassName; - } else if (protocolDesc.ImplementingType is SwiftBuiltInType builtInType) { - return SwiftClassName.FromFullyQualifiedName ($"Swift.{builtInType.BuiltInType}", OperatorType.None, "V"); - } - } + public static SwiftClassName ToFormalClassName(TLDefinition tld) + { + TLClassElem elem = tld as TLClassElem; + if (elem != null) + { + if (elem.Class == null) + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 2, $"Expected a top level definition to have a class name."); + return elem.Class.ClassName; + } + if (tld is TLProtocolConformanceDescriptor protocolDesc) + { + if (protocolDesc.ImplementingType is SwiftClassType swiftClass) + return swiftClass.ClassName; + if (protocolDesc.ImplementingType is SwiftBoundGenericType boundGen) + { + var baseType = boundGen.BaseType as SwiftClassType; + if (baseType != null) + return baseType.ClassName; + } + else if (protocolDesc.ImplementingType is SwiftBuiltInType builtInType) + { + return SwiftClassName.FromFullyQualifiedName($"Swift.{builtInType.BuiltInType}", OperatorType.None, "V"); + } + } - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 0, $"unknown top level definition {tld.GetType ().Name}"); - } + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 0, $"unknown top level definition {tld.GetType().Name}"); + } - public static SwiftName ToClassName (TLDefinition tld) - { - SwiftClassName cln = ToFormalClassName (tld); - return new SwiftName (cln.ToFullyQualifiedName (), false); - } - } + public static SwiftName ToClassName(TLDefinition tld) + { + SwiftClassName cln = ToFormalClassName(tld); + return new SwiftName(cln.ToFullyQualifiedName(), false); + } + } } diff --git a/src/SwiftReflector/Inventory/FunctionInventory.cs b/src/SwiftReflector/Inventory/FunctionInventory.cs index 129d57f6a087..9df5858a7840 100644 --- a/src/SwiftReflector/Inventory/FunctionInventory.cs +++ b/src/SwiftReflector/Inventory/FunctionInventory.cs @@ -8,104 +8,112 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class FunctionInventory : Inventory { - int sizeofMachinePointer; - public FunctionInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - public override void Add (TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 10, $"expected a top-level function but got a {tld.GetType ().Name}"); +namespace SwiftReflector.Inventory +{ + public class FunctionInventory : Inventory + { + int sizeofMachinePointer; + public FunctionInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + public override void Add(TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 10, $"expected a top-level function but got a {tld.GetType().Name}"); - lock (valuesLock) { - OverloadInventory overloads = null; - if (!values.TryGetValue (tlf.Name, out overloads)) { - overloads = new OverloadInventory (tlf.Name, sizeofMachinePointer); - values.Add (tlf.Name, overloads); - } - overloads.Add (tlf, srcStm); - } - } + lock (valuesLock) + { + OverloadInventory overloads = null; + if (!values.TryGetValue(tlf.Name, out overloads)) + { + overloads = new OverloadInventory(tlf.Name, sizeofMachinePointer); + values.Add(tlf.Name, overloads); + } + overloads.Add(tlf, srcStm); + } + } - public TLFunction ContainsEquivalentFunction (TLFunction func) - { - // for finding a func with the same name and signature which may or may not be a thunk - var nameMatched = MethodsWithName (func.Signature.Name); - if (nameMatched.Count == 0) - return null; - foreach (var candidate in nameMatched) { - if (ArgumentsMatch (candidate, func) && ReturnsMatch (candidate, func) && candidate.Signature.CanThrow == func.Signature.CanThrow) - return candidate; - } - return null; - } + public TLFunction ContainsEquivalentFunction(TLFunction func) + { + // for finding a func with the same name and signature which may or may not be a thunk + var nameMatched = MethodsWithName(func.Signature.Name); + if (nameMatched.Count == 0) + return null; + foreach (var candidate in nameMatched) + { + if (ArgumentsMatch(candidate, func) && ReturnsMatch(candidate, func) && candidate.Signature.CanThrow == func.Signature.CanThrow) + return candidate; + } + return null; + } - public void ReplaceFunction (TLFunction original, TLFunction replacement) - { - var overloads = values [original.Name]; - if (overloads == null) - throw new ArgumentException ("original function name must be in the inventory"); - if (!overloads.Functions.Remove (original)) - throw new ArgumentException ("original function not found"); - overloads.Functions.Add (replacement); - } + public void ReplaceFunction(TLFunction original, TLFunction replacement) + { + var overloads = values[original.Name]; + if (overloads == null) + throw new ArgumentException("original function name must be in the inventory"); + if (!overloads.Functions.Remove(original)) + throw new ArgumentException("original function not found"); + overloads.Functions.Add(replacement); + } - static bool ArgumentsMatch (TLFunction candidate, TLFunction func) - { - if (candidate.Signature.ParameterCount != func.Signature.ParameterCount) - return false; + static bool ArgumentsMatch(TLFunction candidate, TLFunction func) + { + if (candidate.Signature.ParameterCount != func.Signature.ParameterCount) + return false; - for (int i = 0; i < candidate.Signature.ParameterCount; i++) { - if (!candidate.Signature.GetParameter (i).Equals (func.Signature.GetParameter (i))) - return false; - } - return true; - } + for (int i = 0; i < candidate.Signature.ParameterCount; i++) + { + if (!candidate.Signature.GetParameter(i).Equals(func.Signature.GetParameter(i))) + return false; + } + return true; + } - static bool ReturnsMatch (TLFunction candidate, TLFunction func) - { - return candidate.Signature.ReturnType.Equals (func.Signature.ReturnType); - } + static bool ReturnsMatch(TLFunction candidate, TLFunction func) + { + return candidate.Signature.ReturnType.Equals(func.Signature.ReturnType); + } - public IEnumerable> AllMethodsNoCDTor () - { - foreach (SwiftName key in values.Keys) { - OverloadInventory oi = values [key]; - foreach (TLFunction tlf in oi.Functions) - yield return new Tuple (key, tlf); - } - } + public IEnumerable> AllMethodsNoCDTor() + { + foreach (SwiftName key in values.Keys) + { + OverloadInventory oi = values[key]; + foreach (TLFunction tlf in oi.Functions) + yield return new Tuple(key, tlf); + } + } - public List MethodsWithName (SwiftName name) - { - var result = new List (); - foreach (var oi in Values) { - if (oi.Name.Name == name.Name) - result.AddRange (oi.Functions); - } - return result; - } + public List MethodsWithName(SwiftName name) + { + var result = new List(); + foreach (var oi in Values) + { + if (oi.Name.Name == name.Name) + result.AddRange(oi.Functions); + } + return result; + } - public List MethodsWithName (string name) - { - SwiftName sn = new SwiftName (name, false); - return MethodsWithName (sn); - } + public List MethodsWithName(string name) + { + SwiftName sn = new SwiftName(name, false); + return MethodsWithName(sn); + } - public List AllocatingConstructors () - { - return MethodsWithName (Decomposer.kSwiftAllocatingConstructorName); - } + public List AllocatingConstructors() + { + return MethodsWithName(Decomposer.kSwiftAllocatingConstructorName); + } - public List DeallocatingDestructors () - { - return MethodsWithName (Decomposer.kSwiftDeallocatingDestructorName); - } - } + public List DeallocatingDestructors() + { + return MethodsWithName(Decomposer.kSwiftDeallocatingDestructorName); + } + } } diff --git a/src/SwiftReflector/Inventory/Inventory.cs b/src/SwiftReflector/Inventory/Inventory.cs index cc75f6f82f74..764ab6d94f51 100644 --- a/src/SwiftReflector/Inventory/Inventory.cs +++ b/src/SwiftReflector/Inventory/Inventory.cs @@ -6,38 +6,42 @@ using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public abstract class Inventory { - protected object valuesLock = new object (); - protected Dictionary values = new Dictionary (); - - public IEnumerable Names { get { return values.Keys; } } - public IEnumerable Values { get { return values.Values; } } - - public abstract void Add (TLDefinition tlf, Stream srcStm); - - public bool ContainsName (SwiftName name) - { - lock (valuesLock) { - return values.ContainsKey (name); - } - } - public bool ContainsName (string name) - { - return ContainsName (new SwiftName (name, false)); - } - - public bool TryGetValue (SwiftName name, out T value) - { - lock (valuesLock) { - return values.TryGetValue (name, out value); - } - } - - public bool TryGetValue (string name, out T value) - { - return TryGetValue (new SwiftName (name, false), out value); - } - } +namespace SwiftReflector.Inventory +{ + public abstract class Inventory + { + protected object valuesLock = new object(); + protected Dictionary values = new Dictionary(); + + public IEnumerable Names { get { return values.Keys; } } + public IEnumerable Values { get { return values.Values; } } + + public abstract void Add(TLDefinition tlf, Stream srcStm); + + public bool ContainsName(SwiftName name) + { + lock (valuesLock) + { + return values.ContainsKey(name); + } + } + public bool ContainsName(string name) + { + return ContainsName(new SwiftName(name, false)); + } + + public bool TryGetValue(SwiftName name, out T value) + { + lock (valuesLock) + { + return values.TryGetValue(name, out value); + } + } + + public bool TryGetValue(string name, out T value) + { + return TryGetValue(new SwiftName(name, false), out value); + } + } } diff --git a/src/SwiftReflector/Inventory/ModuleContents.cs b/src/SwiftReflector/Inventory/ModuleContents.cs index 172fb3c7e19b..18310067331e 100644 --- a/src/SwiftReflector/Inventory/ModuleContents.cs +++ b/src/SwiftReflector/Inventory/ModuleContents.cs @@ -7,86 +7,116 @@ using SwiftReflector.Demangling; using SwiftRuntimeLibrary; -namespace SwiftReflector.Inventory { - public class ModuleContents { - public ModuleContents (SwiftName name, int sizeofMachinePointer) - { - Name = Exceptions.ThrowOnNull (name, nameof(name)); - Classes = new ClassInventory (sizeofMachinePointer); - Functions = new FunctionInventory (sizeofMachinePointer); - Variables = new VariableInventory (sizeofMachinePointer); - WitnessTables = new WitnessInventory (sizeofMachinePointer); - Protocols = new ProtocolInventory (sizeofMachinePointer); - Extensions = new FunctionInventory (sizeofMachinePointer); - MetadataFieldDescriptor = new List (); - MetadataBuiltInDescriptor = new List (); - PropertyDescriptors = new VariableInventory (sizeofMachinePointer); - ExtensionDescriptors = new List (); - } +namespace SwiftReflector.Inventory +{ + public class ModuleContents + { + public ModuleContents(SwiftName name, int sizeofMachinePointer) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + Classes = new ClassInventory(sizeofMachinePointer); + Functions = new FunctionInventory(sizeofMachinePointer); + Variables = new VariableInventory(sizeofMachinePointer); + WitnessTables = new WitnessInventory(sizeofMachinePointer); + Protocols = new ProtocolInventory(sizeofMachinePointer); + Extensions = new FunctionInventory(sizeofMachinePointer); + MetadataFieldDescriptor = new List(); + MetadataBuiltInDescriptor = new List(); + PropertyDescriptors = new VariableInventory(sizeofMachinePointer); + ExtensionDescriptors = new List(); + } - public void Add (TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) { - if (tlf.Signature.IsExtension) { - Extensions.Add (tlf, srcStm); - } else if (tlf.IsTopLevelFunction) { - if (tlf.Signature is SwiftAddressorType) { - Variables.Add (tlf, srcStm); - } else if (tlf.Signature is SwiftWitnessTableType) { - WitnessTables.Add (tld, srcStm); - } else { - Functions.Add (tlf, srcStm); - } - } else { - if (tlf.Class.EntityKind == MemberNesting.Protocol) { - Protocols.Add (tlf, srcStm); - } else { - Classes.Add (tld, srcStm); - } - } - } else { - if (tld is TLVariable tlvar && ((TLVariable)tld).Class == null) { - if (tlvar is TLPropertyDescriptor propDesc) { - if (propDesc.ExtensionOn != null) - ExtensionDescriptors.Add (propDesc); - else - PropertyDescriptors.Add (tlvar, srcStm); - } else { - Variables.Add (tld, srcStm); - } - } else if (tld is TLProtocolTypeDescriptor || tld is TLProtocolRequirementsBaseDescriptor) { - Protocols.Add (tld, srcStm); - } else if (tld is TLModuleDescriptor module) { - ModuleDescriptor = module; - } else if (tld is TLMetadataDescriptor metadata) { - if (metadata.IsBuiltIn) - MetadataBuiltInDescriptor.Add (metadata); - else - MetadataFieldDescriptor.Add (metadata); - } else { - // global unsafe mutable addressors get ignored. We don't need/use them. - if (tld is TLUnsafeMutableAddressor addressor && addressor.Class == null) - return; - Classes.Add (tld, srcStm); - } - } - } + public void Add(TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) + { + if (tlf.Signature.IsExtension) + { + Extensions.Add(tlf, srcStm); + } + else if (tlf.IsTopLevelFunction) + { + if (tlf.Signature is SwiftAddressorType) + { + Variables.Add(tlf, srcStm); + } + else if (tlf.Signature is SwiftWitnessTableType) + { + WitnessTables.Add(tld, srcStm); + } + else + { + Functions.Add(tlf, srcStm); + } + } + else + { + if (tlf.Class.EntityKind == MemberNesting.Protocol) + { + Protocols.Add(tlf, srcStm); + } + else + { + Classes.Add(tld, srcStm); + } + } + } + else + { + if (tld is TLVariable tlvar && ((TLVariable)tld).Class == null) + { + if (tlvar is TLPropertyDescriptor propDesc) + { + if (propDesc.ExtensionOn != null) + ExtensionDescriptors.Add(propDesc); + else + PropertyDescriptors.Add(tlvar, srcStm); + } + else + { + Variables.Add(tld, srcStm); + } + } + else if (tld is TLProtocolTypeDescriptor || tld is TLProtocolRequirementsBaseDescriptor) + { + Protocols.Add(tld, srcStm); + } + else if (tld is TLModuleDescriptor module) + { + ModuleDescriptor = module; + } + else if (tld is TLMetadataDescriptor metadata) + { + if (metadata.IsBuiltIn) + MetadataBuiltInDescriptor.Add(metadata); + else + MetadataFieldDescriptor.Add(metadata); + } + else + { + // global unsafe mutable addressors get ignored. We don't need/use them. + if (tld is TLUnsafeMutableAddressor addressor && addressor.Class == null) + return; + Classes.Add(tld, srcStm); + } + } + } - public TLModuleDescriptor ModuleDescriptor { get; private set; } - public SwiftName Name { get; private set; } + public TLModuleDescriptor ModuleDescriptor { get; private set; } + public SwiftName Name { get; private set; } - public WitnessInventory WitnessTables { get; private set; } - public ProtocolInventory Protocols { get; private set; } - public ClassInventory Classes { get; private set; } - public FunctionInventory Functions { get; private set; } - public VariableInventory Variables { get; private set; } - public VariableInventory PropertyDescriptors { get; private set; } - public List ExtensionDescriptors { get; private set; } - public FunctionInventory Extensions { get; private set; } - public List MetadataFieldDescriptor { get; private set; } - public List MetadataBuiltInDescriptor { get; private set; } - } + public WitnessInventory WitnessTables { get; private set; } + public ProtocolInventory Protocols { get; private set; } + public ClassInventory Classes { get; private set; } + public FunctionInventory Functions { get; private set; } + public VariableInventory Variables { get; private set; } + public VariableInventory PropertyDescriptors { get; private set; } + public List ExtensionDescriptors { get; private set; } + public FunctionInventory Extensions { get; private set; } + public List MetadataFieldDescriptor { get; private set; } + public List MetadataBuiltInDescriptor { get; private set; } + } } diff --git a/src/SwiftReflector/Inventory/ModuleInventory.cs b/src/SwiftReflector/Inventory/ModuleInventory.cs index 2362ba80603a..54e493e7d35c 100644 --- a/src/SwiftReflector/Inventory/ModuleInventory.cs +++ b/src/SwiftReflector/Inventory/ModuleInventory.cs @@ -12,153 +12,183 @@ using SwiftRuntimeLibrary; using System.Threading.Tasks; -namespace SwiftReflector.Inventory { - public class ModuleInventory : Inventory { - public MachO.Architectures Architecture { get; private set; } - public int SizeofMachinePointer { - get { - return Architecture == MachO.Architectures.x86_64 || - Architecture == MachO.Architectures.ARM64 ? 8 : 4; - } - } - - public override void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - ModuleContents module = null; - if (!values.TryGetValue (tld.Module, out module)) { - module = new ModuleContents (tld.Module, SizeofMachinePointer); - values.Add (tld.Module, module); - } - module.Add (tld, srcStm); - } - } - - public static ModuleInventory FromFile (string pathToDynamicLibrary, ErrorHandling errors) - { - Exceptions.ThrowOnNull (pathToDynamicLibrary, nameof(pathToDynamicLibrary)); - FileStream stm = null; - try { - stm = new FileStream (pathToDynamicLibrary, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - } catch (Exception e) { - Console.WriteLine (e.Message); - errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 57, e, "unable to open file {0}: {1}\n", pathToDynamicLibrary, e.Message)); - } - try { - return FromStream (stm, errors, pathToDynamicLibrary); - } finally { - stm.Dispose (); - } - } - - public static async Task FromFilesAsync (IEnumerable pathsToLibraryFiles, ErrorHandling errors) - { - var streams = pathsToLibraryFiles.Select (path => new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)).ToList (); - if (streams.Count == 0) - return null; - var inventory = new ModuleInventory (); - try { - var tasks = streams.Select (stm => FromStreamIntoAsync (stm, inventory, errors, stm.Name)); - await Task.WhenAll (tasks); - } finally { - foreach (var stm in streams) { - stm.Dispose (); - } - } - return inventory; - } - - public static ModuleInventory FromFiles (IEnumerable pathsToLibraryFiles, ErrorHandling errors) - { - ModuleInventory inventory = null; - foreach (string path in pathsToLibraryFiles) { - if (inventory == null) - inventory = new ModuleInventory (); - using (FileStream stm = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)) { - FromStreamInto (stm, inventory, errors, path); - } - } - return inventory; - } - - static async Task FromStreamIntoAsync (Stream stm, ModuleInventory inventory, - ErrorHandling errors, string fileName = null) - { - return await Task.Run (() => { - return FromStreamInto (stm, inventory, errors, fileName); - }); - } - - static ModuleInventory FromStreamInto (Stream stm, ModuleInventory inventory, - ErrorHandling errors, string fileName = null) - { - // Exceptions.ThrowOnNull (errors, "errors"); - Exceptions.ThrowOnNull (stm, "stm"); - OffsetStream osstm = null; - List entries = null; - try { - List macho = MachO.Read (stm, null).ToList (); - MachOFile file = macho [0]; - - List symbols = file.load_commands.OfType ().ToList (); - NListEntryType nlet = symbols [0].nlist [0].EntryType; - entries = symbols [0].nlist. - Where ((nle, i) => nle.IsPublic && nle.EntryType == NListEntryType.InSection).ToList (); - inventory.Architecture = file.Architecture; - osstm = new OffsetStream (stm, file.StartOffset); - } catch (Exception e) { - errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 58, e, "Unable to retrieve functions from {0}: {1}", - fileName ?? "stream", e.Message)); - return inventory; - } - - bool isOldVersion = IsOldVersion (entries); - - foreach (var entry in entries) { - if (!entry.IsSwiftEntryPoint ()) - continue; - TLDefinition def = null; - def = Decomposer.Decompose (entry.str, isOldVersion, Offset (entry)); - if (def != null) { - // this skips over privatized names - var tlf = def as TLFunction; - if (tlf != null && tlf.Name != null && tlf.Name.Name.Contains ("...")) - continue; - try { - inventory.Add (def, osstm); - } catch (RuntimeException e) { - e = new RuntimeException (e.Code, e.Error, $"error dispensing top level definition of type {def.GetType ().Name} decomposed from {entry.str}: {e.Message}"); - errors.Add (e); - } - } else { - var ex = ErrorHelper.CreateWarning (ReflectorError.kInventoryBase + 18, $"entry {entry.str} uses an unsupported swift feature, skipping."); - errors.Add (ex); - } - } - - return inventory; - } - - public static ModuleInventory FromStream (Stream stm, ErrorHandling errors, string fileName = null) - { - ModuleInventory inventory = new ModuleInventory (); - return FromStreamInto (stm, inventory, errors, fileName); - } - - static ulong Offset (NListEntry entry) - { - NListEntry32 nl32 = entry as NListEntry32; - return nl32 != null ? nl32.n_value : ((NListEntry64)entry).n_value; - } - - static bool IsOldVersion (List entries) - { - foreach (NListEntry entry in entries) { - if (entry.str.StartsWith ("__TMd", StringComparison.Ordinal)) - return true; - } - return false; - } - } +namespace SwiftReflector.Inventory +{ + public class ModuleInventory : Inventory + { + public MachO.Architectures Architecture { get; private set; } + public int SizeofMachinePointer + { + get + { + return Architecture == MachO.Architectures.x86_64 || + Architecture == MachO.Architectures.ARM64 ? 8 : 4; + } + } + + public override void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + ModuleContents module = null; + if (!values.TryGetValue(tld.Module, out module)) + { + module = new ModuleContents(tld.Module, SizeofMachinePointer); + values.Add(tld.Module, module); + } + module.Add(tld, srcStm); + } + } + + public static ModuleInventory FromFile(string pathToDynamicLibrary, ErrorHandling errors) + { + Exceptions.ThrowOnNull(pathToDynamicLibrary, nameof(pathToDynamicLibrary)); + FileStream stm = null; + try + { + stm = new FileStream(pathToDynamicLibrary, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 57, e, "unable to open file {0}: {1}\n", pathToDynamicLibrary, e.Message)); + } + try + { + return FromStream(stm, errors, pathToDynamicLibrary); + } + finally + { + stm.Dispose(); + } + } + + public static async Task FromFilesAsync(IEnumerable pathsToLibraryFiles, ErrorHandling errors) + { + var streams = pathsToLibraryFiles.Select(path => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)).ToList(); + if (streams.Count == 0) + return null; + var inventory = new ModuleInventory(); + try + { + var tasks = streams.Select(stm => FromStreamIntoAsync(stm, inventory, errors, stm.Name)); + await Task.WhenAll(tasks); + } + finally + { + foreach (var stm in streams) + { + stm.Dispose(); + } + } + return inventory; + } + + public static ModuleInventory FromFiles(IEnumerable pathsToLibraryFiles, ErrorHandling errors) + { + ModuleInventory inventory = null; + foreach (string path in pathsToLibraryFiles) + { + if (inventory == null) + inventory = new ModuleInventory(); + using (FileStream stm = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + FromStreamInto(stm, inventory, errors, path); + } + } + return inventory; + } + + static async Task FromStreamIntoAsync(Stream stm, ModuleInventory inventory, + ErrorHandling errors, string fileName = null) + { + return await Task.Run(() => + { + return FromStreamInto(stm, inventory, errors, fileName); + }); + } + + static ModuleInventory FromStreamInto(Stream stm, ModuleInventory inventory, + ErrorHandling errors, string fileName = null) + { + // Exceptions.ThrowOnNull (errors, "errors"); + Exceptions.ThrowOnNull(stm, "stm"); + OffsetStream osstm = null; + List entries = null; + try + { + List macho = MachO.Read(stm, null).ToList(); + MachOFile file = macho[0]; + + List symbols = file.load_commands.OfType().ToList(); + NListEntryType nlet = symbols[0].nlist[0].EntryType; + entries = symbols[0].nlist. + Where((nle, i) => nle.IsPublic && nle.EntryType == NListEntryType.InSection).ToList(); + inventory.Architecture = file.Architecture; + osstm = new OffsetStream(stm, file.StartOffset); + } + catch (Exception e) + { + errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 58, e, "Unable to retrieve functions from {0}: {1}", + fileName ?? "stream", e.Message)); + return inventory; + } + + bool isOldVersion = IsOldVersion(entries); + + foreach (var entry in entries) + { + if (!entry.IsSwiftEntryPoint()) + continue; + TLDefinition def = null; + def = Decomposer.Decompose(entry.str, isOldVersion, Offset(entry)); + if (def != null) + { + // this skips over privatized names + var tlf = def as TLFunction; + if (tlf != null && tlf.Name != null && tlf.Name.Name.Contains("...")) + continue; + try + { + inventory.Add(def, osstm); + } + catch (RuntimeException e) + { + e = new RuntimeException(e.Code, e.Error, $"error dispensing top level definition of type {def.GetType().Name} decomposed from {entry.str}: {e.Message}"); + errors.Add(e); + } + } + else + { + var ex = ErrorHelper.CreateWarning(ReflectorError.kInventoryBase + 18, $"entry {entry.str} uses an unsupported swift feature, skipping."); + errors.Add(ex); + } + } + + return inventory; + } + + public static ModuleInventory FromStream(Stream stm, ErrorHandling errors, string fileName = null) + { + ModuleInventory inventory = new ModuleInventory(); + return FromStreamInto(stm, inventory, errors, fileName); + } + + static ulong Offset(NListEntry entry) + { + NListEntry32 nl32 = entry as NListEntry32; + return nl32 != null ? nl32.n_value : ((NListEntry64)entry).n_value; + } + + static bool IsOldVersion(List entries) + { + foreach (NListEntry entry in entries) + { + if (entry.str.StartsWith("__TMd", StringComparison.Ordinal)) + return true; + } + return false; + } + } } diff --git a/src/SwiftReflector/Inventory/OverloadInventory.cs b/src/SwiftReflector/Inventory/OverloadInventory.cs index addf401bb00e..aea92806ad8e 100644 --- a/src/SwiftReflector/Inventory/OverloadInventory.cs +++ b/src/SwiftReflector/Inventory/OverloadInventory.cs @@ -8,35 +8,41 @@ using SwiftReflector.Demangling; using SwiftRuntimeLibrary; -namespace SwiftReflector.Inventory { - public class OverloadInventory : Inventory> { - int sizeofMachinePointer; - public OverloadInventory (SwiftName name, int sizeofMachinePointer) - { - Name = Exceptions.ThrowOnNull (name, nameof(name)); - Functions = new List (); - this.sizeofMachinePointer = sizeofMachinePointer; - } +namespace SwiftReflector.Inventory +{ + public class OverloadInventory : Inventory> + { + int sizeofMachinePointer; + public OverloadInventory(SwiftName name, int sizeofMachinePointer) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + Functions = new List(); + this.sizeofMachinePointer = sizeofMachinePointer; + } - public override void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 11, $"expected a top-level function but got a {tld.GetType ().Name}"); - if (Functions.Exists (f => tlf.MangledName == f.MangledName)) { - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 12, $"duplicate function found for {tlf.MangledName}"); - } else { - Functions.Add (tlf); - } - } - } + public override void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 11, $"expected a top-level function but got a {tld.GetType().Name}"); + if (Functions.Exists(f => tlf.MangledName == f.MangledName)) + { + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 12, $"duplicate function found for {tlf.MangledName}"); + } + else + { + Functions.Add(tlf); + } + } + } - public List Functions { get; private set; } + public List Functions { get; private set; } - public SwiftName Name { get; private set; } - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } + public SwiftName Name { get; private set; } + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } } diff --git a/src/SwiftReflector/Inventory/PropertyContents.cs b/src/SwiftReflector/Inventory/PropertyContents.cs index dd5909510655..3c25cc0ccf12 100644 --- a/src/SwiftReflector/Inventory/PropertyContents.cs +++ b/src/SwiftReflector/Inventory/PropertyContents.cs @@ -6,184 +6,214 @@ using SwiftReflector.Demangling; using SwiftRuntimeLibrary; -namespace SwiftReflector.Inventory { - public class PropertyContents { - int sizeofMachinePointer; - public PropertyContents (SwiftClassType ofClass, SwiftName propName, int sizeofMachinePointer) - { - Class = Exceptions.ThrowOnNull (ofClass, nameof(ofClass)); - Name = Exceptions.ThrowOnNull (propName, nameof(propName)); - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public SwiftClassType Class { get; private set; } - - public SwiftName Name { get; private set; } - - public void Add (TLFunction tlf, SwiftPropertyType prop) - { - var method = tlf as TLMethodDescriptor; - if (method != null) { - switch (prop.PropertyType) { - case PropertyType.Getter: - TLFGetterDescriptor = method; - break; - case PropertyType.Setter: - TLFSetterDescriptor = method; - break; - case PropertyType.Materializer: - TLFMaterializerDescriptor = method; - break; - case PropertyType.DidSet: - TLFDidSetDescriptor = method; - break; - case PropertyType.WillSet: - TLFWillSetDescriptor = method; - break; - case PropertyType.ModifyAccessor: - TLFModifyDescriptor = method; - break; - default: - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 68, $"Unexpected property descriptor {prop.PropertyType.ToString ()}"); - } - } else { - switch (prop.PropertyType) { - case PropertyType.Getter: - var oldget = Getter; - Getter = ConditionalChainThunk (prop, oldget); - TLFGetter = oldget == null || Getter != prop ? tlf : TLFGetter; - break; - case PropertyType.Setter: - var oldset = Setter; - Setter = ConditionalChainThunk (prop, oldset); - TLFSetter = oldset == null || Setter != prop ? tlf : TLFSetter; - break; - case PropertyType.Materializer: - var oldmaterialize = Materializer; - Materializer = ConditionalChainThunk (prop, oldmaterialize); - TLFMaterializer = oldmaterialize == null || Materializer != prop ? tlf : TLFMaterializer; - break; - case PropertyType.DidSet: - var olddidset = DidSet; - DidSet = ConditionalChainThunk (prop, olddidset); - TLFDidSet = olddidset == null || DidSet != prop ? tlf : TLFDidSet; - break; - case PropertyType.WillSet: - var oldwillset = WillSet; - WillSet = ConditionalChainThunk (prop, oldwillset); - TLFWillSet = oldwillset == null || WillSet != prop ? tlf : TLFWillSet; - break; - case PropertyType.ModifyAccessor: - var oldmodify = WillSet; - ModifyAccessor = ConditionalChainThunk (prop, oldmodify); - TLFModifyAccessor = oldmodify == null || ModifyAccessor != prop ? tlf : TLFModifyAccessor; - break; - default: - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 2, $"Unexpected property element {prop.PropertyType.ToString ()}"); - } - } - } - - static SwiftPropertyType ConditionalChainThunk (SwiftPropertyType newProp, SwiftPropertyType oldProp) - { - if (oldProp == null) { - return newProp; - } - if (oldProp.IsThunk) { - newProp.Thunk = oldProp; - return newProp; - } else if (newProp.IsThunk) { - oldProp.Thunk = newProp; - return oldProp; - } else { - throw new NotImplementedException ("At least one needs to be a thunk - should never happen"); - } - } - - SwiftPropertyType getter; - public SwiftPropertyType Getter { - get { - return getter; - } - set { - ThrowOnExistingProperty (getter, "getter"); - getter = value; - } - } - public TLFunction TLFGetter { get; set; } - public TLMethodDescriptor TLFGetterDescriptor { get; set; } - - SwiftPropertyType setter; - public SwiftPropertyType Setter { - get { - return setter; - } - set { - ThrowOnExistingProperty (setter, "setter"); - setter = value; - } - } - public TLFunction TLFSetter { get; set; } - public TLMethodDescriptor TLFSetterDescriptor { get; set; } - - SwiftPropertyType materializer; - public SwiftPropertyType Materializer { - get { - return materializer; - } - set { - ThrowOnExistingProperty (materializer, "materializer"); - materializer = value; - } - } - public TLFunction TLFMaterializer { get; set; } - public TLMethodDescriptor TLFMaterializerDescriptor { get; set; } - - SwiftPropertyType modifyAccessor; - public SwiftPropertyType ModifyAccessor { - get { return modifyAccessor; } - set { - ThrowOnExistingProperty (modifyAccessor, "modifyAccessor"); - modifyAccessor = value; - } - } - public TLFunction TLFModifyAccessor { get; set; } - public TLMethodDescriptor TLFModifyDescriptor { get; set; } - - SwiftPropertyType didSet; - public SwiftPropertyType DidSet { - get { - return didSet; - } - set { - ThrowOnExistingProperty (didSet, "did set"); - didSet = value; - } - } - public TLFunction TLFDidSet { get; set; } - public TLMethodDescriptor TLFDidSetDescriptor { get; set; } - - SwiftPropertyType willSet; - public SwiftPropertyType WillSet { - get { - return willSet; - } - set { - ThrowOnExistingProperty (willSet, "will set"); - willSet = value; - } - } - public TLFunction TLFWillSet { get; set; } - public TLMethodDescriptor TLFWillSetDescriptor { get; set; } - - void ThrowOnExistingProperty (SwiftPropertyType prop, string propType) - { - if (prop != null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 6, $"Already have a {propType} entry for property {Name} in {Class.ClassName.ToFullyQualifiedName ()}"); - } - - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } +namespace SwiftReflector.Inventory +{ + public class PropertyContents + { + int sizeofMachinePointer; + public PropertyContents(SwiftClassType ofClass, SwiftName propName, int sizeofMachinePointer) + { + Class = Exceptions.ThrowOnNull(ofClass, nameof(ofClass)); + Name = Exceptions.ThrowOnNull(propName, nameof(propName)); + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public SwiftClassType Class { get; private set; } + + public SwiftName Name { get; private set; } + + public void Add(TLFunction tlf, SwiftPropertyType prop) + { + var method = tlf as TLMethodDescriptor; + if (method != null) + { + switch (prop.PropertyType) + { + case PropertyType.Getter: + TLFGetterDescriptor = method; + break; + case PropertyType.Setter: + TLFSetterDescriptor = method; + break; + case PropertyType.Materializer: + TLFMaterializerDescriptor = method; + break; + case PropertyType.DidSet: + TLFDidSetDescriptor = method; + break; + case PropertyType.WillSet: + TLFWillSetDescriptor = method; + break; + case PropertyType.ModifyAccessor: + TLFModifyDescriptor = method; + break; + default: + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 68, $"Unexpected property descriptor {prop.PropertyType.ToString()}"); + } + } + else + { + switch (prop.PropertyType) + { + case PropertyType.Getter: + var oldget = Getter; + Getter = ConditionalChainThunk(prop, oldget); + TLFGetter = oldget == null || Getter != prop ? tlf : TLFGetter; + break; + case PropertyType.Setter: + var oldset = Setter; + Setter = ConditionalChainThunk(prop, oldset); + TLFSetter = oldset == null || Setter != prop ? tlf : TLFSetter; + break; + case PropertyType.Materializer: + var oldmaterialize = Materializer; + Materializer = ConditionalChainThunk(prop, oldmaterialize); + TLFMaterializer = oldmaterialize == null || Materializer != prop ? tlf : TLFMaterializer; + break; + case PropertyType.DidSet: + var olddidset = DidSet; + DidSet = ConditionalChainThunk(prop, olddidset); + TLFDidSet = olddidset == null || DidSet != prop ? tlf : TLFDidSet; + break; + case PropertyType.WillSet: + var oldwillset = WillSet; + WillSet = ConditionalChainThunk(prop, oldwillset); + TLFWillSet = oldwillset == null || WillSet != prop ? tlf : TLFWillSet; + break; + case PropertyType.ModifyAccessor: + var oldmodify = WillSet; + ModifyAccessor = ConditionalChainThunk(prop, oldmodify); + TLFModifyAccessor = oldmodify == null || ModifyAccessor != prop ? tlf : TLFModifyAccessor; + break; + default: + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 2, $"Unexpected property element {prop.PropertyType.ToString()}"); + } + } + } + + static SwiftPropertyType ConditionalChainThunk(SwiftPropertyType newProp, SwiftPropertyType oldProp) + { + if (oldProp == null) + { + return newProp; + } + if (oldProp.IsThunk) + { + newProp.Thunk = oldProp; + return newProp; + } + else if (newProp.IsThunk) + { + oldProp.Thunk = newProp; + return oldProp; + } + else + { + throw new NotImplementedException("At least one needs to be a thunk - should never happen"); + } + } + + SwiftPropertyType getter; + public SwiftPropertyType Getter + { + get + { + return getter; + } + set + { + ThrowOnExistingProperty(getter, "getter"); + getter = value; + } + } + public TLFunction TLFGetter { get; set; } + public TLMethodDescriptor TLFGetterDescriptor { get; set; } + + SwiftPropertyType setter; + public SwiftPropertyType Setter + { + get + { + return setter; + } + set + { + ThrowOnExistingProperty(setter, "setter"); + setter = value; + } + } + public TLFunction TLFSetter { get; set; } + public TLMethodDescriptor TLFSetterDescriptor { get; set; } + + SwiftPropertyType materializer; + public SwiftPropertyType Materializer + { + get + { + return materializer; + } + set + { + ThrowOnExistingProperty(materializer, "materializer"); + materializer = value; + } + } + public TLFunction TLFMaterializer { get; set; } + public TLMethodDescriptor TLFMaterializerDescriptor { get; set; } + + SwiftPropertyType modifyAccessor; + public SwiftPropertyType ModifyAccessor + { + get { return modifyAccessor; } + set + { + ThrowOnExistingProperty(modifyAccessor, "modifyAccessor"); + modifyAccessor = value; + } + } + public TLFunction TLFModifyAccessor { get; set; } + public TLMethodDescriptor TLFModifyDescriptor { get; set; } + + SwiftPropertyType didSet; + public SwiftPropertyType DidSet + { + get + { + return didSet; + } + set + { + ThrowOnExistingProperty(didSet, "did set"); + didSet = value; + } + } + public TLFunction TLFDidSet { get; set; } + public TLMethodDescriptor TLFDidSetDescriptor { get; set; } + + SwiftPropertyType willSet; + public SwiftPropertyType WillSet + { + get + { + return willSet; + } + set + { + ThrowOnExistingProperty(willSet, "will set"); + willSet = value; + } + } + public TLFunction TLFWillSet { get; set; } + public TLMethodDescriptor TLFWillSetDescriptor { get; set; } + + void ThrowOnExistingProperty(SwiftPropertyType prop, string propType) + { + if (prop != null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 6, $"Already have a {propType} entry for property {Name} in {Class.ClassName.ToFullyQualifiedName()}"); + } + + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } } diff --git a/src/SwiftReflector/Inventory/PropertyInventory.cs b/src/SwiftReflector/Inventory/PropertyInventory.cs index 509d5b0cceee..82c1dd28d48c 100644 --- a/src/SwiftReflector/Inventory/PropertyInventory.cs +++ b/src/SwiftReflector/Inventory/PropertyInventory.cs @@ -8,47 +8,51 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class PropertyInventory : Inventory { - int sizeofMachinePointer; - public PropertyInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public override void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 7, $"Expected a TLFunction for a property but got a {tld.GetType ().Name}."); - - SwiftPropertyType prop = tlf.Signature as SwiftPropertyType; - if (prop == null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 8, $"Expected a function of property type but got a {tlf.Signature.GetType ().Name}."); - - PropertyContents contents = null; - SwiftName nameToUse = prop.PrivateName ?? prop.Name; - if (!values.TryGetValue (nameToUse, out contents)) { - contents = new PropertyContents (tlf.Class, nameToUse, sizeofMachinePointer); - values.Add (nameToUse, contents); - } - contents.Add (tlf, prop); - } - } - - public PropertyContents PropertyWithName (SwiftName name) - { - PropertyContents pc = Values.Where (oi => oi.Name.Equals (name)).FirstOrDefault (); - return pc; - } - - public PropertyContents PropertyWithName (string name) - { - SwiftName sn = new SwiftName (name, false); - return PropertyWithName (sn); - } - - } +namespace SwiftReflector.Inventory +{ + public class PropertyInventory : Inventory + { + int sizeofMachinePointer; + public PropertyInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + + public override void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 7, $"Expected a TLFunction for a property but got a {tld.GetType().Name}."); + + SwiftPropertyType prop = tlf.Signature as SwiftPropertyType; + if (prop == null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 8, $"Expected a function of property type but got a {tlf.Signature.GetType().Name}."); + + PropertyContents contents = null; + SwiftName nameToUse = prop.PrivateName ?? prop.Name; + if (!values.TryGetValue(nameToUse, out contents)) + { + contents = new PropertyContents(tlf.Class, nameToUse, sizeofMachinePointer); + values.Add(nameToUse, contents); + } + contents.Add(tlf, prop); + } + } + + public PropertyContents PropertyWithName(SwiftName name) + { + PropertyContents pc = Values.Where(oi => oi.Name.Equals(name)).FirstOrDefault(); + return pc; + } + + public PropertyContents PropertyWithName(string name) + { + SwiftName sn = new SwiftName(name, false); + return PropertyWithName(sn); + } + + } } diff --git a/src/SwiftReflector/Inventory/ProtocolContents.cs b/src/SwiftReflector/Inventory/ProtocolContents.cs index 734a18b14868..86ef1e89c2f3 100644 --- a/src/SwiftReflector/Inventory/ProtocolContents.cs +++ b/src/SwiftReflector/Inventory/ProtocolContents.cs @@ -7,79 +7,90 @@ using SwiftReflector.ExceptionTools; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class ProtocolContents { - int sizeofMachinePointer; - public ProtocolContents (SwiftClassName className, int sizeofMachiinePointer) - { - this.sizeofMachinePointer = sizeofMachiinePointer; - WitnessTable = new WitnessInventory (sizeofMachinePointer); - FunctionsOfUnknownDestination = new List (); - DefinitionsOfUnknownDestination = new List (); - BaseDescriptors = new List (); - BaseConformanceDescriptors = new List (); - Name = className; +namespace SwiftReflector.Inventory +{ + public class ProtocolContents + { + int sizeofMachinePointer; + public ProtocolContents(SwiftClassName className, int sizeofMachiinePointer) + { + this.sizeofMachinePointer = sizeofMachiinePointer; + WitnessTable = new WitnessInventory(sizeofMachinePointer); + FunctionsOfUnknownDestination = new List(); + DefinitionsOfUnknownDestination = new List(); + BaseDescriptors = new List(); + BaseConformanceDescriptors = new List(); + Name = className; - } + } - public TLMetaclass Metaclass { get; private set; } - public TLDirectMetadata DirectMetadata { get; private set; } - public TLProtocolTypeDescriptor TypeDescriptor { get; private set; } - public WitnessInventory WitnessTable { get; private set; } - public List FunctionsOfUnknownDestination { get; private set; } - public List DefinitionsOfUnknownDestination { get; private set; } - public List BaseDescriptors { get; private set; } - public List BaseConformanceDescriptors { get; private set; } - public SwiftClassName Name { get; private set; } + public TLMetaclass Metaclass { get; private set; } + public TLDirectMetadata DirectMetadata { get; private set; } + public TLProtocolTypeDescriptor TypeDescriptor { get; private set; } + public WitnessInventory WitnessTable { get; private set; } + public List FunctionsOfUnknownDestination { get; private set; } + public List DefinitionsOfUnknownDestination { get; private set; } + public List BaseDescriptors { get; private set; } + public List BaseConformanceDescriptors { get; private set; } + public SwiftClassName Name { get; private set; } - public void Add (TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) { - if (ClassContents.IsWitnessTable (tlf.Signature, tlf.Class)) { - WitnessTable.Add (tlf, srcStm); - } - FunctionsOfUnknownDestination.Add (tlf); - return; - } + public void Add(TLDefinition tld, Stream srcStm) + { + TLFunction tlf = tld as TLFunction; + if (tlf != null) + { + if (ClassContents.IsWitnessTable(tlf.Signature, tlf.Class)) + { + WitnessTable.Add(tlf, srcStm); + } + FunctionsOfUnknownDestination.Add(tlf); + return; + } - TLDirectMetadata meta = tld as TLDirectMetadata; - if (meta != null) { - if (DirectMetadata != null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 1, $"duplicate direct metadata in protocol {DirectMetadata.Class.ClassName.ToFullyQualifiedName ()}"); - DirectMetadata = meta; - return; - } - TLMetaclass mc = tld as TLMetaclass; - if (mc != null) { - if (Metaclass != null) { - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 2, $"duplicate type meta data descriptor in protocol {Metaclass.Class.ClassName.ToFullyQualifiedName ()}"); - } - Metaclass = mc; - return; - } + TLDirectMetadata meta = tld as TLDirectMetadata; + if (meta != null) + { + if (DirectMetadata != null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 1, $"duplicate direct metadata in protocol {DirectMetadata.Class.ClassName.ToFullyQualifiedName()}"); + DirectMetadata = meta; + return; + } + TLMetaclass mc = tld as TLMetaclass; + if (mc != null) + { + if (Metaclass != null) + { + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 2, $"duplicate type meta data descriptor in protocol {Metaclass.Class.ClassName.ToFullyQualifiedName()}"); + } + Metaclass = mc; + return; + } - TLProtocolTypeDescriptor ptd = tld as TLProtocolTypeDescriptor; - if (ptd != null) { - if (TypeDescriptor != null) { - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 3, $"duplicate protocol type descriptor in protocol {TypeDescriptor.Class.ClassName.ToFullyQualifiedName ()}"); - } - TypeDescriptor = ptd; - return; - } + TLProtocolTypeDescriptor ptd = tld as TLProtocolTypeDescriptor; + if (ptd != null) + { + if (TypeDescriptor != null) + { + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 3, $"duplicate protocol type descriptor in protocol {TypeDescriptor.Class.ClassName.ToFullyQualifiedName()}"); + } + TypeDescriptor = ptd; + return; + } - if (tld is TLProtocolRequirementsBaseDescriptor baseDescriptor) { - BaseDescriptors.Add (baseDescriptor); - return; - } + if (tld is TLProtocolRequirementsBaseDescriptor baseDescriptor) + { + BaseDescriptors.Add(baseDescriptor); + return; + } - if (tld is TLBaseConformanceDescriptor baseConformanceDescriptor) { - BaseConformanceDescriptors.Add (baseConformanceDescriptor); - return; - } + if (tld is TLBaseConformanceDescriptor baseConformanceDescriptor) + { + BaseConformanceDescriptors.Add(baseConformanceDescriptor); + return; + } - DefinitionsOfUnknownDestination.Add (tld); - } - } + DefinitionsOfUnknownDestination.Add(tld); + } + } } diff --git a/src/SwiftReflector/Inventory/ProtocolInventory.cs b/src/SwiftReflector/Inventory/ProtocolInventory.cs index 8ce239658f7b..aef78d2f85f0 100644 --- a/src/SwiftReflector/Inventory/ProtocolInventory.cs +++ b/src/SwiftReflector/Inventory/ProtocolInventory.cs @@ -5,27 +5,31 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class ProtocolInventory : Inventory { - int sizeofMachinePointer; - public ProtocolInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } +namespace SwiftReflector.Inventory +{ + public class ProtocolInventory : Inventory + { + int sizeofMachinePointer; + public ProtocolInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } - public override void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - SwiftName className = ClassInventory.ToClassName (tld); - SwiftClassName formalName = ClassInventory.ToFormalClassName (tld); - ProtocolContents contents = null; - if (!values.TryGetValue (className, out contents)) { - contents = new ProtocolContents (formalName, sizeofMachinePointer); - values.Add (className, contents); - } - contents.Add (tld, srcStm); - } - } - } + public override void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + SwiftName className = ClassInventory.ToClassName(tld); + SwiftClassName formalName = ClassInventory.ToFormalClassName(tld); + ProtocolContents contents = null; + if (!values.TryGetValue(className, out contents)) + { + contents = new ProtocolContents(formalName, sizeofMachinePointer); + values.Add(className, contents); + } + contents.Add(tld, srcStm); + } + } + } } diff --git a/src/SwiftReflector/Inventory/VariableContents.cs b/src/SwiftReflector/Inventory/VariableContents.cs index bff5e56dc595..bd4cbb994f10 100644 --- a/src/SwiftReflector/Inventory/VariableContents.cs +++ b/src/SwiftReflector/Inventory/VariableContents.cs @@ -4,20 +4,22 @@ using System.Collections.Generic; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class VariableContents { - int sizeofMachinePointer; - public VariableContents (SwiftName name, int sizeofMachinePointer) - { - Name = name; - Addressors = new List (); - this.sizeofMachinePointer = sizeofMachinePointer; - } +namespace SwiftReflector.Inventory +{ + public class VariableContents + { + int sizeofMachinePointer; + public VariableContents(SwiftName name, int sizeofMachinePointer) + { + Name = name; + Addressors = new List(); + this.sizeofMachinePointer = sizeofMachinePointer; + } - public TLVariable Variable { get; set; } - public List Addressors { get; private set; } - public SwiftName Name { get; private set; } - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } + public TLVariable Variable { get; set; } + public List Addressors { get; private set; } + public SwiftName Name { get; private set; } + public int SizeofMachinePointer { get { return sizeofMachinePointer; } } + } } diff --git a/src/SwiftReflector/Inventory/VariableInventory.cs b/src/SwiftReflector/Inventory/VariableInventory.cs index 8a6595e10fe0..3979951b8af5 100644 --- a/src/SwiftReflector/Inventory/VariableInventory.cs +++ b/src/SwiftReflector/Inventory/VariableInventory.cs @@ -6,46 +6,52 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class VariableInventory : Inventory { - int sizeofMachinePointer; - public VariableInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - public override void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - TLVariable vari = tld as TLVariable; - if (vari != null) { - VariableContents contents = GoGetIt (vari.Name); - if (contents.Variable != null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 4, $"duplicate variable {vari.Name.Name}."); - contents.Variable = vari; - return; - } +namespace SwiftReflector.Inventory +{ + public class VariableInventory : Inventory + { + int sizeofMachinePointer; + public VariableInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } + public override void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + TLVariable vari = tld as TLVariable; + if (vari != null) + { + VariableContents contents = GoGetIt(vari.Name); + if (contents.Variable != null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 4, $"duplicate variable {vari.Name.Name}."); + contents.Variable = vari; + return; + } - TLFunction tlf = tld as TLFunction; - if (tlf != null) { - VariableContents contents = GoGetIt (tlf.Name); - contents.Addressors.Add (tlf); - return; - } + TLFunction tlf = tld as TLFunction; + if (tlf != null) + { + VariableContents contents = GoGetIt(tlf.Name); + contents.Addressors.Add(tlf); + return; + } - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 5, $"expected a top-level function or top-level variable but got a {tld.GetType ().Name}"); - } + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 5, $"expected a top-level function or top-level variable but got a {tld.GetType().Name}"); + } - } + } - VariableContents GoGetIt (SwiftName name) - { - VariableContents vari = null; - if (!values.TryGetValue (name, out vari)) { - vari = new VariableContents (name, sizeofMachinePointer); - values.Add (name, vari); - } - return vari; - } - } + VariableContents GoGetIt(SwiftName name) + { + VariableContents vari = null; + if (!values.TryGetValue(name, out vari)) + { + vari = new VariableContents(name, sizeofMachinePointer); + values.Add(name, vari); + } + return vari; + } + } } diff --git a/src/SwiftReflector/Inventory/WitnessInventory.cs b/src/SwiftReflector/Inventory/WitnessInventory.cs index f4cf7ac564f9..42d7c2d327bf 100644 --- a/src/SwiftReflector/Inventory/WitnessInventory.cs +++ b/src/SwiftReflector/Inventory/WitnessInventory.cs @@ -8,60 +8,64 @@ using System.IO; using SwiftReflector.Demangling; -namespace SwiftReflector.Inventory { - public class WitnessInventory { - object valuesLock = new object (); - Dictionary values = new Dictionary (); - int sizeofMachinePointer; +namespace SwiftReflector.Inventory +{ + public class WitnessInventory + { + object valuesLock = new object(); + Dictionary values = new Dictionary(); + int sizeofMachinePointer; - public WitnessInventory (int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } + public WitnessInventory(int sizeofMachinePointer) + { + this.sizeofMachinePointer = sizeofMachinePointer; + } - public void Add (TLDefinition tld, Stream srcStm) - { - lock (valuesLock) { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 9, $"Expected a TLFunction for a witness table but got a {tld.GetType ().Name}."); + public void Add(TLDefinition tld, Stream srcStm) + { + lock (valuesLock) + { + TLFunction tlf = tld as TLFunction; + if (tlf == null) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 9, $"Expected a TLFunction for a witness table but got a {tld.GetType().Name}."); - if (values.ContainsKey (tlf.MangledName)) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 10, $"Already received witness table entry for {tlf.MangledName}."); - values.Add (tlf.MangledName, tlf); - LoadWitnessTable (tlf, srcStm); - } - } + if (values.ContainsKey(tlf.MangledName)) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 10, $"Already received witness table entry for {tlf.MangledName}."); + values.Add(tlf.MangledName, tlf); + LoadWitnessTable(tlf, srcStm); + } + } - public IEnumerable MangledNames { get { return values.Keys; } } - public IEnumerable Functions { get { return values.Values; } } - public IEnumerable WitnessEntriesOfType (WitnessType wit) - { - return Functions.Where (fn => (fn.Signature is SwiftWitnessTableType) && ((SwiftWitnessTableType)fn.Signature).WitnessType == wit); - } + public IEnumerable MangledNames { get { return values.Keys; } } + public IEnumerable Functions { get { return values.Values; } } + public IEnumerable WitnessEntriesOfType(WitnessType wit) + { + return Functions.Where(fn => (fn.Signature is SwiftWitnessTableType) && ((SwiftWitnessTableType)fn.Signature).WitnessType == wit); + } - public ValueWitnessTable ValueWitnessTable { get; private set; } + public ValueWitnessTable ValueWitnessTable { get; private set; } - void LoadWitnessTable (TLFunction tlf, Stream stm) - { - WitnessType type = FromTLF (tlf); - switch (type) { - case WitnessType.Value: - ValueWitnessTable = ValueWitnessTable.FromStream (stm, tlf, sizeofMachinePointer); - break; - default: - break; - } - } + void LoadWitnessTable(TLFunction tlf, Stream stm) + { + WitnessType type = FromTLF(tlf); + switch (type) + { + case WitnessType.Value: + ValueWitnessTable = ValueWitnessTable.FromStream(stm, tlf, sizeofMachinePointer); + break; + default: + break; + } + } - WitnessType FromTLF (TLFunction tlf) - { - SwiftWitnessTableType wit = tlf.Signature as SwiftWitnessTableType; - if (wit == null) - throw new ArgumentException ("tlf"); - return wit.WitnessType; - } - } + WitnessType FromTLF(TLFunction tlf) + { + SwiftWitnessTableType wit = tlf.Signature as SwiftWitnessTableType; + if (wit == null) + throw new ArgumentException("tlf"); + return wit.WitnessType; + } + } } diff --git a/src/SwiftReflector/MachOHawley.cs b/src/SwiftReflector/MachOHawley.cs index 6581f647374f..4fe851bd0525 100644 --- a/src/SwiftReflector/MachOHawley.cs +++ b/src/SwiftReflector/MachOHawley.cs @@ -13,279 +13,295 @@ using MonoTouch; #endif -namespace Xamarin { - public class MachO { - /* definitions from: /usr/include/mach-o/loader.h */ - /* Constant for the magic field of the mach_header (32-bit architectures) */ - internal const uint MH_MAGIC = 0xfeedface; /* the mach magic number */ - internal const uint MH_CIGAM = 0xcefaedfe; /* NXSwapInt(MH_MAGIC) */ - - /* Constant for the magic field of the mach_header_64 (64-bit architectures) */ - internal const uint MH_MAGIC_64 = 0xfeedfacf; /* the 64-bit mach magic number */ - internal const uint MH_CIGAM_64 = 0xcffaedfe; /* NXSwapInt(MH_MAGIC_64) */ - - /* definitions from: /usr/include/mach-o/fat.h */ - internal const uint FAT_MAGIC = 0xcafebabe; - internal const uint FAT_CIGAM = 0xbebafeca; /* NXSwapLong(FAT_MAGIC) */ - - public enum Architectures { - None = 0, - i386 = 1, - ARMv6 = 2, - ARMv7 = 4, - ARMv7s = 8, - ARM64 = 16, - x86_64 = 32, - ARM64e = 64, - ARM64_32 = 128, - } - - public enum LoadCommands : uint { - //#define LC_REQ_DYLD 0x80000000 - ReqDyld = 0x80000000, - // - // /* Constants for the cmd field of all load commands, the type */ - //#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ - Segment = 0x1, - //#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ - SymTab = 0x2, - //#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ - SymSeg = 0x3, - //#define LC_THREAD 0x4 /* thread */ - Thread = 0x4, - //#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ - UnixThread = 0x5, - //#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */ - LoadFVMLib = 0x6, - //#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */ - IDFVMLib = 0x7, - //#define LC_IDENT 0x8 /* object identification info (obsolete) */ - Ident = 0x8, - //#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */ - FVMFile = 0x9, - //#define LC_PREPAGE 0xa /* prepage command (internal use) */ - Prepage = 0xa, - //#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */ - DySymTab = 0x0b, - - //#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */ - LoadDylib = 0xc, - //#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */ - IdDylib = 0xd, - //#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */ - LoadDylinker = 0xe, - //#define LC_ID_DYLINKER 0xf /* dynamic linker identification */ - IdDylinker = 0xf, - //#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */ - PreboundDylib = 0x10, - // /* linked shared library */ - //#define LC_ROUTINES 0x11 /* image routines */ - Routines = 0x11, - //#define LC_SUB_FRAMEWORK 0x12 /* sub framework */ - SubFramework = 0x12, - //#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */ - SubUmbrella = 0x13, - //#define LC_SUB_CLIENT 0x14 /* sub client */ - SubClient = 0x14, - //#define LC_SUB_LIBRARY 0x15 /* sub library */ - SubLibrary = 0x15, - //#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */ - TwolevelHints = 0x16, - //#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */ - PrebindChecksum = 0x17, - // - // /* - // * load a dynamically linked shared library that is allowed to be missing - // * (all symbols are weak imported). - // */ - //#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD) - LoadWeakDylib = 0x18 | ReqDyld, - // - //#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be - Segment64 = 0x19, - // mapped */ - //#define LC_ROUTINES_64 0x1a /* 64-bit image routines */ - Routines64 = 0x1a, - //#define LC_UUID 0x1b /* the uuid */ - Uuid = 0x1b, - //#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */ - RPath = 0x1c | ReqDyld, - //#define LC_CODE_SIGNATURE 0x1d /* local of code signature */ - CodeSignature = 0x1d, - //#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */ - SegmentSplitInfo = 0x1e, - //#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */ - ReexportDylib = 0x1f | ReqDyld, - //#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */ - LazyLoadDylib = 0x20, - //#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */ - EncryptionInfo = 0x21, - //#define LC_DYLD_INFO 0x22 /* compressed dyld information */ - DyldInfo = 0x22, - //#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ - DyldInfoOnly = 0x22 | ReqDyld, - //#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */ - LoadUpwardDylib = 0x23 | ReqDyld, - //#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */ - VersionMinMacOS = 0x24, - //#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */ - VersionMinIPhoneOS = 0x25, - //#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */ - FunctionStarts = 0x26, - //#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat - DyldEnvironment = 0x27, - // like environment variable */ - //#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */ - Main = 0x28 | ReqDyld, - //#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */ - DataInCode = 0x29, - //#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */ - SourceVersion = 0x2a, - //#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */ - DylibCodeSignDrs = 0x2b, - //#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */ - EncryptionInfo64 = 0x2c, - //#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */ - VersionMinTVOS = 0x2f, - //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ - VersionMinWatchOS = 0x30, - //#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */ - Note = 0x31, - //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ - BuildVersion = 0x32, - //#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */ - DyldExportsTrie = 0x33 | ReqDyld, - //#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */ - DyldChainedFixups = 0x34 | ReqDyld, - } - - public enum Platform : uint { - MacOS = 1, - IOS = 2, - TvOS = 3, - WatchOS = 4, - BridgeOS = 5, - IOSSimulator = 7, - TvOSSimulator = 8, - WatchOSSimulator = 9, - } - - internal static uint FromBigEndian (uint number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static int FromBigEndian (int number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static uint ToBigEndian (uint number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static int ToBigEndian (int number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - static IDisposable ReadFile (ReaderParameters parameters) - { - var reader = parameters.Reader; - var magic = reader.ReadUInt32 (); - reader.BaseStream.Position = 0; - switch (magic) { - case MH_MAGIC: - case MH_MAGIC_64: - var mf = new MachOFile (parameters); - mf.Read (); - return mf; - case FAT_MAGIC: // little-endian fat binary - case FAT_CIGAM: // big-endian fat binary - { - var f = new FatFile (parameters); - f.Read (); - return f; - } - default: - throw new Exception (string.Format ("File format not recognized: {0} (magic: 0x{1})", parameters.Filename ?? "(no file name available)", magic.ToString ("X"))); - } - } - - public static MachOFileCollection Read (string filename, ReadingMode mode) - { - var parameters = new ReaderParameters (); - parameters.Filename = filename; - parameters.ReadingMode = mode; - parameters.Reader = new BinaryReader (new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8, false); - try { - return GetMachOFiles (parameters, ReadFile (parameters)); - } finally { - if (mode == ReadingMode.Immediate) - parameters.Dispose (); - } - } - - static MachOFileCollection GetMachOFiles (ReaderParameters parameters, IDisposable readOutput) - { - var rv = new MachOFileCollection (parameters); - if (readOutput is FatFile fatfile) { - foreach (var ff in fatfile.entries) - rv.Add (ff.entry); - } else { - rv.Add ((MachOFile) readOutput); - } - return rv; - } - - public static IEnumerable Read (Stream stm, string filename = null) - { - if (stm == null) - throw new ArgumentNullException (nameof (stm)); - using (var parameters = new ReaderParameters ()) { - parameters.ReadingMode = ReadingMode.Immediate; - parameters.Reader = new BinaryReader (stm, Encoding.UTF8, true); - parameters.Filename = filename; - return GetMachOFiles (parameters, ReadFile (parameters)); - } - } - - public static bool IsMachoFile (string filename) - { - using (FileStream stm = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { - return IsMachoFile (stm); - } - } - - public static bool IsMachoFile (Stream stm) - { - using (var reader = new BinaryReader (stm, UTF8Encoding.UTF8, true)) { - var magic = reader.ReadUInt32 (); - reader.BaseStream.Position = 0; - switch (magic) { - case MH_MAGIC: - case MH_MAGIC_64: - case FAT_MAGIC: // little-endian fat binary - case FAT_CIGAM: // big-endian fat binary - return true; - default: - return false; - } - } - } +namespace Xamarin +{ + public class MachO + { + /* definitions from: /usr/include/mach-o/loader.h */ + /* Constant for the magic field of the mach_header (32-bit architectures) */ + internal const uint MH_MAGIC = 0xfeedface; /* the mach magic number */ + internal const uint MH_CIGAM = 0xcefaedfe; /* NXSwapInt(MH_MAGIC) */ + + /* Constant for the magic field of the mach_header_64 (64-bit architectures) */ + internal const uint MH_MAGIC_64 = 0xfeedfacf; /* the 64-bit mach magic number */ + internal const uint MH_CIGAM_64 = 0xcffaedfe; /* NXSwapInt(MH_MAGIC_64) */ + + /* definitions from: /usr/include/mach-o/fat.h */ + internal const uint FAT_MAGIC = 0xcafebabe; + internal const uint FAT_CIGAM = 0xbebafeca; /* NXSwapLong(FAT_MAGIC) */ + + public enum Architectures + { + None = 0, + i386 = 1, + ARMv6 = 2, + ARMv7 = 4, + ARMv7s = 8, + ARM64 = 16, + x86_64 = 32, + ARM64e = 64, + ARM64_32 = 128, + } + + public enum LoadCommands : uint + { + //#define LC_REQ_DYLD 0x80000000 + ReqDyld = 0x80000000, + // + // /* Constants for the cmd field of all load commands, the type */ + //#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ + Segment = 0x1, + //#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ + SymTab = 0x2, + //#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ + SymSeg = 0x3, + //#define LC_THREAD 0x4 /* thread */ + Thread = 0x4, + //#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ + UnixThread = 0x5, + //#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */ + LoadFVMLib = 0x6, + //#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */ + IDFVMLib = 0x7, + //#define LC_IDENT 0x8 /* object identification info (obsolete) */ + Ident = 0x8, + //#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */ + FVMFile = 0x9, + //#define LC_PREPAGE 0xa /* prepage command (internal use) */ + Prepage = 0xa, + //#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */ + DySymTab = 0x0b, + + //#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */ + LoadDylib = 0xc, + //#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */ + IdDylib = 0xd, + //#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */ + LoadDylinker = 0xe, + //#define LC_ID_DYLINKER 0xf /* dynamic linker identification */ + IdDylinker = 0xf, + //#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */ + PreboundDylib = 0x10, + // /* linked shared library */ + //#define LC_ROUTINES 0x11 /* image routines */ + Routines = 0x11, + //#define LC_SUB_FRAMEWORK 0x12 /* sub framework */ + SubFramework = 0x12, + //#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */ + SubUmbrella = 0x13, + //#define LC_SUB_CLIENT 0x14 /* sub client */ + SubClient = 0x14, + //#define LC_SUB_LIBRARY 0x15 /* sub library */ + SubLibrary = 0x15, + //#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */ + TwolevelHints = 0x16, + //#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */ + PrebindChecksum = 0x17, + // + // /* + // * load a dynamically linked shared library that is allowed to be missing + // * (all symbols are weak imported). + // */ + //#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD) + LoadWeakDylib = 0x18 | ReqDyld, + // + //#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be + Segment64 = 0x19, + // mapped */ + //#define LC_ROUTINES_64 0x1a /* 64-bit image routines */ + Routines64 = 0x1a, + //#define LC_UUID 0x1b /* the uuid */ + Uuid = 0x1b, + //#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */ + RPath = 0x1c | ReqDyld, + //#define LC_CODE_SIGNATURE 0x1d /* local of code signature */ + CodeSignature = 0x1d, + //#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */ + SegmentSplitInfo = 0x1e, + //#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */ + ReexportDylib = 0x1f | ReqDyld, + //#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */ + LazyLoadDylib = 0x20, + //#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */ + EncryptionInfo = 0x21, + //#define LC_DYLD_INFO 0x22 /* compressed dyld information */ + DyldInfo = 0x22, + //#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ + DyldInfoOnly = 0x22 | ReqDyld, + //#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */ + LoadUpwardDylib = 0x23 | ReqDyld, + //#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */ + VersionMinMacOS = 0x24, + //#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */ + VersionMinIPhoneOS = 0x25, + //#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */ + FunctionStarts = 0x26, + //#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat + DyldEnvironment = 0x27, + // like environment variable */ + //#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */ + Main = 0x28 | ReqDyld, + //#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */ + DataInCode = 0x29, + //#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */ + SourceVersion = 0x2a, + //#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */ + DylibCodeSignDrs = 0x2b, + //#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */ + EncryptionInfo64 = 0x2c, + //#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */ + VersionMinTVOS = 0x2f, + //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ + VersionMinWatchOS = 0x30, + //#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */ + Note = 0x31, + //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ + BuildVersion = 0x32, + //#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */ + DyldExportsTrie = 0x33 | ReqDyld, + //#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */ + DyldChainedFixups = 0x34 | ReqDyld, + } + + public enum Platform : uint + { + MacOS = 1, + IOS = 2, + TvOS = 3, + WatchOS = 4, + BridgeOS = 5, + IOSSimulator = 7, + TvOSSimulator = 8, + WatchOSSimulator = 9, + } + + internal static uint FromBigEndian(uint number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static int FromBigEndian(int number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static uint ToBigEndian(uint number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + internal static int ToBigEndian(int number) + { + return (((number >> 24) & 0xFF) + | ((number >> 08) & 0xFF00) + | ((number << 08) & 0xFF0000) + | ((number << 24))); + } + + static IDisposable ReadFile(ReaderParameters parameters) + { + var reader = parameters.Reader; + var magic = reader.ReadUInt32(); + reader.BaseStream.Position = 0; + switch (magic) + { + case MH_MAGIC: + case MH_MAGIC_64: + var mf = new MachOFile(parameters); + mf.Read(); + return mf; + case FAT_MAGIC: // little-endian fat binary + case FAT_CIGAM: // big-endian fat binary + { + var f = new FatFile(parameters); + f.Read(); + return f; + } + default: + throw new Exception(string.Format("File format not recognized: {0} (magic: 0x{1})", parameters.Filename ?? "(no file name available)", magic.ToString("X"))); + } + } + + public static MachOFileCollection Read(string filename, ReadingMode mode) + { + var parameters = new ReaderParameters(); + parameters.Filename = filename; + parameters.ReadingMode = mode; + parameters.Reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8, false); + try + { + return GetMachOFiles(parameters, ReadFile(parameters)); + } + finally + { + if (mode == ReadingMode.Immediate) + parameters.Dispose(); + } + } + + static MachOFileCollection GetMachOFiles(ReaderParameters parameters, IDisposable readOutput) + { + var rv = new MachOFileCollection(parameters); + if (readOutput is FatFile fatfile) + { + foreach (var ff in fatfile.entries) + rv.Add(ff.entry); + } + else + { + rv.Add((MachOFile)readOutput); + } + return rv; + } + + public static IEnumerable Read(Stream stm, string filename = null) + { + if (stm == null) + throw new ArgumentNullException(nameof(stm)); + using (var parameters = new ReaderParameters()) + { + parameters.ReadingMode = ReadingMode.Immediate; + parameters.Reader = new BinaryReader(stm, Encoding.UTF8, true); + parameters.Filename = filename; + return GetMachOFiles(parameters, ReadFile(parameters)); + } + } + + public static bool IsMachoFile(string filename) + { + using (FileStream stm = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + return IsMachoFile(stm); + } + } + + public static bool IsMachoFile(Stream stm) + { + using (var reader = new BinaryReader(stm, UTF8Encoding.UTF8, true)) + { + var magic = reader.ReadUInt32(); + reader.BaseStream.Position = 0; + switch (magic) + { + case MH_MAGIC: + case MH_MAGIC_64: + case FAT_MAGIC: // little-endian fat binary + case FAT_CIGAM: // big-endian fat binary + return true; + default: + return false; + } + } + } @@ -378,31 +394,35 @@ public static void SelectArchitectures (string filename, ICollection abis) } #endif - static Dictionary> native_dependencies = new Dictionary> (); - - public static IEnumerable GetNativeDependencies (string libraryName) - { - IEnumerable result; - lock (native_dependencies) { - if (native_dependencies.TryGetValue (libraryName, out result)) - return result; - } - - var macho_files = Read (libraryName, ReadingMode.Deferred); - var dependencies = new HashSet (); - foreach (var macho_file in macho_files) { - foreach (var lc in macho_file.load_commands) { - var dyld_lc = lc as Xamarin.DylibLoadCommand; - if (dyld_lc != null) { - dependencies.Add (dyld_lc.name); - } - } - } - result = dependencies; - lock (native_dependencies) - native_dependencies.Add (libraryName, result); - return result; - } + static Dictionary> native_dependencies = new Dictionary>(); + + public static IEnumerable GetNativeDependencies(string libraryName) + { + IEnumerable result; + lock (native_dependencies) + { + if (native_dependencies.TryGetValue(libraryName, out result)) + return result; + } + + var macho_files = Read(libraryName, ReadingMode.Deferred); + var dependencies = new HashSet(); + foreach (var macho_file in macho_files) + { + foreach (var lc in macho_file.load_commands) + { + var dyld_lc = lc as Xamarin.DylibLoadCommand; + if (dyld_lc != null) + { + dependencies.Add(dyld_lc.name); + } + } + } + result = dependencies; + lock (native_dependencies) + native_dependencies.Add(libraryName, result); + return result; + } #if MTOUCH public static List GetArchitectures (string file) @@ -488,852 +508,927 @@ static Abi GetArch (int cputype, int cpusubtype) return Abi.None; } #endif - } - - public class StaticLibrary - { - public static bool IsStaticLibrary (BinaryReader reader) - { - var pos = reader.BaseStream.Position; - - var bytes = reader.ReadBytes (8); - var rv = bytes [0] == '!' && bytes [1] == '<' && bytes [2] == 'a' && bytes [3] == 'r' && bytes [4] == 'c' && bytes [5] == 'h' && bytes [6] == '>' && bytes [7] == 0xa; - reader.BaseStream.Position = pos; - - return rv; - } - } - - public enum ReadingMode { - Immediate = 1, - Deferred = 2, - } - - sealed class ReaderParameters : IDisposable { - public BinaryReader Reader; - public string Filename; - public ReadingMode ReadingMode { get; set; } - -#region IDisposable Support - void Dispose (bool disposing) - { - Reader?.Dispose (); - } - - ~ReaderParameters () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } -#endregion - } - - public class MachOFileCollection : List, IDisposable { - internal ReaderParameters Parameters { get; private set; } - - internal MachOFileCollection (ReaderParameters parameters) - { - Parameters = parameters; - } - -#region IDisposable Support - protected virtual void Dispose (bool disposing) - { - Parameters.Dispose (); - } - - ~MachOFileCollection () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize(this); - } -#endregion - } - - public class MachOFile : IDisposable { - internal ReaderParameters parameters { get; private set; } - public uint magic; - public int cputype; - public int cpusubtype; - public uint filetype; - public uint ncmds; - public uint sizeofcmds; - public uint flags; - public uint reserved; - - public List load_commands; - - internal MachOFile (ReaderParameters parameters) - { - this.parameters = parameters; - } - - internal void WriteHeader (BinaryWriter writer) - { - writer.Write (magic); - writer.Write (cputype); - writer.Write (cpusubtype); - writer.Write (filetype); - writer.Write (ncmds); - writer.Write (sizeofcmds); - writer.Write ((uint)flags); - if (magic == MachO.MH_MAGIC_64) - writer.Write (reserved); - } - - internal static bool IsMachOLibrary (BinaryReader reader) - { - var pos = reader.BaseStream.Position; - var magic = reader.ReadUInt32 (); - var rv = false; - switch (magic) { - case MachO.MH_CIGAM: - case MachO.MH_MAGIC: - case MachO.MH_CIGAM_64: - case MachO.MH_MAGIC_64: - rv = true; - break; - default: - rv = false; - break; - } - reader.BaseStream.Position = pos; - return rv; - } - - internal void Read () - { - /* definitions from: /usr/include/mach-o/loader.h */ - /* + } + + public class StaticLibrary + { + public static bool IsStaticLibrary(BinaryReader reader) + { + var pos = reader.BaseStream.Position; + + var bytes = reader.ReadBytes(8); + var rv = bytes[0] == '!' && bytes[1] == '<' && bytes[2] == 'a' && bytes[3] == 'r' && bytes[4] == 'c' && bytes[5] == 'h' && bytes[6] == '>' && bytes[7] == 0xa; + reader.BaseStream.Position = pos; + + return rv; + } + } + + public enum ReadingMode + { + Immediate = 1, + Deferred = 2, + } + + sealed class ReaderParameters : IDisposable + { + public BinaryReader Reader; + public string Filename; + public ReadingMode ReadingMode { get; set; } + + #region IDisposable Support + void Dispose(bool disposing) + { + Reader?.Dispose(); + } + + ~ReaderParameters() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + #endregion + } + + public class MachOFileCollection : List, IDisposable + { + internal ReaderParameters Parameters { get; private set; } + + internal MachOFileCollection(ReaderParameters parameters) + { + Parameters = parameters; + } + + #region IDisposable Support + protected virtual void Dispose(bool disposing) + { + Parameters.Dispose(); + } + + ~MachOFileCollection() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + #endregion + } + + public class MachOFile : IDisposable + { + internal ReaderParameters parameters { get; private set; } + public uint magic; + public int cputype; + public int cpusubtype; + public uint filetype; + public uint ncmds; + public uint sizeofcmds; + public uint flags; + public uint reserved; + + public List load_commands; + + internal MachOFile(ReaderParameters parameters) + { + this.parameters = parameters; + } + + internal void WriteHeader(BinaryWriter writer) + { + writer.Write(magic); + writer.Write(cputype); + writer.Write(cpusubtype); + writer.Write(filetype); + writer.Write(ncmds); + writer.Write(sizeofcmds); + writer.Write((uint)flags); + if (magic == MachO.MH_MAGIC_64) + writer.Write(reserved); + } + + internal static bool IsMachOLibrary(BinaryReader reader) + { + var pos = reader.BaseStream.Position; + var magic = reader.ReadUInt32(); + var rv = false; + switch (magic) + { + case MachO.MH_CIGAM: + case MachO.MH_MAGIC: + case MachO.MH_CIGAM_64: + case MachO.MH_MAGIC_64: + rv = true; + break; + default: + rv = false; + break; + } + reader.BaseStream.Position = pos; + return rv; + } + + internal void Read() + { + /* definitions from: /usr/include/mach-o/loader.h */ + /* * The 32-bit mach header appears at the very beginning of the object file for * 32-bit architectures. */ - // struct mach_header { - // uint32_t magic; /* mach magic number identifier */ - // cpu_type_t cputype; /* cpu specifier */ - // cpu_subtype_t cpusubtype; /* machine specifier */ - // uint32_t filetype; /* type of file */ - // uint32_t ncmds; /* number of load commands */ - // uint32_t sizeofcmds; /* the size of all the load commands */ - // uint32_t flags; /* flags */ - // }; - - /* + // struct mach_header { + // uint32_t magic; /* mach magic number identifier */ + // cpu_type_t cputype; /* cpu specifier */ + // cpu_subtype_t cpusubtype; /* machine specifier */ + // uint32_t filetype; /* type of file */ + // uint32_t ncmds; /* number of load commands */ + // uint32_t sizeofcmds; /* the size of all the load commands */ + // uint32_t flags; /* flags */ + // }; + + /* * The 64-bit mach header appears at the very beginning of object files for * 64-bit architectures. */ - // struct mach_header_64 { - // uint32_t magic; /* mach magic number identifier */ - // cpu_type_t cputype; /* cpu specifier */ - // cpu_subtype_t cpusubtype; /* machine specifier */ - // uint32_t filetype; /* type of file */ - // uint32_t ncmds; /* number of load commands */ - // uint32_t sizeofcmds; /* the size of all the load commands */ - // uint32_t flags; /* flags */ - // uint32_t reserved; /* reserved */ - // }; - var reader = parameters.Reader; - StartOffset = reader.BaseStream.Position; - if (!MachOFile.IsMachOLibrary (reader)) { - if (StaticLibrary.IsStaticLibrary (reader)) { - throw new Exception ("Static libraries are not supported (yet)."); - } - throw new Exception ($"Unknown format for fat entry at position {StartOffset}"); - } - magic = reader.ReadUInt32 (); - cputype = reader.ReadInt32 (); - cpusubtype = reader.ReadInt32 (); - filetype = reader.ReadUInt32 (); - ncmds = reader.ReadUInt32 (); - sizeofcmds = reader.ReadUInt32 (); - flags = reader.ReadUInt32 (); - if (magic == MachO.MH_MAGIC_64) - reserved = reader.ReadUInt32 (); - var cmds = new List ((int)ncmds); - for (int i = 0; i < ncmds; i++) { - var cmd = (MachO.LoadCommands)reader.ReadUInt32 (); - reader.BaseStream.Position -= 4; - LoadCommand lc; - switch (cmd) { - case MachO.LoadCommands.LoadDylib: - case MachO.LoadCommands.LoadWeakDylib: - case MachO.LoadCommands.ReexportDylib: - lc = DylibLoadCommand.FromBinaryReader (reader); - break; - case MachO.LoadCommands.SymTab: - lc = SymTabLoadCommand.FromBinaryReader (this, StartOffset); - break; - case MachO.LoadCommands.VersionMinTVOS: - case MachO.LoadCommands.VersionMinMacOS: - case MachO.LoadCommands.VersionMinIPhoneOS: - case MachO.LoadCommands.VersionMinWatchOS: - lc = VersionMinOSLoadCommand.FromBinaryReader (reader); - break; - case MachO.LoadCommands.BuildVersion: - var buildVer = new BuildVersionCommand (); - buildVer.cmd = reader.ReadUInt32 (); - buildVer.cmdsize = reader.ReadUInt32 (); - buildVer.platform = reader.ReadUInt32 (); - buildVer.minos = reader.ReadUInt32 (); - buildVer.sdk = reader.ReadUInt32 (); - buildVer.ntools = reader.ReadUInt32 (); - buildVer.tools = new BuildVersionCommand.BuildToolVersion [buildVer.ntools]; - for (int j = 0; j < buildVer.ntools; j++) { - var buildToolVer = new BuildVersionCommand.BuildToolVersion (); - buildToolVer.tool = reader.ReadUInt32 (); - buildToolVer.version = reader.ReadUInt32 (); - buildVer.tools[j] = buildToolVer; - } - lc = buildVer; - break; - default: - lc = new LoadCommand (); - lc.cmd = reader.ReadUInt32 (); - lc.cmdsize = reader.ReadUInt32 (); - reader.BaseStream.Position += lc.cmdsize - 8; - break; - } - cmds.Add (lc); - } - load_commands = cmds; - } - - public MachO.Architectures Architecture { - get { - switch (cputype) { - case 12: // arm - switch (cpusubtype) { - case 6: - return MachO.Architectures.ARMv6; - case 9: - return MachO.Architectures.ARMv7; - case 11: - return MachO.Architectures.ARMv7s; - default: - return MachO.Architectures.None; - } - case 12 | 0x01000000: - switch (cpusubtype) { - case 2: - return MachO.Architectures.ARM64e; - case 0: - default: - return MachO.Architectures.ARM64; - } - case 12 | 0x02000000: - switch (cpusubtype & ~0xff000000) { - case 1: - return MachO.Architectures.ARM64_32; - default: - return MachO.Architectures.ARM64; - } - case 7: // x86 - return MachO.Architectures.i386; - case 7 | 0x01000000: // x64 - return MachO.Architectures.x86_64; - } - - return MachO.Architectures.None; - } - } - - public bool Is32Bit { - get { - switch (Architecture) { - case MachO.Architectures.ARMv6: - case MachO.Architectures.ARMv7: - case MachO.Architectures.ARMv7s: - case MachO.Architectures.i386: - case MachO.Architectures.None: // not sure what to do with None. - return true; - default: - return false; - } - } - } - - public long StartOffset { get; private set; } - - public class MinOSVersion { - public Version Version; - public string OSName { - get { - switch (Platform) { - case MachO.Platform.IOS: - case MachO.Platform.IOSSimulator: - return "ios"; - case MachO.Platform.MacOS: - return "macosx"; - case MachO.Platform.TvOS: - case MachO.Platform.TvOSSimulator: - return "tvos"; - case MachO.Platform.WatchOS: - case MachO.Platform.WatchOSSimulator: - return "watchos"; - default: - throw new ArgumentOutOfRangeException (Platform.ToString ()); - } - } - } - public MachO.Platform Platform; - public Version Sdk; - } - - public MinOSVersion MinOS { - get { - uint? version = null; - uint? sdk = null; - MachO.Platform platform = (MachO.Platform) 0; - foreach (var lc in load_commands) { - if (lc is VersionMinOSLoadCommand min_lc) { - if (version.HasValue) - throw new NotSupportedException ("File has multiple minOS load commands."); - version = min_lc.version; - sdk = min_lc.sdk; - - switch (min_lc.Command) { - case MachO.LoadCommands.VersionMinMacOS: - platform = MachO.Platform.MacOS; - break; - case MachO.LoadCommands.VersionMinIPhoneOS: - platform = MachO.Platform.IOS; - break; - case MachO.LoadCommands.VersionMinTVOS: - platform = MachO.Platform.TvOS; - break; - case MachO.LoadCommands.VersionMinWatchOS: - platform = MachO.Platform.WatchOS; - break; - default: - throw new ArgumentOutOfRangeException (nameof (min_lc.Command)); - } - } else if (lc is BuildVersionCommand build_lc) { - if (version.HasValue) - throw new NotSupportedException ("File has multiple minOS load commands."); - version = build_lc.minos; - sdk = build_lc.sdk; - platform = build_lc.Platform; - } - } - if (!version.HasValue) - return null; - - return new MinOSVersion { - Version = BuildVersionCommand.DeNibble (version.Value), - Platform = platform, - Sdk = BuildVersionCommand.DeNibble (sdk.Value) - }; - } - } - -#region IDisposable Support - protected virtual void Dispose (bool disposing) - { - parameters?.Dispose (); - } - - ~MachOFile () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } -#endregion - } - - public class FatFile : IDisposable { - internal ReaderParameters parameters { get; private set; } - public uint magic; - public uint nfat_arch; - - public List entries; - internal FatFile (ReaderParameters parameters) - { - this.parameters = parameters; - } - - internal bool is_big_endian { - get { return magic == MachO.FAT_CIGAM; } - } - - internal void WriteHeader (BinaryWriter writer) - { - writer.Write (magic); - if (is_big_endian) { - writer.Write (MachO.ToBigEndian (nfat_arch)); - } else { - writer.Write (nfat_arch); - } - } - - internal void WriteHeaders (BinaryWriter writer) - { - WriteHeader (writer); - for (int i = 0; i < entries.Count; i++) { - entries [i].WriteHeader (writer); - } - } - - internal void Read () - { - var reader = parameters.Reader; - magic = reader.ReadUInt32 (); - nfat_arch = reader.ReadUInt32 (); - if (is_big_endian) - nfat_arch = MachO.FromBigEndian (nfat_arch); - - entries = new List ((int)nfat_arch); - for (int i = 0; i < (int)nfat_arch; i++) { - var entry = new FatEntry (this); - entry.Read (); - entries.Add (entry); - } - foreach (var entry in entries) - entry.ReadEntry (); - } - -#region IDisposable Support - protected virtual void Dispose (bool disposing) - { - parameters.Dispose (); - } - - ~FatFile () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } -#endregion - } - - public class FatEntry { - FatFile parent; - public int cputype; - public int cpusubtype; - public uint offset; - public uint size; - public uint align; - - public MachOFile entry; - - public FatEntry (FatFile parent) - { - this.parent = parent; - } - - internal void WriteHeader (BinaryWriter writer) - { - if (parent.is_big_endian) { - writer.Write (MachO.ToBigEndian (cputype)); - writer.Write (MachO.ToBigEndian (cpusubtype)); - writer.Write (MachO.ToBigEndian (offset)); - writer.Write (MachO.ToBigEndian (size)); - writer.Write (MachO.ToBigEndian (align)); - } else { - writer.Write (cputype); - writer.Write (cpusubtype); - writer.Write (offset); - writer.Write (size); - writer.Write (align); - } - } - - internal void Write (BinaryWriter writer, BinaryReader reader, uint reader_offset) - { - writer.BaseStream.Position = offset; - // write data - WriteFile (writer, reader, reader_offset); - } - - internal void WriteFile (BinaryWriter writer, BinaryReader reader, uint reader_offset) - { - // write data - var ofs = writer.BaseStream.Position; - reader.BaseStream.Position = reader_offset; - var buffer = new byte [1 << (int)align]; - var left = (int)size; - while (left > 0) { - var read = reader.Read (buffer, 0, Math.Min (buffer.Length, left)); - writer.Write (buffer, 0, read); - left -= read; - } - writer.BaseStream.Position = ofs; // restore to the post-header location. - } - - internal void Read () - { - var reader = parent.parameters.Reader; - cputype = reader.ReadInt32 (); - cpusubtype = reader.ReadInt32 (); - offset = reader.ReadUInt32 (); - size = reader.ReadUInt32 (); - align = reader.ReadUInt32 (); - - if (parent.is_big_endian) { - cputype = MachO.FromBigEndian (cputype); - cpusubtype = MachO.FromBigEndian (cpusubtype); - offset = MachO.FromBigEndian (offset); - size = MachO.FromBigEndian (size); - align = MachO.FromBigEndian (align); - } - } - - internal void ReadEntry () - { - var reader = parent.parameters.Reader; - reader.BaseStream.Position = offset; - entry = new MachOFile (parent.parameters); - entry.Read (); - } - } - - public class LoadCommand { - public uint cmd; - public uint cmdsize; - - public MachO.LoadCommands Command { - get { return (MachO.LoadCommands) cmd; } - } + // struct mach_header_64 { + // uint32_t magic; /* mach magic number identifier */ + // cpu_type_t cputype; /* cpu specifier */ + // cpu_subtype_t cpusubtype; /* machine specifier */ + // uint32_t filetype; /* type of file */ + // uint32_t ncmds; /* number of load commands */ + // uint32_t sizeofcmds; /* the size of all the load commands */ + // uint32_t flags; /* flags */ + // uint32_t reserved; /* reserved */ + // }; + var reader = parameters.Reader; + StartOffset = reader.BaseStream.Position; + if (!MachOFile.IsMachOLibrary(reader)) + { + if (StaticLibrary.IsStaticLibrary(reader)) + { + throw new Exception("Static libraries are not supported (yet)."); + } + throw new Exception($"Unknown format for fat entry at position {StartOffset}"); + } + magic = reader.ReadUInt32(); + cputype = reader.ReadInt32(); + cpusubtype = reader.ReadInt32(); + filetype = reader.ReadUInt32(); + ncmds = reader.ReadUInt32(); + sizeofcmds = reader.ReadUInt32(); + flags = reader.ReadUInt32(); + if (magic == MachO.MH_MAGIC_64) + reserved = reader.ReadUInt32(); + var cmds = new List((int)ncmds); + for (int i = 0; i < ncmds; i++) + { + var cmd = (MachO.LoadCommands)reader.ReadUInt32(); + reader.BaseStream.Position -= 4; + LoadCommand lc; + switch (cmd) + { + case MachO.LoadCommands.LoadDylib: + case MachO.LoadCommands.LoadWeakDylib: + case MachO.LoadCommands.ReexportDylib: + lc = DylibLoadCommand.FromBinaryReader(reader); + break; + case MachO.LoadCommands.SymTab: + lc = SymTabLoadCommand.FromBinaryReader(this, StartOffset); + break; + case MachO.LoadCommands.VersionMinTVOS: + case MachO.LoadCommands.VersionMinMacOS: + case MachO.LoadCommands.VersionMinIPhoneOS: + case MachO.LoadCommands.VersionMinWatchOS: + lc = VersionMinOSLoadCommand.FromBinaryReader(reader); + break; + case MachO.LoadCommands.BuildVersion: + var buildVer = new BuildVersionCommand(); + buildVer.cmd = reader.ReadUInt32(); + buildVer.cmdsize = reader.ReadUInt32(); + buildVer.platform = reader.ReadUInt32(); + buildVer.minos = reader.ReadUInt32(); + buildVer.sdk = reader.ReadUInt32(); + buildVer.ntools = reader.ReadUInt32(); + buildVer.tools = new BuildVersionCommand.BuildToolVersion[buildVer.ntools]; + for (int j = 0; j < buildVer.ntools; j++) + { + var buildToolVer = new BuildVersionCommand.BuildToolVersion(); + buildToolVer.tool = reader.ReadUInt32(); + buildToolVer.version = reader.ReadUInt32(); + buildVer.tools[j] = buildToolVer; + } + lc = buildVer; + break; + default: + lc = new LoadCommand(); + lc.cmd = reader.ReadUInt32(); + lc.cmdsize = reader.ReadUInt32(); + reader.BaseStream.Position += lc.cmdsize - 8; + break; + } + cmds.Add(lc); + } + load_commands = cmds; + } + + public MachO.Architectures Architecture + { + get + { + switch (cputype) + { + case 12: // arm + switch (cpusubtype) + { + case 6: + return MachO.Architectures.ARMv6; + case 9: + return MachO.Architectures.ARMv7; + case 11: + return MachO.Architectures.ARMv7s; + default: + return MachO.Architectures.None; + } + case 12 | 0x01000000: + switch (cpusubtype) + { + case 2: + return MachO.Architectures.ARM64e; + case 0: + default: + return MachO.Architectures.ARM64; + } + case 12 | 0x02000000: + switch (cpusubtype & ~0xff000000) + { + case 1: + return MachO.Architectures.ARM64_32; + default: + return MachO.Architectures.ARM64; + } + case 7: // x86 + return MachO.Architectures.i386; + case 7 | 0x01000000: // x64 + return MachO.Architectures.x86_64; + } + + return MachO.Architectures.None; + } + } + + public bool Is32Bit + { + get + { + switch (Architecture) + { + case MachO.Architectures.ARMv6: + case MachO.Architectures.ARMv7: + case MachO.Architectures.ARMv7s: + case MachO.Architectures.i386: + case MachO.Architectures.None: // not sure what to do with None. + return true; + default: + return false; + } + } + } + + public long StartOffset { get; private set; } + + public class MinOSVersion + { + public Version Version; + public string OSName + { + get + { + switch (Platform) + { + case MachO.Platform.IOS: + case MachO.Platform.IOSSimulator: + return "ios"; + case MachO.Platform.MacOS: + return "macosx"; + case MachO.Platform.TvOS: + case MachO.Platform.TvOSSimulator: + return "tvos"; + case MachO.Platform.WatchOS: + case MachO.Platform.WatchOSSimulator: + return "watchos"; + default: + throw new ArgumentOutOfRangeException(Platform.ToString()); + } + } + } + public MachO.Platform Platform; + public Version Sdk; + } + + public MinOSVersion MinOS + { + get + { + uint? version = null; + uint? sdk = null; + MachO.Platform platform = (MachO.Platform)0; + foreach (var lc in load_commands) + { + if (lc is VersionMinOSLoadCommand min_lc) + { + if (version.HasValue) + throw new NotSupportedException("File has multiple minOS load commands."); + version = min_lc.version; + sdk = min_lc.sdk; + + switch (min_lc.Command) + { + case MachO.LoadCommands.VersionMinMacOS: + platform = MachO.Platform.MacOS; + break; + case MachO.LoadCommands.VersionMinIPhoneOS: + platform = MachO.Platform.IOS; + break; + case MachO.LoadCommands.VersionMinTVOS: + platform = MachO.Platform.TvOS; + break; + case MachO.LoadCommands.VersionMinWatchOS: + platform = MachO.Platform.WatchOS; + break; + default: + throw new ArgumentOutOfRangeException(nameof(min_lc.Command)); + } + } + else if (lc is BuildVersionCommand build_lc) + { + if (version.HasValue) + throw new NotSupportedException("File has multiple minOS load commands."); + version = build_lc.minos; + sdk = build_lc.sdk; + platform = build_lc.Platform; + } + } + if (!version.HasValue) + return null; + + return new MinOSVersion + { + Version = BuildVersionCommand.DeNibble(version.Value), + Platform = platform, + Sdk = BuildVersionCommand.DeNibble(sdk.Value) + }; + } + } + + #region IDisposable Support + protected virtual void Dispose(bool disposing) + { + parameters?.Dispose(); + } + + ~MachOFile() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + #endregion + } + + public class FatFile : IDisposable + { + internal ReaderParameters parameters { get; private set; } + public uint magic; + public uint nfat_arch; + + public List entries; + internal FatFile(ReaderParameters parameters) + { + this.parameters = parameters; + } + + internal bool is_big_endian + { + get { return magic == MachO.FAT_CIGAM; } + } + + internal void WriteHeader(BinaryWriter writer) + { + writer.Write(magic); + if (is_big_endian) + { + writer.Write(MachO.ToBigEndian(nfat_arch)); + } + else + { + writer.Write(nfat_arch); + } + } + + internal void WriteHeaders(BinaryWriter writer) + { + WriteHeader(writer); + for (int i = 0; i < entries.Count; i++) + { + entries[i].WriteHeader(writer); + } + } + + internal void Read() + { + var reader = parameters.Reader; + magic = reader.ReadUInt32(); + nfat_arch = reader.ReadUInt32(); + if (is_big_endian) + nfat_arch = MachO.FromBigEndian(nfat_arch); + + entries = new List((int)nfat_arch); + for (int i = 0; i < (int)nfat_arch; i++) + { + var entry = new FatEntry(this); + entry.Read(); + entries.Add(entry); + } + foreach (var entry in entries) + entry.ReadEntry(); + } + + #region IDisposable Support + protected virtual void Dispose(bool disposing) + { + parameters.Dispose(); + } + + ~FatFile() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + #endregion + } + + public class FatEntry + { + FatFile parent; + public int cputype; + public int cpusubtype; + public uint offset; + public uint size; + public uint align; + + public MachOFile entry; + + public FatEntry(FatFile parent) + { + this.parent = parent; + } + + internal void WriteHeader(BinaryWriter writer) + { + if (parent.is_big_endian) + { + writer.Write(MachO.ToBigEndian(cputype)); + writer.Write(MachO.ToBigEndian(cpusubtype)); + writer.Write(MachO.ToBigEndian(offset)); + writer.Write(MachO.ToBigEndian(size)); + writer.Write(MachO.ToBigEndian(align)); + } + else + { + writer.Write(cputype); + writer.Write(cpusubtype); + writer.Write(offset); + writer.Write(size); + writer.Write(align); + } + } + + internal void Write(BinaryWriter writer, BinaryReader reader, uint reader_offset) + { + writer.BaseStream.Position = offset; + // write data + WriteFile(writer, reader, reader_offset); + } + + internal void WriteFile(BinaryWriter writer, BinaryReader reader, uint reader_offset) + { + // write data + var ofs = writer.BaseStream.Position; + reader.BaseStream.Position = reader_offset; + var buffer = new byte[1 << (int)align]; + var left = (int)size; + while (left > 0) + { + var read = reader.Read(buffer, 0, Math.Min(buffer.Length, left)); + writer.Write(buffer, 0, read); + left -= read; + } + writer.BaseStream.Position = ofs; // restore to the post-header location. + } + + internal void Read() + { + var reader = parent.parameters.Reader; + cputype = reader.ReadInt32(); + cpusubtype = reader.ReadInt32(); + offset = reader.ReadUInt32(); + size = reader.ReadUInt32(); + align = reader.ReadUInt32(); + + if (parent.is_big_endian) + { + cputype = MachO.FromBigEndian(cputype); + cpusubtype = MachO.FromBigEndian(cpusubtype); + offset = MachO.FromBigEndian(offset); + size = MachO.FromBigEndian(size); + align = MachO.FromBigEndian(align); + } + } + + internal void ReadEntry() + { + var reader = parent.parameters.Reader; + reader.BaseStream.Position = offset; + entry = new MachOFile(parent.parameters); + entry.Read(); + } + } + + public class LoadCommand + { + public uint cmd; + public uint cmdsize; + + public MachO.LoadCommands Command + { + get { return (MachO.LoadCommands)cmd; } + } #if DEBUG - public virtual void Dump () - { - Console.WriteLine (" cmd: {0}", cmd); - Console.WriteLine (" cmdsize: {0}", cmdsize); - } + public virtual void Dump() + { + Console.WriteLine(" cmd: {0}", cmd); + Console.WriteLine(" cmdsize: {0}", cmdsize); + } #endif - public override string ToString () - { - return Command.ToString (); - } - } - - public class DylibLoadCommand : LoadCommand { - public string name; - public uint timestamp; - public uint current_version; - public uint compatibility_version; - - public static LoadCommand FromBinaryReader (BinaryReader reader) - { - var dlc = new DylibLoadCommand (); - dlc.cmd = reader.ReadUInt32 (); - dlc.cmdsize = reader.ReadUInt32 (); - /*var nameofs = */ - reader.ReadUInt32 (); - dlc.timestamp = reader.ReadUInt32 (); - dlc.current_version = reader.ReadUInt32 (); - dlc.compatibility_version = reader.ReadUInt32 (); - var namelength = dlc.cmdsize - 6 * 4; - var namechars = reader.ReadBytes ((int)namelength); - // strip off any null characters at the end. - for (int n = namechars.Length - 1; n >= 0; n--) { - if (namechars [n] == 0) - namelength--; - else - break; - } - dlc.name = System.Text.UTF8Encoding.UTF8.GetString (namechars, 0, (int)namelength); - return dlc; - } + public override string ToString() + { + return Command.ToString(); + } + } + + public class DylibLoadCommand : LoadCommand + { + public string name; + public uint timestamp; + public uint current_version; + public uint compatibility_version; + + public static LoadCommand FromBinaryReader(BinaryReader reader) + { + var dlc = new DylibLoadCommand(); + dlc.cmd = reader.ReadUInt32(); + dlc.cmdsize = reader.ReadUInt32(); + /*var nameofs = */ + reader.ReadUInt32(); + dlc.timestamp = reader.ReadUInt32(); + dlc.current_version = reader.ReadUInt32(); + dlc.compatibility_version = reader.ReadUInt32(); + var namelength = dlc.cmdsize - 6 * 4; + var namechars = reader.ReadBytes((int)namelength); + // strip off any null characters at the end. + for (int n = namechars.Length - 1; n >= 0; n--) + { + if (namechars[n] == 0) + namelength--; + else + break; + } + dlc.name = System.Text.UTF8Encoding.UTF8.GetString(namechars, 0, (int)namelength); + return dlc; + } #if DEBUG - public override void Dump () - { - base.Dump (); - Console.WriteLine (" name: {0}", name); - Console.WriteLine (" timestamp: {0}", timestamp); - Console.WriteLine (" current_version: {0}", current_version); - Console.WriteLine (" compatibility_version: {0}", compatibility_version); - } + public override void Dump() + { + base.Dump(); + Console.WriteLine(" name: {0}", name); + Console.WriteLine(" timestamp: {0}", timestamp); + Console.WriteLine(" current_version: {0}", current_version); + Console.WriteLine(" compatibility_version: {0}", compatibility_version); + } #endif - } - - public class VersionMinOSLoadCommand : LoadCommand { - public uint version; - public uint sdk; - public static LoadCommand FromBinaryReader (BinaryReader reader) - { - var vmlc = new VersionMinOSLoadCommand (); - vmlc.cmd = reader.ReadUInt32 (); - vmlc.cmdsize = reader.ReadUInt32 (); - vmlc.version = reader.ReadUInt32 (); - vmlc.sdk = reader.ReadUInt32 (); - return vmlc; - } - string ToConventionalString (uint val) - { - uint major = val >> 16; - uint minor = (val >> 8) & 0xff; - uint sub = val & 0xff; - if (sub == 0) - return $"{major}.{minor}"; - else - return $"{major}.{minor}.{sub}"; - } - string ToOperatingSystemString (uint theCmd) - { - switch ((MachO.LoadCommands)theCmd) { - case MachO.LoadCommands.VersionMinMacOS: - return "macosx"; - case MachO.LoadCommands.VersionMinIPhoneOS: - return "ios"; - case MachO.LoadCommands.VersionMinTVOS: - return "tvos"; - case MachO.LoadCommands.VersionMinWatchOS: - return "watchos"; - default: - throw new ArgumentOutOfRangeException (nameof (theCmd)); - } - } - - public string ToOSVersionString () - { - return $"{ToConventionalString (version)}"; - } - - public string ToOSString (bool isx8664) - { - return $"{ToOperatingSystemString (cmd)}{ToConventionalString (version)}"; - } - } - - - - public class SymTabLoadCommand : LoadCommand { - MachOFile file; - long startOffset; - - public uint symoff; /* symbol table offset */ - public uint nsyms; /* number of symbol table entries */ - public uint stroff; /* string table offset */ - public uint strsize; /* string table size in bytes */ - NListEntry [] _nlist; - - public NListEntry [] nlist { - get { - if (_nlist == null) - ReadNList (); - return _nlist; - } - } - - public static LoadCommand FromBinaryReader (MachOFile file, long startOffset) - { - var parameters = file.parameters; - var reader = parameters.Reader; - - var stc = new SymTabLoadCommand (); - stc.file = file; - stc.startOffset = startOffset; - stc.cmd = reader.ReadUInt32 (); - stc.cmdsize = reader.ReadUInt32 (); - stc.symoff = reader.ReadUInt32 (); - stc.nsyms = reader.ReadUInt32 (); - stc.stroff = reader.ReadUInt32 (); - stc.strsize = reader.ReadUInt32 (); - if (parameters.ReadingMode == ReadingMode.Immediate) - stc.ReadNList (); - return stc; - } - - public void ReadNList () - { - var reader = file.parameters.Reader; - _nlist = new NListEntry [nsyms]; - long savePos = reader.BaseStream.Position; - try { - reader.BaseStream.Seek (startOffset + symoff, SeekOrigin.Begin); - for (uint i = 0; i < nsyms; i++) - _nlist [i] = NListEntry.FromBinaryReader (reader, file.Is32Bit); - - for (uint i = 0; i < nsyms; i++) { - var entry = _nlist [i]; - reader.BaseStream.Seek (startOffset + stroff + entry.n_strx, SeekOrigin.Begin); - entry.str = ReadStringEntry (reader); - } - } finally { - reader.BaseStream.Seek (savePos, SeekOrigin.Begin); - } - } - - - static string ReadStringEntry (BinaryReader reader) - { - StringBuilder builder = new StringBuilder (); - byte b; - while ((b = reader.ReadByte ()) != 0) { - builder.Append ((char)b); - } - return builder.ToString (); - } - - IEnumerable PublicSymbols { - get { - return nlist.Where ((nle, i) => nle.IsPublic && !nle.IsSymbolicDebuggerEntry); - } - } + } + + public class VersionMinOSLoadCommand : LoadCommand + { + public uint version; + public uint sdk; + public static LoadCommand FromBinaryReader(BinaryReader reader) + { + var vmlc = new VersionMinOSLoadCommand(); + vmlc.cmd = reader.ReadUInt32(); + vmlc.cmdsize = reader.ReadUInt32(); + vmlc.version = reader.ReadUInt32(); + vmlc.sdk = reader.ReadUInt32(); + return vmlc; + } + string ToConventionalString(uint val) + { + uint major = val >> 16; + uint minor = (val >> 8) & 0xff; + uint sub = val & 0xff; + if (sub == 0) + return $"{major}.{minor}"; + else + return $"{major}.{minor}.{sub}"; + } + string ToOperatingSystemString(uint theCmd) + { + switch ((MachO.LoadCommands)theCmd) + { + case MachO.LoadCommands.VersionMinMacOS: + return "macosx"; + case MachO.LoadCommands.VersionMinIPhoneOS: + return "ios"; + case MachO.LoadCommands.VersionMinTVOS: + return "tvos"; + case MachO.LoadCommands.VersionMinWatchOS: + return "watchos"; + default: + throw new ArgumentOutOfRangeException(nameof(theCmd)); + } + } + + public string ToOSVersionString() + { + return $"{ToConventionalString(version)}"; + } + + public string ToOSString(bool isx8664) + { + return $"{ToOperatingSystemString(cmd)}{ToConventionalString(version)}"; + } + } + + + + public class SymTabLoadCommand : LoadCommand + { + MachOFile file; + long startOffset; + + public uint symoff; /* symbol table offset */ + public uint nsyms; /* number of symbol table entries */ + public uint stroff; /* string table offset */ + public uint strsize; /* string table size in bytes */ + NListEntry[] _nlist; + + public NListEntry[] nlist + { + get + { + if (_nlist == null) + ReadNList(); + return _nlist; + } + } + + public static LoadCommand FromBinaryReader(MachOFile file, long startOffset) + { + var parameters = file.parameters; + var reader = parameters.Reader; + + var stc = new SymTabLoadCommand(); + stc.file = file; + stc.startOffset = startOffset; + stc.cmd = reader.ReadUInt32(); + stc.cmdsize = reader.ReadUInt32(); + stc.symoff = reader.ReadUInt32(); + stc.nsyms = reader.ReadUInt32(); + stc.stroff = reader.ReadUInt32(); + stc.strsize = reader.ReadUInt32(); + if (parameters.ReadingMode == ReadingMode.Immediate) + stc.ReadNList(); + return stc; + } + + public void ReadNList() + { + var reader = file.parameters.Reader; + _nlist = new NListEntry[nsyms]; + long savePos = reader.BaseStream.Position; + try + { + reader.BaseStream.Seek(startOffset + symoff, SeekOrigin.Begin); + for (uint i = 0; i < nsyms; i++) + _nlist[i] = NListEntry.FromBinaryReader(reader, file.Is32Bit); + + for (uint i = 0; i < nsyms; i++) + { + var entry = _nlist[i]; + reader.BaseStream.Seek(startOffset + stroff + entry.n_strx, SeekOrigin.Begin); + entry.str = ReadStringEntry(reader); + } + } + finally + { + reader.BaseStream.Seek(savePos, SeekOrigin.Begin); + } + } + + + static string ReadStringEntry(BinaryReader reader) + { + StringBuilder builder = new StringBuilder(); + byte b; + while ((b = reader.ReadByte()) != 0) + { + builder.Append((char)b); + } + return builder.ToString(); + } + + IEnumerable PublicSymbols + { + get + { + return nlist.Where((nle, i) => nle.IsPublic && !nle.IsSymbolicDebuggerEntry); + } + } #if DEBUG - public override void Dump () - { - base.Dump (); - Console.WriteLine (" symoff: {0}", symoff); - Console.WriteLine (" nsyms: {0}", nsyms); - Console.WriteLine (" stroff: {0}", stroff); - Console.WriteLine (" strsize: {0}", strsize); - } + public override void Dump() + { + base.Dump(); + Console.WriteLine(" symoff: {0}", symoff); + Console.WriteLine(" nsyms: {0}", nsyms); + Console.WriteLine(" stroff: {0}", stroff); + Console.WriteLine(" strsize: {0}", strsize); + } #endif - } - - public class BuildVersionCommand : LoadCommand { - public uint platform; - public uint minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ - public uint sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ - public uint ntools; - public BuildToolVersion[] tools; - - public class BuildToolVersion { - public uint tool; - public uint version; - } - - public static Version DeNibble (uint value) - { - var major = (int) (value >> 16); - var minor = (int) ((value >> 8) & 0xff); - var sub = (int) (value & 0xff); - if (sub == 0) { - // This makes sure the string version is a two-part version (X.Y) when the 'sub' version is 0, - // otherwise various toolchain tools (swiftc among others) will complain. - return new Version (major, minor); - } else { - // Here we have no choice but to be a three-part version (X.Y.Z). - return new Version (major, minor, sub); - } - } - - public Version MinOS { - get { return DeNibble (minos); } - } - - public Version Sdk { - get { return DeNibble (sdk); } - } - - public MachO.Platform Platform { - get { return (MachO.Platform) platform; } - } - } - - // #define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */ - // #define N_ABS 0x2 /* absolute, n_sect == NO_SECT */ - // #define N_SECT 0xe /* defined in section number n_sect */ - // #define N_PBUD 0xc /* prebound undefined (defined in a dylib) */ - // #define N_INDR 0xa /* indirect */ - - public enum NListEntryType { - Undefined = 0, - Absolute = 0x2, - InSection = 0xe, - PreboundUndefined = 0x0c, - Indirect = 0x0a - }; - - public class NListEntry { - const int kSymbolTableMask = 0xe0, - kPrivateExternalMask = 0x10, - kTypeMask = 0x0e, - kExternalMask = 0x01; - - // from nlist.h - public int n_strx; - public byte n_type; - public byte n_sect; - public short n_desc; - public string str; - - public static NListEntry FromBinaryReader (BinaryReader reader, bool is32Bit) - { - NListEntry entry = is32Bit ? (NListEntry)new NListEntry32 () : (NListEntry)new NListEntry64 (); - return entry.FromBinaryReader (reader); - } - - protected virtual NListEntry FromBinaryReader (BinaryReader reader) - { - n_strx = reader.ReadInt32 (); - n_type = reader.ReadByte (); - n_sect = reader.ReadByte (); - n_desc = reader.ReadInt16 (); - return this; - } - - public NListEntryType EntryType { - get { - switch (n_type & kTypeMask) { - case 0x2: - return NListEntryType.Absolute; - case 0xa: - return NListEntryType.Indirect; - case 0xc: - return NListEntryType.PreboundUndefined; - case 0xe: - return NListEntryType.InSection; - default: - return NListEntryType.Undefined; - } - } - } - - public bool IsSymbolicDebuggerEntry { get { return (n_type & kSymbolTableMask) != 0; } } - public bool IsPublic { get { return (n_type & kExternalMask) != 0; } } - public bool IsPrivate { get { return (n_type & kPrivateExternalMask) != 0; } } - - public override string ToString () - { - return str ?? ""; - } - } - - public class NListEntry32 : NListEntry { - public uint n_value; - - protected override NListEntry FromBinaryReader (BinaryReader reader) - { - base.FromBinaryReader (reader); - n_value = reader.ReadUInt32 (); - return this; - } - } - - public class NListEntry64 : NListEntry { - public ulong n_value; - protected override NListEntry FromBinaryReader (BinaryReader reader) - { - base.FromBinaryReader (reader); - n_value = reader.ReadUInt64 (); - return this; - } - } + } + + public class BuildVersionCommand : LoadCommand + { + public uint platform; + public uint minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + public uint sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + public uint ntools; + public BuildToolVersion[] tools; + + public class BuildToolVersion + { + public uint tool; + public uint version; + } + + public static Version DeNibble(uint value) + { + var major = (int)(value >> 16); + var minor = (int)((value >> 8) & 0xff); + var sub = (int)(value & 0xff); + if (sub == 0) + { + // This makes sure the string version is a two-part version (X.Y) when the 'sub' version is 0, + // otherwise various toolchain tools (swiftc among others) will complain. + return new Version(major, minor); + } + else + { + // Here we have no choice but to be a three-part version (X.Y.Z). + return new Version(major, minor, sub); + } + } + + public Version MinOS + { + get { return DeNibble(minos); } + } + + public Version Sdk + { + get { return DeNibble(sdk); } + } + + public MachO.Platform Platform + { + get { return (MachO.Platform)platform; } + } + } + + // #define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */ + // #define N_ABS 0x2 /* absolute, n_sect == NO_SECT */ + // #define N_SECT 0xe /* defined in section number n_sect */ + // #define N_PBUD 0xc /* prebound undefined (defined in a dylib) */ + // #define N_INDR 0xa /* indirect */ + + public enum NListEntryType + { + Undefined = 0, + Absolute = 0x2, + InSection = 0xe, + PreboundUndefined = 0x0c, + Indirect = 0x0a + }; + + public class NListEntry + { + const int kSymbolTableMask = 0xe0, + kPrivateExternalMask = 0x10, + kTypeMask = 0x0e, + kExternalMask = 0x01; + + // from nlist.h + public int n_strx; + public byte n_type; + public byte n_sect; + public short n_desc; + public string str; + + public static NListEntry FromBinaryReader(BinaryReader reader, bool is32Bit) + { + NListEntry entry = is32Bit ? (NListEntry)new NListEntry32() : (NListEntry)new NListEntry64(); + return entry.FromBinaryReader(reader); + } + + protected virtual NListEntry FromBinaryReader(BinaryReader reader) + { + n_strx = reader.ReadInt32(); + n_type = reader.ReadByte(); + n_sect = reader.ReadByte(); + n_desc = reader.ReadInt16(); + return this; + } + + public NListEntryType EntryType + { + get + { + switch (n_type & kTypeMask) + { + case 0x2: + return NListEntryType.Absolute; + case 0xa: + return NListEntryType.Indirect; + case 0xc: + return NListEntryType.PreboundUndefined; + case 0xe: + return NListEntryType.InSection; + default: + return NListEntryType.Undefined; + } + } + } + + public bool IsSymbolicDebuggerEntry { get { return (n_type & kSymbolTableMask) != 0; } } + public bool IsPublic { get { return (n_type & kExternalMask) != 0; } } + public bool IsPrivate { get { return (n_type & kPrivateExternalMask) != 0; } } + + public override string ToString() + { + return str ?? ""; + } + } + + public class NListEntry32 : NListEntry + { + public uint n_value; + + protected override NListEntry FromBinaryReader(BinaryReader reader) + { + base.FromBinaryReader(reader); + n_value = reader.ReadUInt32(); + return this; + } + } + + public class NListEntry64 : NListEntry + { + public ulong n_value; + protected override NListEntry FromBinaryReader(BinaryReader reader) + { + base.FromBinaryReader(reader); + n_value = reader.ReadUInt64(); + return this; + } + } } diff --git a/src/SwiftReflector/MarshalEngine.cs b/src/SwiftReflector/MarshalEngine.cs index 85c4c5d909fc..74db006bfe8d 100644 --- a/src/SwiftReflector/MarshalEngine.cs +++ b/src/SwiftReflector/MarshalEngine.cs @@ -12,267 +12,302 @@ using SwiftReflector.SwiftXmlReflection; using SwiftReflector.Demangling; -namespace SwiftReflector { - public class MarshalEngine { - CSUsingPackages use; - List identifiersUsed; - TypeMapper typeMapper; - public bool skipThisParameterPremarshal = false; - List fixedChain = new List (); - Version swiftLangVersion; - public Func genericReferenceNamer = null; - - public MarshalEngine (CSUsingPackages use, List identifiersUsed, TypeMapper typeMapper, Version swiftLangVersion) - { - this.use = use; - this.identifiersUsed = identifiersUsed; - absolutelyMustBeFirst = new List (); - preMarshalCode = new List (); - postMarshalCode = new List (); - - this.typeMapper = typeMapper; - this.swiftLangVersion = swiftLangVersion; - } - - public IEnumerable MarshalFunctionCall (FunctionDeclaration wrapperFuncDecl, bool isExtension, string pinvokeCall, - CSParameterList pl, - BaseDeclaration typeContext, - TypeSpec swiftReturnType, - CSType returnType, - TypeSpec swiftInstanceType, - CSType instanceType, - bool includeCastToReturnType, - FunctionDeclaration originalFunction, - bool includeIntermediateCastToLong = false, - int passedInIndexOfReturn = -1, - bool originalThrows = false, - bool restoreDynamicSelf = false) - { - RequiredUnsafeCode = false; - preMarshalCode.Clear (); - postMarshalCode.Clear (); - fixedChain.Clear (); - returnLine = null; - functionCall = null; - - var parms = new CSParameterList (pl); // work with local copy - CSIdentifier returnIdent = null, returnIntPtr = null, returnProtocol = null; - var indexOfReturn = passedInIndexOfReturn; - - var originalReturn = swiftReturnType; - - int indexOfInstance = (swiftReturnType != null && (typeMapper.MustForcePassByReference (typeContext, swiftReturnType)) && !swiftReturnType.IsDynamicSelf) || originalThrows ? - 1 : 0; - var instanceIsSwiftProtocol = false; - var instanceIsObjC = false; - - if (swiftInstanceType != null) { - var entity = typeMapper.GetEntityForTypeSpec (swiftInstanceType); - instanceIsSwiftProtocol = entity.EntityType == EntityType.Protocol; - instanceIsObjC = entity.Type.IsObjC; - var thisIdentifier = isExtension ? new CSIdentifier ("self") : CSIdentifier.This; - parms.Insert (0, new CSParameter (instanceType, thisIdentifier, wrapperFuncDecl.ParameterLists.Last () [indexOfInstance].IsInOut ? - CSParameterKind.Ref : CSParameterKind.None)); - } - - var hasReturn = returnType != null && returnType != CSSimpleType.Void; - - if (hasReturn) - returnType = ReworkTypeWithNamer (returnType); - - var isExtensionMethod = pl.Count () > 0 && pl [0].ParameterKind == CSParameterKind.This; - var returnIsScalar = returnType != null && TypeMapper.IsScalar (swiftReturnType); - var returnEntity = hasReturn && !typeContext.IsTypeSpecGenericReference (swiftReturnType) ? typeMapper.GetEntityForTypeSpec (swiftReturnType) : null; - var returnIsTrivialEnum = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.TrivialEnum; - var returnIsGenericClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class && swiftReturnType.ContainsGenericParameters; - var returnIsClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class; - var returnIsNonTrivialTuple = hasReturn && swiftReturnType is TupleTypeSpec && ((TupleTypeSpec)swiftReturnType).Elements.Count > 1; - var returnIsClosure = hasReturn && swiftReturnType is ClosureTypeSpec; - var returnIsGeneric = hasReturn && typeContext.IsTypeSpecGeneric (swiftReturnType) && !returnIsClosure; - var returnIsAssocPath = hasReturn && typeContext.IsProtocolWithAssociatedTypesFullPath (swiftReturnType as NamedTypeSpec, typeMapper); - var returnIsNonScalarStruct = hasReturn && !returnIsScalar && returnEntity != null && - (returnEntity.EntityType == EntityType.Struct || returnEntity.EntityType == EntityType.Enum); - var returnIsSelf = hasReturn && swiftReturnType.IsDynamicSelf; - - var retSimple = returnType as CSSimpleType; - var returnIsInterfaceFromProtocol = - hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Protocol && retSimple != null; - var returnIsProtocolList = hasReturn && swiftReturnType is ProtocolListTypeSpec; - var returnIsObjCProtocol = hasReturn && returnEntity != null && returnEntity.IsObjCProtocol; - var returnNeedsPostProcessing = (hasReturn && (returnIsClass || returnIsProtocolList || returnIsInterfaceFromProtocol || returnIsNonTrivialTuple || - returnIsGeneric || returnIsNonScalarStruct || returnIsAssocPath || (returnIsSelf && !restoreDynamicSelf))) || originalThrows - || returnIsTrivialEnum; - - includeCastToReturnType = includeCastToReturnType || returnIsTrivialEnum; - includeIntermediateCastToLong = includeIntermediateCastToLong || returnIsTrivialEnum; - - var filteredTypeSpec = FilterParams (parms, wrapperFuncDecl, originalThrows); - - var callParameters = new List (parms.Count); - - var offsetToOriginalArgs = 0; - if ((hasReturn && indexOfReturn >= 0) || originalThrows) - offsetToOriginalArgs++; - if (swiftInstanceType != null) - offsetToOriginalArgs++; - if (isExtensionMethod && swiftInstanceType == null) - offsetToOriginalArgs++; - - for (int i = 0; i < parms.Count; i++) { - var p = parms [i]; - // if it's the instance, pass that - // if it's the return, pass that - // otherwise take it from the original functions primary parameter list - TypeSpec originalParm = null; - - if (i == indexOfInstance && swiftInstanceType != null) { - originalParm = swiftInstanceType; - } else if ((hasReturn && i == indexOfReturn) || (originalThrows && i == indexOfReturn)) { - originalParm = swiftReturnType; - } else if (isExtensionMethod && p.ParameterKind == CSParameterKind.This) { - originalParm = originalFunction.IsExtension ? originalFunction.ParentExtension.ExtensionOnType : - new NamedTypeSpec (originalFunction.Parent.ToFullyQualifiedNameWithGenerics ()); - } else { - var index = i - offsetToOriginalArgs; - originalParm = originalFunction.ParameterLists.Last () [i - offsetToOriginalArgs].TypeSpec; - } - callParameters.Add (Marshal (typeContext, wrapperFuncDecl, p, filteredTypeSpec [i], instanceIsSwiftProtocol && i == indexOfInstance, - indexOfReturn >= 0 && i == indexOfReturn, originalParm)); - } - - - var call = new CSFunctionCall (pinvokeCall, false, callParameters.ToArray ()); - - // Post marshal code demands an intermediate return value - if (postMarshalCode.Count > 0 && ((object)returnIdent) == null && (returnType != null && returnType != CSSimpleType.Void)) { - returnIdent = new CSIdentifier (Uniqueify ("retval", identifiersUsed)); - identifiersUsed.Add (returnIdent.Name); - preMarshalCode.Add (CSVariableDeclaration.VarLine (returnType, returnIdent, returnType.Default ())); - } - - - if (((object)returnIdent) != null) { - // if returnIntPtr is non-null, then the function returns a pointer to a class - // If this is the case, we have post marshal code which will assign it to - // retval. - - if (typeMapper.MustForcePassByReference (typeContext, swiftReturnType) || returnIsNonTrivialTuple || returnIsProtocolList) { - this.functionCall = new CSLine (call); - } else { - CSBaseExpression callExpr = call; - if (includeCastToReturnType && returnType != null && returnType != CSSimpleType.Void) { - if (includeIntermediateCastToLong) { - callExpr = new CSCastExpression (CSSimpleType.Long, callExpr); - } - callExpr = new CSCastExpression (returnType, callExpr); - } - this.functionCall = CSAssignment.Assign ((returnIntPtr ?? returnProtocol) ?? returnIdent, callExpr); - } - this.returnLine = CSReturn.ReturnLine (returnIdent); - } else { - if (returnType != null && returnType != CSSimpleType.Void) { - if (includeCastToReturnType) { - CSBaseExpression expr = call; - if (includeIntermediateCastToLong) { - expr = new CSCastExpression (CSSimpleType.Long, expr); - } - expr = new CSCastExpression (returnType, expr); - this.functionCall = CSReturn.ReturnLine (expr); - } else { - this.functionCall = CSReturn.ReturnLine ((ICSExpression)call); - } - } else - this.functionCall = new CSLine (call); - } - - foreach (var l in absolutelyMustBeFirst) - yield return l; - foreach (var l in preMarshalCode) - yield return l; - yield return functionCall; - foreach (var l in postMarshalCode) - yield return l; - if (returnLine != null) - yield return returnLine; - } - - CSParameter ReworkParameterWithNamer (CSParameter p) - { - if (GenericReferenceNamer == null) - return p; - var pClone = ReworkTypeWithNamer (p.CSType); - return new CSParameter (pClone, p.Name, p.ParameterKind, p.DefaultValue); - } - - CSType ReworkTypeWithNamer (CSType ty) - { - if (ty is CSGenericReferenceType genRef) { - var newGen = new CSGenericReferenceType (genRef.Depth, genRef.Index); - newGen.ReferenceNamer = GenericReferenceNamer; - return newGen; - } else if (ty is CSSimpleType simple) { - if (simple.GenericTypes == null) - return simple; - var genSubTypes = new CSType [simple.GenericTypes.Length]; - for (int i = 0; i < genSubTypes.Length; i++) { - genSubTypes [i] = ReworkTypeWithNamer (simple.GenericTypes [i]); - } - var simpleClone = new CSSimpleType (simple.GenericTypeName, simple.IsArray, genSubTypes); - return simpleClone; - } else { - throw new NotImplementedException ($"Unable to rework type {ty.GetType ().Name} {ty.ToString ()} as generic reference"); - } - } - - CSBaseExpression Marshal (BaseDeclaration typeContext, FunctionDeclaration funcDecl, CSParameter p, TypeSpec swiftType, - bool marshalProtocolAsValueType, bool isReturnVariable, TypeSpec originalType) - { - p = ReworkParameterWithNamer (p); - - var entityType = typeMapper.GetEntityTypeForTypeSpec (swiftType); - switch (entityType) { - case EntityType.Scalar: - case EntityType.Tuple: - case EntityType.None: - // Add more types - break; - } - throw new NotImplementedException ($"Uh-oh - not ready for {swiftType.ToString ()}, a {entityType}."); - } - - public static string Uniqueify (string name, IEnumerable names) - { - int thisTime = 0; - var sb = new StringBuilder (name); - while (names.Contains (sb.ToString ())) { - sb.Clear ().Append (name).Append (thisTime++); - } - return sb.ToString (); - } - - TypeSpec [] FilterParams (CSParameterList parms, FunctionDeclaration wrapperFunc, bool originalThrows) - { - var results = new TypeSpec [parms.Count]; - var parameterList = wrapperFunc.ParameterLists.Last (); - for (int i=0; i < parms.Count; i++) { - var currType = parameterList [i].TypeSpec; - results [i] = currType; - } - return results; - } - - List absolutelyMustBeFirst; - List preMarshalCode; - CSLine functionCall; - List postMarshalCode; - CSLine returnLine; - - public bool MarshalProtocolsDirectly { get; set; } - public bool RequiredUnsafeCode { get; private set; } - public bool MarshalingConstructor { get; set; } - public Func GenericReferenceNamer { get; set; } - public CSType ProtocolInterfaceType { get; set; } - - } +namespace SwiftReflector +{ + public class MarshalEngine + { + CSUsingPackages use; + List identifiersUsed; + TypeMapper typeMapper; + public bool skipThisParameterPremarshal = false; + List fixedChain = new List(); + Version swiftLangVersion; + public Func genericReferenceNamer = null; + + public MarshalEngine(CSUsingPackages use, List identifiersUsed, TypeMapper typeMapper, Version swiftLangVersion) + { + this.use = use; + this.identifiersUsed = identifiersUsed; + absolutelyMustBeFirst = new List(); + preMarshalCode = new List(); + postMarshalCode = new List(); + + this.typeMapper = typeMapper; + this.swiftLangVersion = swiftLangVersion; + } + + public IEnumerable MarshalFunctionCall(FunctionDeclaration wrapperFuncDecl, bool isExtension, string pinvokeCall, + CSParameterList pl, + BaseDeclaration typeContext, + TypeSpec swiftReturnType, + CSType returnType, + TypeSpec swiftInstanceType, + CSType instanceType, + bool includeCastToReturnType, + FunctionDeclaration originalFunction, + bool includeIntermediateCastToLong = false, + int passedInIndexOfReturn = -1, + bool originalThrows = false, + bool restoreDynamicSelf = false) + { + RequiredUnsafeCode = false; + preMarshalCode.Clear(); + postMarshalCode.Clear(); + fixedChain.Clear(); + returnLine = null; + functionCall = null; + + var parms = new CSParameterList(pl); // work with local copy + CSIdentifier returnIdent = null, returnIntPtr = null, returnProtocol = null; + var indexOfReturn = passedInIndexOfReturn; + + var originalReturn = swiftReturnType; + + int indexOfInstance = (swiftReturnType != null && (typeMapper.MustForcePassByReference(typeContext, swiftReturnType)) && !swiftReturnType.IsDynamicSelf) || originalThrows ? + 1 : 0; + var instanceIsSwiftProtocol = false; + var instanceIsObjC = false; + + if (swiftInstanceType != null) + { + var entity = typeMapper.GetEntityForTypeSpec(swiftInstanceType); + instanceIsSwiftProtocol = entity.EntityType == EntityType.Protocol; + instanceIsObjC = entity.Type.IsObjC; + var thisIdentifier = isExtension ? new CSIdentifier("self") : CSIdentifier.This; + parms.Insert(0, new CSParameter(instanceType, thisIdentifier, wrapperFuncDecl.ParameterLists.Last()[indexOfInstance].IsInOut ? + CSParameterKind.Ref : CSParameterKind.None)); + } + + var hasReturn = returnType != null && returnType != CSSimpleType.Void; + + if (hasReturn) + returnType = ReworkTypeWithNamer(returnType); + + var isExtensionMethod = pl.Count() > 0 && pl[0].ParameterKind == CSParameterKind.This; + var returnIsScalar = returnType != null && TypeMapper.IsScalar(swiftReturnType); + var returnEntity = hasReturn && !typeContext.IsTypeSpecGenericReference(swiftReturnType) ? typeMapper.GetEntityForTypeSpec(swiftReturnType) : null; + var returnIsTrivialEnum = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.TrivialEnum; + var returnIsGenericClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class && swiftReturnType.ContainsGenericParameters; + var returnIsClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class; + var returnIsNonTrivialTuple = hasReturn && swiftReturnType is TupleTypeSpec && ((TupleTypeSpec)swiftReturnType).Elements.Count > 1; + var returnIsClosure = hasReturn && swiftReturnType is ClosureTypeSpec; + var returnIsGeneric = hasReturn && typeContext.IsTypeSpecGeneric(swiftReturnType) && !returnIsClosure; + var returnIsAssocPath = hasReturn && typeContext.IsProtocolWithAssociatedTypesFullPath(swiftReturnType as NamedTypeSpec, typeMapper); + var returnIsNonScalarStruct = hasReturn && !returnIsScalar && returnEntity != null && + (returnEntity.EntityType == EntityType.Struct || returnEntity.EntityType == EntityType.Enum); + var returnIsSelf = hasReturn && swiftReturnType.IsDynamicSelf; + + var retSimple = returnType as CSSimpleType; + var returnIsInterfaceFromProtocol = + hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Protocol && retSimple != null; + var returnIsProtocolList = hasReturn && swiftReturnType is ProtocolListTypeSpec; + var returnIsObjCProtocol = hasReturn && returnEntity != null && returnEntity.IsObjCProtocol; + var returnNeedsPostProcessing = (hasReturn && (returnIsClass || returnIsProtocolList || returnIsInterfaceFromProtocol || returnIsNonTrivialTuple || + returnIsGeneric || returnIsNonScalarStruct || returnIsAssocPath || (returnIsSelf && !restoreDynamicSelf))) || originalThrows + || returnIsTrivialEnum; + + includeCastToReturnType = includeCastToReturnType || returnIsTrivialEnum; + includeIntermediateCastToLong = includeIntermediateCastToLong || returnIsTrivialEnum; + + var filteredTypeSpec = FilterParams(parms, wrapperFuncDecl, originalThrows); + + var callParameters = new List(parms.Count); + + var offsetToOriginalArgs = 0; + if ((hasReturn && indexOfReturn >= 0) || originalThrows) + offsetToOriginalArgs++; + if (swiftInstanceType != null) + offsetToOriginalArgs++; + if (isExtensionMethod && swiftInstanceType == null) + offsetToOriginalArgs++; + + for (int i = 0; i < parms.Count; i++) + { + var p = parms[i]; + // if it's the instance, pass that + // if it's the return, pass that + // otherwise take it from the original functions primary parameter list + TypeSpec originalParm = null; + + if (i == indexOfInstance && swiftInstanceType != null) + { + originalParm = swiftInstanceType; + } + else if ((hasReturn && i == indexOfReturn) || (originalThrows && i == indexOfReturn)) + { + originalParm = swiftReturnType; + } + else if (isExtensionMethod && p.ParameterKind == CSParameterKind.This) + { + originalParm = originalFunction.IsExtension ? originalFunction.ParentExtension.ExtensionOnType : + new NamedTypeSpec(originalFunction.Parent.ToFullyQualifiedNameWithGenerics()); + } + else + { + var index = i - offsetToOriginalArgs; + originalParm = originalFunction.ParameterLists.Last()[i - offsetToOriginalArgs].TypeSpec; + } + callParameters.Add(Marshal(typeContext, wrapperFuncDecl, p, filteredTypeSpec[i], instanceIsSwiftProtocol && i == indexOfInstance, + indexOfReturn >= 0 && i == indexOfReturn, originalParm)); + } + + + var call = new CSFunctionCall(pinvokeCall, false, callParameters.ToArray()); + + // Post marshal code demands an intermediate return value + if (postMarshalCode.Count > 0 && ((object)returnIdent) == null && (returnType != null && returnType != CSSimpleType.Void)) + { + returnIdent = new CSIdentifier(Uniqueify("retval", identifiersUsed)); + identifiersUsed.Add(returnIdent.Name); + preMarshalCode.Add(CSVariableDeclaration.VarLine(returnType, returnIdent, returnType.Default())); + } + + + if (((object)returnIdent) != null) + { + // if returnIntPtr is non-null, then the function returns a pointer to a class + // If this is the case, we have post marshal code which will assign it to + // retval. + + if (typeMapper.MustForcePassByReference(typeContext, swiftReturnType) || returnIsNonTrivialTuple || returnIsProtocolList) + { + this.functionCall = new CSLine(call); + } + else + { + CSBaseExpression callExpr = call; + if (includeCastToReturnType && returnType != null && returnType != CSSimpleType.Void) + { + if (includeIntermediateCastToLong) + { + callExpr = new CSCastExpression(CSSimpleType.Long, callExpr); + } + callExpr = new CSCastExpression(returnType, callExpr); + } + this.functionCall = CSAssignment.Assign((returnIntPtr ?? returnProtocol) ?? returnIdent, callExpr); + } + this.returnLine = CSReturn.ReturnLine(returnIdent); + } + else + { + if (returnType != null && returnType != CSSimpleType.Void) + { + if (includeCastToReturnType) + { + CSBaseExpression expr = call; + if (includeIntermediateCastToLong) + { + expr = new CSCastExpression(CSSimpleType.Long, expr); + } + expr = new CSCastExpression(returnType, expr); + this.functionCall = CSReturn.ReturnLine(expr); + } + else + { + this.functionCall = CSReturn.ReturnLine((ICSExpression)call); + } + } + else + this.functionCall = new CSLine(call); + } + + foreach (var l in absolutelyMustBeFirst) + yield return l; + foreach (var l in preMarshalCode) + yield return l; + yield return functionCall; + foreach (var l in postMarshalCode) + yield return l; + if (returnLine != null) + yield return returnLine; + } + + CSParameter ReworkParameterWithNamer(CSParameter p) + { + if (GenericReferenceNamer == null) + return p; + var pClone = ReworkTypeWithNamer(p.CSType); + return new CSParameter(pClone, p.Name, p.ParameterKind, p.DefaultValue); + } + + CSType ReworkTypeWithNamer(CSType ty) + { + if (ty is CSGenericReferenceType genRef) + { + var newGen = new CSGenericReferenceType(genRef.Depth, genRef.Index); + newGen.ReferenceNamer = GenericReferenceNamer; + return newGen; + } + else if (ty is CSSimpleType simple) + { + if (simple.GenericTypes == null) + return simple; + var genSubTypes = new CSType[simple.GenericTypes.Length]; + for (int i = 0; i < genSubTypes.Length; i++) + { + genSubTypes[i] = ReworkTypeWithNamer(simple.GenericTypes[i]); + } + var simpleClone = new CSSimpleType(simple.GenericTypeName, simple.IsArray, genSubTypes); + return simpleClone; + } + else + { + throw new NotImplementedException($"Unable to rework type {ty.GetType().Name} {ty.ToString()} as generic reference"); + } + } + + CSBaseExpression Marshal(BaseDeclaration typeContext, FunctionDeclaration funcDecl, CSParameter p, TypeSpec swiftType, + bool marshalProtocolAsValueType, bool isReturnVariable, TypeSpec originalType) + { + p = ReworkParameterWithNamer(p); + + var entityType = typeMapper.GetEntityTypeForTypeSpec(swiftType); + switch (entityType) + { + case EntityType.Scalar: + case EntityType.Tuple: + case EntityType.None: + // Add more types + break; + } + throw new NotImplementedException($"Uh-oh - not ready for {swiftType.ToString()}, a {entityType}."); + } + + public static string Uniqueify(string name, IEnumerable names) + { + int thisTime = 0; + var sb = new StringBuilder(name); + while (names.Contains(sb.ToString())) + { + sb.Clear().Append(name).Append(thisTime++); + } + return sb.ToString(); + } + + TypeSpec[] FilterParams(CSParameterList parms, FunctionDeclaration wrapperFunc, bool originalThrows) + { + var results = new TypeSpec[parms.Count]; + var parameterList = wrapperFunc.ParameterLists.Last(); + for (int i = 0; i < parms.Count; i++) + { + var currType = parameterList[i].TypeSpec; + results[i] = currType; + } + return results; + } + + List absolutelyMustBeFirst; + List preMarshalCode; + CSLine functionCall; + List postMarshalCode; + CSLine returnLine; + + public bool MarshalProtocolsDirectly { get; set; } + public bool RequiredUnsafeCode { get; private set; } + public bool MarshalingConstructor { get; set; } + public Func GenericReferenceNamer { get; set; } + public CSType ProtocolInterfaceType { get; set; } + + } } diff --git a/src/SwiftReflector/PunyCode.cs b/src/SwiftReflector/PunyCode.cs index 1b342c8be262..fa792b740d0c 100644 --- a/src/SwiftReflector/PunyCode.cs +++ b/src/SwiftReflector/PunyCode.cs @@ -6,156 +6,168 @@ using System.Linq; using System.Text; -namespace SwiftReflector { - public class PunyCode { - const string kEncodingStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"; - - Dictionary decodeTable; - const int kBase = 36; - const int tMin = 1; - const int tMax = 26; - const int skew = 38; - const int damp = 700; - const int initialBias = 72; - const int initialN = 0x80; - const char delimiter = '_'; - - public PunyCode () - { - decodeTable = MakeDecodeTable (kEncodingStr); - } - - public Dictionary MakeDecodeTable (string s) - { - var table = new Dictionary (); - for (int i = 0; i < s.Length; i++) { - table [s [i]] = i; - } - return table; - } - - static int Adapt (int delta, int numPoints, bool firstTime) - { - delta = delta / (firstTime ? damp : 2); - - delta += delta / numPoints; - int k = 0; - while (delta > ((kBase - tMin) * tMax) / 2) { - delta = delta / (kBase - tMin); - k = k + kBase; - } - k += ((kBase - tMin + 1) * delta) / (delta + skew); - return k; - } - - public string Decode (string input) - { - - int n = initialN; - int i = 0; - int bias = initialBias; - var output = new StringBuilder (); - - int pos = 0; - var delim = input.LastIndexOf ('_'); - if (delim > 0) { - output.Append (input.Substring (0, delim)); - pos = delim + 1; - } - - int outputLength = output.Length; - int inputLength = input.Length; - while (pos < inputLength) { - int oldi = i; - int w = 1; - for (int k = kBase; ; k += kBase) { - int digit = decodeTable [input [pos++]]; - i = i + (digit * w); - int t = Math.Max (Math.Min (k - bias, tMax), tMin); - if (digit < t) { - break; - } - w = w * (kBase - t); - } - bias = Adapt (i - oldi, ++outputLength, (oldi == 0)); - n = n + i / outputLength; - i = i % outputLength; - if (n >= 0xd800 && n <= 0xdfff) - output.Insert (i, (char)n); - else - output.Insert (i, Char.ConvertFromUtf32 (n)); - i++; - } - return output.ToString (); - } - - static int digit_index (char value) - { - if (value >= 'a' && value <= 'z') - return value - 'a'; - if (value >= 'A' && value <= 'J') - return value - 'A' + 26; - return -1; - } - - // I'm leaving this here for possible future need. - // This is a port of Apple's decode which is more or less equivalent to - // the above Decode. They both have their plusses and minuses, but I like Apple's - // lees, so it's not (currently) active. - - public string AppleDecode (string inputPunyCode) - { - var output = new StringBuilder (); - int i = 0; - var n = initialN; - var bias = initialBias; - - var lastDelimiter = inputPunyCode.LastIndexOf (delimiter); - if (lastDelimiter > 0) { - for (int x=0; x < lastDelimiter; x++) { - if (inputPunyCode [x] > 0x7f) - return output.ToString (); - output.Append (inputPunyCode [x]); - } - } - - var inputPunySlice = new StringSlice (inputPunyCode.Substring (lastDelimiter + 1)); - - while (!inputPunySlice.IsAtEnd) { - var oldi = i; - var w = 1; - for (int k = kBase; ; k += kBase) { - if (inputPunySlice.IsAtEnd) - return output.ToString (); - var codePoint = inputPunySlice.Advance (); - - var digit = digit_index (codePoint); - if (digit < 0) - return output.ToString (); - - i = i + digit * w; - var t = k <= bias ? tMin - : (k >= bias + tMax ? tMax : k - bias); - if (digit < t) - break; - w = w * (kBase - t); - } - bias = Adapt (i - oldi, output.Length + 1, oldi == 0); - n = n + i / (output.Length + 1); - i = i % (output.Length + 1); - if (n < 0x80) - return output.ToString (); - if (n >= 0xd800 && n <= 0xdfff) - output.Insert (i, (char)n); - else - output.Insert (i, Char.ConvertFromUtf32 (n)); - i++; - } - return output.ToString (); - } - - static PunyCode _puny = new PunyCode (); - public static PunyCode PunySingleton { get { return _puny; } } - } +namespace SwiftReflector +{ + public class PunyCode + { + const string kEncodingStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"; + + Dictionary decodeTable; + const int kBase = 36; + const int tMin = 1; + const int tMax = 26; + const int skew = 38; + const int damp = 700; + const int initialBias = 72; + const int initialN = 0x80; + const char delimiter = '_'; + + public PunyCode() + { + decodeTable = MakeDecodeTable(kEncodingStr); + } + + public Dictionary MakeDecodeTable(string s) + { + var table = new Dictionary(); + for (int i = 0; i < s.Length; i++) + { + table[s[i]] = i; + } + return table; + } + + static int Adapt(int delta, int numPoints, bool firstTime) + { + delta = delta / (firstTime ? damp : 2); + + delta += delta / numPoints; + int k = 0; + while (delta > ((kBase - tMin) * tMax) / 2) + { + delta = delta / (kBase - tMin); + k = k + kBase; + } + k += ((kBase - tMin + 1) * delta) / (delta + skew); + return k; + } + + public string Decode(string input) + { + + int n = initialN; + int i = 0; + int bias = initialBias; + var output = new StringBuilder(); + + int pos = 0; + var delim = input.LastIndexOf('_'); + if (delim > 0) + { + output.Append(input.Substring(0, delim)); + pos = delim + 1; + } + + int outputLength = output.Length; + int inputLength = input.Length; + while (pos < inputLength) + { + int oldi = i; + int w = 1; + for (int k = kBase; ; k += kBase) + { + int digit = decodeTable[input[pos++]]; + i = i + (digit * w); + int t = Math.Max(Math.Min(k - bias, tMax), tMin); + if (digit < t) + { + break; + } + w = w * (kBase - t); + } + bias = Adapt(i - oldi, ++outputLength, (oldi == 0)); + n = n + i / outputLength; + i = i % outputLength; + if (n >= 0xd800 && n <= 0xdfff) + output.Insert(i, (char)n); + else + output.Insert(i, Char.ConvertFromUtf32(n)); + i++; + } + return output.ToString(); + } + + static int digit_index(char value) + { + if (value >= 'a' && value <= 'z') + return value - 'a'; + if (value >= 'A' && value <= 'J') + return value - 'A' + 26; + return -1; + } + + // I'm leaving this here for possible future need. + // This is a port of Apple's decode which is more or less equivalent to + // the above Decode. They both have their plusses and minuses, but I like Apple's + // lees, so it's not (currently) active. + + public string AppleDecode(string inputPunyCode) + { + var output = new StringBuilder(); + int i = 0; + var n = initialN; + var bias = initialBias; + + var lastDelimiter = inputPunyCode.LastIndexOf(delimiter); + if (lastDelimiter > 0) + { + for (int x = 0; x < lastDelimiter; x++) + { + if (inputPunyCode[x] > 0x7f) + return output.ToString(); + output.Append(inputPunyCode[x]); + } + } + + var inputPunySlice = new StringSlice(inputPunyCode.Substring(lastDelimiter + 1)); + + while (!inputPunySlice.IsAtEnd) + { + var oldi = i; + var w = 1; + for (int k = kBase; ; k += kBase) + { + if (inputPunySlice.IsAtEnd) + return output.ToString(); + var codePoint = inputPunySlice.Advance(); + + var digit = digit_index(codePoint); + if (digit < 0) + return output.ToString(); + + i = i + digit * w; + var t = k <= bias ? tMin + : (k >= bias + tMax ? tMax : k - bias); + if (digit < t) + break; + w = w * (kBase - t); + } + bias = Adapt(i - oldi, output.Length + 1, oldi == 0); + n = n + i / (output.Length + 1); + i = i % (output.Length + 1); + if (n < 0x80) + return output.ToString(); + if (n >= 0xd800 && n <= 0xdfff) + output.Insert(i, (char)n); + else + output.Insert(i, Char.ConvertFromUtf32(n)); + i++; + } + return output.ToString(); + } + + static PunyCode _puny = new PunyCode(); + public static PunyCode PunySingleton { get { return _puny; } } + } } diff --git a/src/SwiftReflector/ReflectorError.cs b/src/SwiftReflector/ReflectorError.cs index 06d753b007a7..5b56fcb6708d 100644 --- a/src/SwiftReflector/ReflectorError.cs +++ b/src/SwiftReflector/ReflectorError.cs @@ -6,53 +6,60 @@ using SwiftReflector.ExceptionTools; using System.Linq; -namespace SwiftReflector { - - // Range of error messages - // 0000 - total abject failure - // 0500 - should never, ever happen. Ever. (skipped case, argument null, argument out of range) - // 1000 - compiler error, generating C# - // 1500 - compiler error, C# trying to reference swift wrapper - // 2500 - importing types from C# bindings - // 2000 - wrapping error, wrapping swift code in C# callable wrappers - // 3000 - decomposition error, demangling swift symbols - // 4000 - error dropping swift symbols into inventory - // 5000 - error reflecting on swift module - // 6000 - error parsing TypeSpec - // 7000 - error mapping one type to another - - - public class ReflectorError { - public const int kCantHappenBase = 500; - public const int kCompilerBase = 1000; - public const int kCompilerReferenceBase = 1500; - public const int kWrappingBase = 2000; - public const int kImportingBase = 2500; - public const int kDecomposeBase = 3000; - public const int kInventoryBase = 4000; - public const int kReflectionErrorBase = 5000; - public const int kTypeParseBase = 6000; - public const int kTypeMapBase = 7000; - - public ReflectorError (Exception e) - { - if (e is RuntimeException re) { - Exception = re; - Error = re.Error; - } else if (e is AggregateException ae && ae.InnerExceptions.All ((v) => v is RuntimeException)) { - Exception = ae; - // If any of the exceptions is an error, the whole collection is an error as well. - Error = ae.InnerExceptions.Cast ().Any ((v) => v.Error); - } else { - Exception = new RuntimeException (kCantHappenBase + 54, error: true, innerException: e, message: e.Message); - Error = true; - } - } - - public Exception Exception { get; private set; } - public bool Error { get; private set; } - - public bool IsWarning => !Error; - public string Message => Exception.Message; - } +namespace SwiftReflector +{ + + // Range of error messages + // 0000 - total abject failure + // 0500 - should never, ever happen. Ever. (skipped case, argument null, argument out of range) + // 1000 - compiler error, generating C# + // 1500 - compiler error, C# trying to reference swift wrapper + // 2500 - importing types from C# bindings + // 2000 - wrapping error, wrapping swift code in C# callable wrappers + // 3000 - decomposition error, demangling swift symbols + // 4000 - error dropping swift symbols into inventory + // 5000 - error reflecting on swift module + // 6000 - error parsing TypeSpec + // 7000 - error mapping one type to another + + + public class ReflectorError + { + public const int kCantHappenBase = 500; + public const int kCompilerBase = 1000; + public const int kCompilerReferenceBase = 1500; + public const int kWrappingBase = 2000; + public const int kImportingBase = 2500; + public const int kDecomposeBase = 3000; + public const int kInventoryBase = 4000; + public const int kReflectionErrorBase = 5000; + public const int kTypeParseBase = 6000; + public const int kTypeMapBase = 7000; + + public ReflectorError(Exception e) + { + if (e is RuntimeException re) + { + Exception = re; + Error = re.Error; + } + else if (e is AggregateException ae && ae.InnerExceptions.All((v) => v is RuntimeException)) + { + Exception = ae; + // If any of the exceptions is an error, the whole collection is an error as well. + Error = ae.InnerExceptions.Cast().Any((v) => v.Error); + } + else + { + Exception = new RuntimeException(kCantHappenBase + 54, error: true, innerException: e, message: e.Message); + Error = true; + } + } + + public Exception Exception { get; private set; } + public bool Error { get; private set; } + + public bool IsWarning => !Error; + public string Message => Exception.Message; + } } diff --git a/src/SwiftReflector/StringSlice.cs b/src/SwiftReflector/StringSlice.cs index cc271e8b08cf..38f2e0c8264a 100644 --- a/src/SwiftReflector/StringSlice.cs +++ b/src/SwiftReflector/StringSlice.cs @@ -6,211 +6,228 @@ using System.Collections.Generic; using SwiftRuntimeLibrary; -namespace SwiftReflector { - public class StringSlice { - string slice; - - public StringSlice (string s) - { - slice = Exceptions.ThrowOnNull (s, "s"); - } - - public bool StartsWith (char c) - { - return Current == c; - } - - public bool StartsWith (string s) - { - if (s == null) - throw new ArgumentNullException (nameof(s)); - if (s == "") - return true; // I guess? - if (s.Length > Length) - return false; - for (int i = 0; i < s.Length; i++) { - if (s [i] != this [i]) - return false; - } - return true; - } - - public char Current { - get { - // returns the current character in the slice - // this[0] always points to the character (see - // the indexer). - if (IsAtEnd) - throw new ArgumentException ("at end"); - return this [0]; - } - } - - public bool IsAtEnd { get { return Position == slice.Length; } } - - public int Position { get; private set; } - public int Length { get { return slice.Length - Position; } } - - public string Original { get { return slice; } } - - public override string ToString () - { - if (IsAtEnd) - return ""; - return Position == 0 ? slice : slice.Substring (Current); - } - - public char Advance () - { - if (IsAtEnd) { - throw new IndexOutOfRangeException (); - } - char c = Current; - Position++; - return c; - } - - public bool AdvanceIfEquals (char c) - { - return AdvanceIf (sl => sl.Current == c); - } - - public bool AdvanceIf (Predicate pred) - { - if (pred == null) - throw new ArgumentNullException (); - bool eq = pred (this); - if (eq) - Advance (); - return eq; - } - - public string Advance (int n) - { - if (n < 0 || n + Position > slice.Length) - throw new ArgumentOutOfRangeException (nameof(n)); - if (n == 0) - return ""; - string sub = slice.Substring (Position, n); - Position += n; - return sub; - } - - public void Rewind() - { - if (Position <= 0) - throw new InvalidOperationException ("Can't rewind a slice already at the start."); - Position -= 1; - } - - public char this [int index] { - get { - if (index + Position >= slice.Length) - throw new IndexOutOfRangeException (); - return slice [index + Position]; - } - } - - static bool IsNameStart (char c) - { - return Char.IsDigit (c) || c == 'X'; - } - - public bool IsNameNext { - get { - return !IsAtEnd && IsNameStart (Current); - } - } - - public string ConsumeRemaining() - { - if (IsAtEnd) - return ""; - var result = slice.Substring (Position); - Advance (result.Length); - return result; - } - - public string Substring(int position, int length) - { - return slice.Substring (position, length); - } - - public string ExtractSwiftString (out bool isPunyCode) - { - if (!IsNameNext) { - isPunyCode = false; - return null; - } - - int count = 0; - - if ((isPunyCode = Current == 'X')) - Advance (); - - while (!IsAtEnd && Char.IsDigit (Current)) { - count = count * 10 + Advance () - '0'; - } - return Advance (count); - } - - public SwiftName ExtractSwiftName () - { - bool isPunyCode = false; - string s = ExtractSwiftString (out isPunyCode); - if (s == null) - return null; - return new SwiftName (s, isPunyCode); - } - - public SwiftName ExtractSwiftNameMaybeOperator (out OperatorType oper) - { - oper = OperatorType.None; - if (StartsWith ('o')) { - Advance (); - char c = Advance (); - switch (c) { - case 'p': - oper = OperatorType.Prefix; - break; - case 'P': - oper = OperatorType.Postfix; - break; - case 'i': - oper = OperatorType.Infix; - break; - default: - break; - } - } - bool isPunyCode = false; - string s = ExtractSwiftString (out isPunyCode); - if (s == null) - return null; - if (oper != OperatorType.None) { - s = DecodeOperatorName (s); - } - return new SwiftName (s, isPunyCode); - } - - static string _opChars = "& @/= > <*!|+?%-~ ^ ."; - static string DecodeOperatorName (string s) - { - var sb = new StringBuilder (); - foreach (char c in s) { - if (c > 32767) { - sb.Append (c); - continue; - } - if (c < 'a' || c > 'z') - throw new ArgumentOutOfRangeException (nameof(s), String.Format ("operator name '{0}' contains illegal characters", s)); - char o = _opChars [c - 'a']; - sb.Append (o); - } - return sb.ToString (); - } - - - } +namespace SwiftReflector +{ + public class StringSlice + { + string slice; + + public StringSlice(string s) + { + slice = Exceptions.ThrowOnNull(s, "s"); + } + + public bool StartsWith(char c) + { + return Current == c; + } + + public bool StartsWith(string s) + { + if (s == null) + throw new ArgumentNullException(nameof(s)); + if (s == "") + return true; // I guess? + if (s.Length > Length) + return false; + for (int i = 0; i < s.Length; i++) + { + if (s[i] != this[i]) + return false; + } + return true; + } + + public char Current + { + get + { + // returns the current character in the slice + // this[0] always points to the character (see + // the indexer). + if (IsAtEnd) + throw new ArgumentException("at end"); + return this[0]; + } + } + + public bool IsAtEnd { get { return Position == slice.Length; } } + + public int Position { get; private set; } + public int Length { get { return slice.Length - Position; } } + + public string Original { get { return slice; } } + + public override string ToString() + { + if (IsAtEnd) + return ""; + return Position == 0 ? slice : slice.Substring(Current); + } + + public char Advance() + { + if (IsAtEnd) + { + throw new IndexOutOfRangeException(); + } + char c = Current; + Position++; + return c; + } + + public bool AdvanceIfEquals(char c) + { + return AdvanceIf(sl => sl.Current == c); + } + + public bool AdvanceIf(Predicate pred) + { + if (pred == null) + throw new ArgumentNullException(); + bool eq = pred(this); + if (eq) + Advance(); + return eq; + } + + public string Advance(int n) + { + if (n < 0 || n + Position > slice.Length) + throw new ArgumentOutOfRangeException(nameof(n)); + if (n == 0) + return ""; + string sub = slice.Substring(Position, n); + Position += n; + return sub; + } + + public void Rewind() + { + if (Position <= 0) + throw new InvalidOperationException("Can't rewind a slice already at the start."); + Position -= 1; + } + + public char this[int index] + { + get + { + if (index + Position >= slice.Length) + throw new IndexOutOfRangeException(); + return slice[index + Position]; + } + } + + static bool IsNameStart(char c) + { + return Char.IsDigit(c) || c == 'X'; + } + + public bool IsNameNext + { + get + { + return !IsAtEnd && IsNameStart(Current); + } + } + + public string ConsumeRemaining() + { + if (IsAtEnd) + return ""; + var result = slice.Substring(Position); + Advance(result.Length); + return result; + } + + public string Substring(int position, int length) + { + return slice.Substring(position, length); + } + + public string ExtractSwiftString(out bool isPunyCode) + { + if (!IsNameNext) + { + isPunyCode = false; + return null; + } + + int count = 0; + + if ((isPunyCode = Current == 'X')) + Advance(); + + while (!IsAtEnd && Char.IsDigit(Current)) + { + count = count * 10 + Advance() - '0'; + } + return Advance(count); + } + + public SwiftName ExtractSwiftName() + { + bool isPunyCode = false; + string s = ExtractSwiftString(out isPunyCode); + if (s == null) + return null; + return new SwiftName(s, isPunyCode); + } + + public SwiftName ExtractSwiftNameMaybeOperator(out OperatorType oper) + { + oper = OperatorType.None; + if (StartsWith('o')) + { + Advance(); + char c = Advance(); + switch (c) + { + case 'p': + oper = OperatorType.Prefix; + break; + case 'P': + oper = OperatorType.Postfix; + break; + case 'i': + oper = OperatorType.Infix; + break; + default: + break; + } + } + bool isPunyCode = false; + string s = ExtractSwiftString(out isPunyCode); + if (s == null) + return null; + if (oper != OperatorType.None) + { + s = DecodeOperatorName(s); + } + return new SwiftName(s, isPunyCode); + } + + static string _opChars = "& @/= > <*!|+?%-~ ^ ."; + static string DecodeOperatorName(string s) + { + var sb = new StringBuilder(); + foreach (char c in s) + { + if (c > 32767) + { + sb.Append(c); + continue; + } + if (c < 'a' || c > 'z') + throw new ArgumentOutOfRangeException(nameof(s), String.Format("operator name '{0}' contains illegal characters", s)); + char o = _opChars[c - 'a']; + sb.Append(o); + } + return sb.ToString(); + } + + + } } diff --git a/src/SwiftReflector/SwiftClassName.cs b/src/SwiftReflector/SwiftClassName.cs index da6c1cf424ef..e1bbf672dec2 100644 --- a/src/SwiftReflector/SwiftClassName.cs +++ b/src/SwiftReflector/SwiftClassName.cs @@ -8,95 +8,100 @@ using SwiftReflector.Demangling; using SwiftRuntimeLibrary; -namespace SwiftReflector { - public class SwiftClassName { - public SwiftClassName (SwiftName module, IList nesting, IList nestingNames, OperatorType oper = OperatorType.None) - { - Module = Exceptions.ThrowOnNull (module, "module"); - Nesting = Exceptions.ThrowOnNull (nesting, "nesting"); - NestingNames = Exceptions.ThrowOnNull (nestingNames, "nestingNames"); - Terminus = NestingNames.Count > 0 ? NestingNames [NestingNames.Count - 1] : null; - Operator = oper; - } +namespace SwiftReflector +{ + public class SwiftClassName + { + public SwiftClassName(SwiftName module, IList nesting, IList nestingNames, OperatorType oper = OperatorType.None) + { + Module = Exceptions.ThrowOnNull(module, "module"); + Nesting = Exceptions.ThrowOnNull(nesting, "nesting"); + NestingNames = Exceptions.ThrowOnNull(nestingNames, "nestingNames"); + Terminus = NestingNames.Count > 0 ? NestingNames[NestingNames.Count - 1] : null; + Operator = oper; + } - public static SwiftClassName FromFullyQualifiedName (string fullyQualifiedName, OperatorType oper, params char [] nesting) - { - string [] parts = Exceptions.ThrowOnNull (fullyQualifiedName, "fullyQualifiedName").Split ('.'); - if (parts.Length < 2) - throw new ArgumentException (String.Format ("Fully qualified name '{0}' requires at least a module and one name.", - fullyQualifiedName)); - if (nesting.Length != parts.Length - 1) - throw new ArgumentException (String.Format ("Nesting should have {0} elements, but has {1}.", - parts.Length - 1, nesting.Length), "nesting"); - SwiftName module = new SwiftName (parts [0], false); - List nestingNames = parts.Skip (1).Select (name => new SwiftName (name, false)).ToList (); - List actualNesting = nesting.Select (c => Decomposer.ToMaybeMemberNesting (c, true).Value).ToList (); - return new SwiftClassName (module, actualNesting, nestingNames, oper); - } + public static SwiftClassName FromFullyQualifiedName(string fullyQualifiedName, OperatorType oper, params char[] nesting) + { + string[] parts = Exceptions.ThrowOnNull(fullyQualifiedName, "fullyQualifiedName").Split('.'); + if (parts.Length < 2) + throw new ArgumentException(String.Format("Fully qualified name '{0}' requires at least a module and one name.", + fullyQualifiedName)); + if (nesting.Length != parts.Length - 1) + throw new ArgumentException(String.Format("Nesting should have {0} elements, but has {1}.", + parts.Length - 1, nesting.Length), "nesting"); + SwiftName module = new SwiftName(parts[0], false); + List nestingNames = parts.Skip(1).Select(name => new SwiftName(name, false)).ToList(); + List actualNesting = nesting.Select(c => Decomposer.ToMaybeMemberNesting(c, true).Value).ToList(); + return new SwiftClassName(module, actualNesting, nestingNames, oper); + } - public static SwiftClassName FromFullyQualifiedName (string fullyQualifiedName, OperatorType oper, string nesting) - { - return FromFullyQualifiedName (fullyQualifiedName, oper, nesting.ToArray ()); - } + public static SwiftClassName FromFullyQualifiedName(string fullyQualifiedName, OperatorType oper, string nesting) + { + return FromFullyQualifiedName(fullyQualifiedName, oper, nesting.ToArray()); + } - public SwiftName Module { get; private set; } - public IList Nesting { get; private set; } - public IList NestingNames { get; private set; } - public SwiftName Terminus { get; private set; } - public OperatorType Operator { get; set; } + public SwiftName Module { get; private set; } + public IList Nesting { get; private set; } + public IList NestingNames { get; private set; } + public SwiftName Terminus { get; private set; } + public OperatorType Operator { get; set; } - public bool IsClass { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Class; } } - public bool IsStruct { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Struct; } } - public bool IsEnum { get { return Nesting.Count > 0 && Nesting.Last () == MemberNesting.Enum; } } - public bool IsOperator { get { return Operator != OperatorType.None; } } - public string ToFullyQualifiedName (bool includeModule = true) - { - var sb = new StringBuilder (); - if (includeModule) - sb.Append (Module.Name); - for (int i = 0; i < NestingNames.Count; i++) { - if (includeModule || (!includeModule && i > 0)) - sb.Append ('.'); - sb.Append (NestingNames [i].Name); - } - return sb.ToString (); - } + public bool IsClass { get { return Nesting.Count > 0 && Nesting.Last() == MemberNesting.Class; } } + public bool IsStruct { get { return Nesting.Count > 0 && Nesting.Last() == MemberNesting.Struct; } } + public bool IsEnum { get { return Nesting.Count > 0 && Nesting.Last() == MemberNesting.Enum; } } + public bool IsOperator { get { return Operator != OperatorType.None; } } + public string ToFullyQualifiedName(bool includeModule = true) + { + var sb = new StringBuilder(); + if (includeModule) + sb.Append(Module.Name); + for (int i = 0; i < NestingNames.Count; i++) + { + if (includeModule || (!includeModule && i > 0)) + sb.Append('.'); + sb.Append(NestingNames[i].Name); + } + return sb.ToString(); + } - public override int GetHashCode () - { - int hashCode = Module.GetHashCode (); - foreach (SwiftName name in NestingNames) - hashCode += name.GetHashCode (); - return hashCode; - } + public override int GetHashCode() + { + int hashCode = Module.GetHashCode(); + foreach (SwiftName name in NestingNames) + hashCode += name.GetHashCode(); + return hashCode; + } - public override bool Equals (object obj) - { - var other = obj as SwiftClassName; - if (other == null) { - return false; - } - if (other == this) - return true; - return Module.Equals (other.Module) && NamesAreEqual (other); - } + public override bool Equals(object obj) + { + var other = obj as SwiftClassName; + if (other == null) + { + return false; + } + if (other == this) + return true; + return Module.Equals(other.Module) && NamesAreEqual(other); + } - public override string ToString () - { - return ToFullyQualifiedName (true); - } + public override string ToString() + { + return ToFullyQualifiedName(true); + } - bool NamesAreEqual (SwiftClassName other) - { - if (NestingNames.Count != other.NestingNames.Count) - return false; - for (int i = 0; i < NestingNames.Count; i++) { - if (!NestingNames [i].Equals (other.NestingNames [i])) - return false; - } - return true; - } + bool NamesAreEqual(SwiftClassName other) + { + if (NestingNames.Count != other.NestingNames.Count) + return false; + for (int i = 0; i < NestingNames.Count; i++) + { + if (!NestingNames[i].Equals(other.NestingNames[i])) + return false; + } + return true; + } - } + } } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs b/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs index e0583d9d1afa..8dd397dabbbe 100644 --- a/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs +++ b/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs @@ -5,23 +5,26 @@ using System.Linq; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftInterfaceReflector { - public interface IModuleLoader { - bool Load (string moduleName, TypeDatabase into); - } +namespace SwiftReflector.SwiftInterfaceReflector +{ + public interface IModuleLoader + { + bool Load(string moduleName, TypeDatabase into); + } - // this is only useful for tests, really. - public class NoLoadLoader : IModuleLoader { - public NoLoadLoader () - { - } + // this is only useful for tests, really. + public class NoLoadLoader : IModuleLoader + { + public NoLoadLoader() + { + } - public bool Load (string moduleName, TypeDatabase into) - { - if (moduleName == "_Concurrency") - return true; - // only returns true is the module is already loaded - return into.ModuleNames.Contains (moduleName); - } - } + public bool Load(string moduleName, TypeDatabase into) + { + if (moduleName == "_Concurrency") + return true; + // only returns true is the module is already loaded + return into.ModuleNames.Contains(moduleName); + } + } } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs b/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs index 3429dafa31db..69d54e72a7a4 100644 --- a/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs +++ b/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs @@ -8,310 +8,338 @@ using System.Linq; using System.Text; -namespace SwiftReflector.SwiftInterfaceReflector { - public class ObjCSelectorFactory { - XElement funcElement; - - static string [] prepositions = new string [] { - "above", "after", "along", "alongside", "as", "at", - "before", "below", "by", "following", "for", "from", - "given", "in", "including", "inside", "into", "matching", - "of", "on", "passing", "preceding", "since", "to", - "until", "using", "via", "when", "with", "within" - }; - - static string [] pluralSuffixes = new string [] { - "s", "es", "ies" - }; - - public ObjCSelectorFactory (XElement funcElement) - { - this.funcElement = Exceptions.ThrowOnNull (funcElement, nameof (funcElement)); - } - - public string Generate () - { - // it's in an @objc attribute - var providedSelector = ProvidedObjCSelector (); - if (!String.IsNullOrEmpty (providedSelector)) - return providedSelector; - - if (IsDeInit ()) - return "dealloc"; - - var argNames = GetArgumentNames (); - - var baseName = IsInit () ? "init" : - (IsProperty () ? PropertyName () : FunctionName ()); - - if (IsSetter ()) { - return SetterSelector (baseName); - } - - if (IsGetter ()) { - return GetterSelector (baseName); - } - - if (IsSubscriptGetter ()) { - return "objectAtIndexedSubscript:"; - } - - if (IsSubscriptSetter ()) { - return "setObject:atIndexedSubscript:"; - } - - if (IsInit () && argNames.Count == 1 && IsObjCZeroParameterWithLongSelector ()) { - var firstName = argNames [0]; - var sb = new StringBuilder (); - sb.Append ("init"); - if (!IsPreposition (FirstWord (firstName))) - sb.Append ("With"); - sb.Append (CapitalizeFirstLetter (firstName)); - return sb.ToString (); - } - - // at this point, the Apple code needs to know if there are - // foreign async or foreign error conventions. - // The definition of this is opaque enough that it's not clear - // what the conditions are for this predicate, so we're going to - // pretend it doesn't exist for now. - - var asyncConvention = false; - var errorConvention = false; - - var numSelectorPieces = argNames.Count + (asyncConvention ? 1 : 0) - + (errorConvention ? 1 : 0); - - if (numSelectorPieces == 0) - return baseName; - - if (numSelectorPieces == 1 && argNames.Count == 1 && argNames [0] == "_") - return baseName; - - var argIndex = 0; - var selector = new StringBuilder (); - for (var piece = 0; piece != numSelectorPieces; ++piece) { - if (piece > 0) { - if (asyncConvention) { - selector.Append ("completionHandler:"); - continue; - } - - // If we have an error convention that inserts an error parameter - // here, add "error". - if (errorConvention) { - selector.Append ("error:"); - continue; - } - - // Selector pieces beyond the first are simple. - selector.Append (argNames [argIndex++]).Append ('.'); - continue; - } - var firstPiece = baseName; - var scratch = new StringBuilder (); - scratch.Append (firstPiece); - if (asyncConvention) { - // The completion handler is first; append "WithCompletionHandler". - scratch.Append ("WithCompletionHandler"); - firstPiece = scratch.ToString (); - } else if (errorConvention) { - scratch.Append ("AndReturnError"); - firstPiece = scratch.ToString (); - } else if (argNames [argIndex] != "_" && argNames [argIndex] != "") { - // If the first argument name doesn't start with a preposition, and the - // method name doesn't end with a preposition, add "with". - var firstName = argNames [argIndex++]; - if (!IsPreposition (FirstWord (firstName)) && - !IsPreposition (LastWord (firstPiece))) { - scratch.Append ("With"); - } - scratch.Append (CapitalizeFirstLetter (firstName)); - firstPiece = scratch.ToString (); - } else { - ++argIndex; - } - - selector.Append (firstPiece); - if (argNames.Count > 0) - selector.Append (':'); - } - return selector.ToString (); - } - - List GetArgumentNames () - { - var parameterList = funcElement.Descendants (SwiftInterfaceReflector.kParameterList).Last (); - var parameters = parameterList.Descendants (SwiftInterfaceReflector.kParameter).Select ( - p => { - var publicName = p.Attribute (SwiftInterfaceReflector.kPublicName)?.Value; - var privateName = p.Attribute (SwiftInterfaceReflector.kPrivateName).Value; - return String.IsNullOrEmpty (publicName) ? privateName : publicName; - }); - return parameters.ToList (); - } - - string ProvidedObjCSelector () - { - //< attributes > - // < attribute name = "objc" /> - - // - // find the first objc attribute - - var elem = funcElement.Descendants (SwiftInterfaceReflector.kAttribute) - .FirstOrDefault (el => el.Attribute (SwiftInterfaceReflector.kName)?.Value == SwiftInterfaceReflector.kObjC); - if (elem == null) - return null; - var parameters = elem.Descendants (SwiftInterfaceReflector.kAttributeParameter); - if (parameters == null) - return null; - var sb = new StringBuilder (); - foreach (var piece in parameters) { - sb.Append (piece.Attribute (SwiftInterfaceReflector.kValue)?.Value ?? ""); - } - return sb.ToString (); - } - - string GetterSelector (string baseName) - { - return baseName; - } - - string SetterSelector (string baseName) - { - return $"set{CapitalizeFirstLetter (baseName)}:"; - } - - string CapitalizeFirstLetter (string baseName) - { - if (Char.IsLower (baseName [0])) { - return Char.ToUpper (baseName [0]) + baseName.Substring (1); - } - return baseName; - } - - bool IsObjCZeroParameterWithLongSelector () - { - var parameterList = funcElement.Descendants (SwiftInterfaceReflector.kParameterList).Last (); - var onlyParameter = parameterList.Descendants (SwiftInterfaceReflector.kParameter).FirstOrDefault (); - if (onlyParameter == null) - return false; - return onlyParameter.Attribute (SwiftInterfaceReflector.kType)?.Value == "()"; - } - - bool IsDeInit () - { - return FunctionName () == SwiftInterfaceReflector.kDotDtor; - } - - bool IsInit () - { - return FunctionName () == SwiftInterfaceReflector.kDotCtor; - } - - bool IsProperty () - { - return funcElement.Attribute (SwiftInterfaceReflector.kIsProperty)?.Value == "true"; - } - - string PropertyName () - { - return FunctionName ().Substring ("get_".Length); - } - - bool IsGetter () - { - var funcName = FunctionName (); - return IsProperty () && funcName.StartsWith ("get_", StringComparison.Ordinal) && - funcName != SwiftInterfaceReflector.kGetSubscript; - } - - bool IsSetter () - { - var funcName = FunctionName (); - return IsProperty () && funcName.StartsWith ("set_", StringComparison.Ordinal) && - funcName != SwiftInterfaceReflector.kSetSubscript; - } - - bool IsSubscriptGetter () - { - return FunctionName () == SwiftInterfaceReflector.kGetSubscript; - } - - bool IsSubscriptSetter () - { - return FunctionName () == SwiftInterfaceReflector.kSetSubscript; - } - - static bool IsPreposition (string s) - { - return prepositions.Contains (s); - } - - static bool IsPluralSuffix (string s) - { - return pluralSuffixes.Contains (s); - } - - string FunctionName () - { - return funcElement.Attribute (SwiftInterfaceReflector.kName)?.Value; - } - - IEnumerable Words (string src) - { - if (String.IsNullOrEmpty (src)) - yield break; - var length = src.Length; - var start = 0; - - while (start < length) { - if (src [start] == '_') { - start++; - yield return "_"; - continue; - } - var i = start; - while (i < length && Char.IsUpper (src [i])) - i++; - if (i - start > 1) { - var endOfNext = i; - while (endOfNext < length && Char.IsLower (src [endOfNext])) - endOfNext++; - if (i == length || IsPluralSuffix (src.Substring (i, endOfNext - i)) - && src.Substring (i, endOfNext - i).EndsWith ("Is", StringComparison.Ordinal)) { - var word = src.Substring (start, endOfNext - start); - start = endOfNext; - yield return word; - continue; - } else { - if (Char.IsLower (src [i])) - i--; - var word = src.Substring (start, i - start); - start = i; - yield return word; - continue; - } - } - - while (i < length && !Char.IsUpper (src [i]) && src [i] != '_') - i++; - var thisword = src.Substring (start, i - start); - start = i; - yield return thisword; - } - yield break; - } - - string FirstWord (string src) - { - return Words (src).FirstOrDefault () ?? ""; - } - - string LastWord (string src) - { - return Words (src).LastOrDefault () ?? ""; - } - } +namespace SwiftReflector.SwiftInterfaceReflector +{ + public class ObjCSelectorFactory + { + XElement funcElement; + + static string[] prepositions = new string[] { + "above", "after", "along", "alongside", "as", "at", + "before", "below", "by", "following", "for", "from", + "given", "in", "including", "inside", "into", "matching", + "of", "on", "passing", "preceding", "since", "to", + "until", "using", "via", "when", "with", "within" + }; + + static string[] pluralSuffixes = new string[] { + "s", "es", "ies" + }; + + public ObjCSelectorFactory(XElement funcElement) + { + this.funcElement = Exceptions.ThrowOnNull(funcElement, nameof(funcElement)); + } + + public string Generate() + { + // it's in an @objc attribute + var providedSelector = ProvidedObjCSelector(); + if (!String.IsNullOrEmpty(providedSelector)) + return providedSelector; + + if (IsDeInit()) + return "dealloc"; + + var argNames = GetArgumentNames(); + + var baseName = IsInit() ? "init" : + (IsProperty() ? PropertyName() : FunctionName()); + + if (IsSetter()) + { + return SetterSelector(baseName); + } + + if (IsGetter()) + { + return GetterSelector(baseName); + } + + if (IsSubscriptGetter()) + { + return "objectAtIndexedSubscript:"; + } + + if (IsSubscriptSetter()) + { + return "setObject:atIndexedSubscript:"; + } + + if (IsInit() && argNames.Count == 1 && IsObjCZeroParameterWithLongSelector()) + { + var firstName = argNames[0]; + var sb = new StringBuilder(); + sb.Append("init"); + if (!IsPreposition(FirstWord(firstName))) + sb.Append("With"); + sb.Append(CapitalizeFirstLetter(firstName)); + return sb.ToString(); + } + + // at this point, the Apple code needs to know if there are + // foreign async or foreign error conventions. + // The definition of this is opaque enough that it's not clear + // what the conditions are for this predicate, so we're going to + // pretend it doesn't exist for now. + + var asyncConvention = false; + var errorConvention = false; + + var numSelectorPieces = argNames.Count + (asyncConvention ? 1 : 0) + + (errorConvention ? 1 : 0); + + if (numSelectorPieces == 0) + return baseName; + + if (numSelectorPieces == 1 && argNames.Count == 1 && argNames[0] == "_") + return baseName; + + var argIndex = 0; + var selector = new StringBuilder(); + for (var piece = 0; piece != numSelectorPieces; ++piece) + { + if (piece > 0) + { + if (asyncConvention) + { + selector.Append("completionHandler:"); + continue; + } + + // If we have an error convention that inserts an error parameter + // here, add "error". + if (errorConvention) + { + selector.Append("error:"); + continue; + } + + // Selector pieces beyond the first are simple. + selector.Append(argNames[argIndex++]).Append('.'); + continue; + } + var firstPiece = baseName; + var scratch = new StringBuilder(); + scratch.Append(firstPiece); + if (asyncConvention) + { + // The completion handler is first; append "WithCompletionHandler". + scratch.Append("WithCompletionHandler"); + firstPiece = scratch.ToString(); + } + else if (errorConvention) + { + scratch.Append("AndReturnError"); + firstPiece = scratch.ToString(); + } + else if (argNames[argIndex] != "_" && argNames[argIndex] != "") + { + // If the first argument name doesn't start with a preposition, and the + // method name doesn't end with a preposition, add "with". + var firstName = argNames[argIndex++]; + if (!IsPreposition(FirstWord(firstName)) && + !IsPreposition(LastWord(firstPiece))) + { + scratch.Append("With"); + } + scratch.Append(CapitalizeFirstLetter(firstName)); + firstPiece = scratch.ToString(); + } + else + { + ++argIndex; + } + + selector.Append(firstPiece); + if (argNames.Count > 0) + selector.Append(':'); + } + return selector.ToString(); + } + + List GetArgumentNames() + { + var parameterList = funcElement.Descendants(SwiftInterfaceReflector.kParameterList).Last(); + var parameters = parameterList.Descendants(SwiftInterfaceReflector.kParameter).Select( + p => + { + var publicName = p.Attribute(SwiftInterfaceReflector.kPublicName)?.Value; + var privateName = p.Attribute(SwiftInterfaceReflector.kPrivateName).Value; + return String.IsNullOrEmpty(publicName) ? privateName : publicName; + }); + return parameters.ToList(); + } + + string ProvidedObjCSelector() + { + //< attributes > + // < attribute name = "objc" /> + + // + // find the first objc attribute + + var elem = funcElement.Descendants(SwiftInterfaceReflector.kAttribute) + .FirstOrDefault(el => el.Attribute(SwiftInterfaceReflector.kName)?.Value == SwiftInterfaceReflector.kObjC); + if (elem == null) + return null; + var parameters = elem.Descendants(SwiftInterfaceReflector.kAttributeParameter); + if (parameters == null) + return null; + var sb = new StringBuilder(); + foreach (var piece in parameters) + { + sb.Append(piece.Attribute(SwiftInterfaceReflector.kValue)?.Value ?? ""); + } + return sb.ToString(); + } + + string GetterSelector(string baseName) + { + return baseName; + } + + string SetterSelector(string baseName) + { + return $"set{CapitalizeFirstLetter(baseName)}:"; + } + + string CapitalizeFirstLetter(string baseName) + { + if (Char.IsLower(baseName[0])) + { + return Char.ToUpper(baseName[0]) + baseName.Substring(1); + } + return baseName; + } + + bool IsObjCZeroParameterWithLongSelector() + { + var parameterList = funcElement.Descendants(SwiftInterfaceReflector.kParameterList).Last(); + var onlyParameter = parameterList.Descendants(SwiftInterfaceReflector.kParameter).FirstOrDefault(); + if (onlyParameter == null) + return false; + return onlyParameter.Attribute(SwiftInterfaceReflector.kType)?.Value == "()"; + } + + bool IsDeInit() + { + return FunctionName() == SwiftInterfaceReflector.kDotDtor; + } + + bool IsInit() + { + return FunctionName() == SwiftInterfaceReflector.kDotCtor; + } + + bool IsProperty() + { + return funcElement.Attribute(SwiftInterfaceReflector.kIsProperty)?.Value == "true"; + } + + string PropertyName() + { + return FunctionName().Substring("get_".Length); + } + + bool IsGetter() + { + var funcName = FunctionName(); + return IsProperty() && funcName.StartsWith("get_", StringComparison.Ordinal) && + funcName != SwiftInterfaceReflector.kGetSubscript; + } + + bool IsSetter() + { + var funcName = FunctionName(); + return IsProperty() && funcName.StartsWith("set_", StringComparison.Ordinal) && + funcName != SwiftInterfaceReflector.kSetSubscript; + } + + bool IsSubscriptGetter() + { + return FunctionName() == SwiftInterfaceReflector.kGetSubscript; + } + + bool IsSubscriptSetter() + { + return FunctionName() == SwiftInterfaceReflector.kSetSubscript; + } + + static bool IsPreposition(string s) + { + return prepositions.Contains(s); + } + + static bool IsPluralSuffix(string s) + { + return pluralSuffixes.Contains(s); + } + + string FunctionName() + { + return funcElement.Attribute(SwiftInterfaceReflector.kName)?.Value; + } + + IEnumerable Words(string src) + { + if (String.IsNullOrEmpty(src)) + yield break; + var length = src.Length; + var start = 0; + + while (start < length) + { + if (src[start] == '_') + { + start++; + yield return "_"; + continue; + } + var i = start; + while (i < length && Char.IsUpper(src[i])) + i++; + if (i - start > 1) + { + var endOfNext = i; + while (endOfNext < length && Char.IsLower(src[endOfNext])) + endOfNext++; + if (i == length || IsPluralSuffix(src.Substring(i, endOfNext - i)) + && src.Substring(i, endOfNext - i).EndsWith("Is", StringComparison.Ordinal)) + { + var word = src.Substring(start, endOfNext - start); + start = endOfNext; + yield return word; + continue; + } + else + { + if (Char.IsLower(src[i])) + i--; + var word = src.Substring(start, i - start); + start = i; + yield return word; + continue; + } + } + + while (i < length && !Char.IsUpper(src[i]) && src[i] != '_') + i++; + var thisword = src.Substring(start, i - start); + start = i; + yield return thisword; + } + yield break; + } + + string FirstWord(string src) + { + return Words(src).FirstOrDefault() ?? ""; + } + + string LastWord(string src) + { + return Words(src).LastOrDefault() ?? ""; + } + } } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs b/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs index c7aee16d2e35..e438f0077e4c 100644 --- a/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs +++ b/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs @@ -1,18 +1,20 @@ using System; -namespace SwiftReflector.SwiftInterfaceReflector { - public class ParseException : Exception { - public ParseException () - { - } +namespace SwiftReflector.SwiftInterfaceReflector +{ + public class ParseException : Exception + { + public ParseException() + { + } - public ParseException (string message) - : base (message) - { - } + public ParseException(string message) + : base(message) + { + } - public ParseException (string message, Exception inner) - : base (message, inner) - { - } - } + public ParseException(string message, Exception inner) + : base(message, inner) + { + } + } } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs b/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs index 876efcb8ea38..bfe3d037307e 100644 --- a/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs +++ b/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs @@ -17,2314 +17,2452 @@ using System.Threading.Tasks; using System.Threading; -namespace SwiftReflector.SwiftInterfaceReflector { - public class SwiftInterfaceReflector : SwiftInterfaceBaseListener { - // swift-interface-format-version: 1.0 - const string kSwiftInterfaceFormatVersion = "// swift-interface-format-version:"; - // swift-compiler-version: Apple Swift version 5.3 (swiftlang-1200.0.29.2 clang-1200.0.30.1) - const string kSwiftCompilerVersion = "// swift-compiler-version: "; - // swift-module-flags: -target x86_64-apple-macosx10.9 -enable-objc-interop -ena - const string kSwiftModuleFlags = "// swift-module-flags:"; - - internal const string kModuleName = "module-name"; - internal const string kTarget = "target"; - internal const string kIgnore = "IGNORE"; - internal const string kInheritanceKind = "inheritanceKind"; - internal const string kModule = "module"; - internal const string kFunc = "func"; - internal const string kType = "type"; - internal const string kName = "name"; - internal const string kFinal = "final"; - internal const string kPublic = "public"; - internal const string kPrivate = "private"; - internal const string kInternal = "internal"; - internal const string kOpen = "open"; - internal const string kPublicCap = "Public"; - internal const string kPrivateCap = "Private"; - internal const string kInternalCap = "Internal"; - internal const string kOpenCap = "Open"; - internal const string kFilePrivate = "fileprivate"; - internal const string kStatic = "static"; - internal const string kIsStatic = "isStatic"; - internal const string kOptional = "optional"; - internal const string kObjC = "objc"; - internal const string kExtension = "extension"; - internal const string kProtocol = "protocol"; - internal const string kClass = "class"; - internal const string kInnerClasses = "innerclasses"; - internal const string kStruct = "struct"; - internal const string kInnerStructs = "innerstructs"; - internal const string kEnum = "enum"; - internal const string kInnerEnums = "innerenums"; - internal const string kMutating = "mutating"; - internal const string kRequired = "required"; - internal const string kAssociatedTypes = "associatedtypes"; - internal const string kAssociatedType = "associatedtype"; - internal const string kDefaultType = "defaulttype"; - internal const string kConformingProtocols = "conformingprotocols"; - internal const string kConformingProtocol = "conformingprotocol"; - internal const string kMembers = "members"; - internal const string kConvenience = "convenience"; - internal const string kParameterLists = "parameterlists"; - internal const string kParameterList = "parameterlist"; - internal const string kParameter = "parameter"; - internal const string kParam = "param"; - internal const string kGenericParameters = "genericparameters"; - internal const string kWhere = "where"; - internal const string kRelationship = "relationship"; - internal const string kEquals = "equals"; - internal const string kInherits = "inherits"; - internal const string kInherit = "inherit"; - internal const string kIndex = "index"; - internal const string kGetSubscript = "get_subscript"; - internal const string kSetSubscript = "set_subscript"; - internal const string kOperator = "operator"; - internal const string kLittlePrefix = "prefix"; - internal const string kLittlePostfix = "postfix"; - internal const string kPrefix = "Prefix"; - internal const string kPostfix = "Postfix"; - internal const string kInfix = "Infix"; - internal const string kDotCtor = ".ctor"; - internal const string kDotDtor = ".dtor"; - internal const string kNewValue = "newValue"; - internal const string kOperatorKind = "operatorKind"; - internal const string kPublicName = "publicName"; - internal const string kPrivateName = "privateName"; - internal const string kKind = "kind"; - internal const string kNone = "None"; - internal const string kLittleUnknown = "unknown"; - internal const string kUnknown = "Unknown"; - internal const string kOnType = "onType"; - internal const string kAccessibility = "accessibility"; - internal const string kIsVariadic = "isVariadic"; - internal const string kTypeDeclaration = "typedeclaration"; - internal const string kIsAsync = "isAsync"; - internal const string kProperty = "property"; - internal const string kIsProperty = "isProperty"; - internal const string kStorage = "storage"; - internal const string kComputed = "Computed"; - internal const string kEscaping = "escaping"; - internal const string kAutoClosure = "autoclosure"; - internal const string kAttributes = "attributes"; - internal const string kAttribute = "attribute"; - internal const string kAttributeParameterList = "attributeparameterlist"; - internal const string kAttributeParameter = "attributeparameter"; - internal const string kLabel = "Label"; - internal const string kLiteral = "Literal"; - internal const string kSeparator = "Separator"; - internal const string kSublist = "Sublist"; - internal const string kValue = "Value"; - internal const string kObjCSelector = "objcSelector"; - internal const string kDeprecated = "deprecated"; - internal const string kUnavailable = "unavailable"; - internal const string kAvailable = "available"; - internal const string kIntroduced = "introduced"; - internal const string kObsoleted = "obsoleted"; - internal const string kElements = "elements"; - internal const string kElement = "element"; - internal const string kIntValue = "intValue"; - internal const string kRawType = "rawType"; - internal const string kRawValue = "RawValue"; - internal const string kTypeAliases = "typealiases"; - internal const string kTypeAlias = "typealias"; - internal const string kSuperclass = "superclass"; - - Stack currentElement = new Stack (); - Version interfaceVersion; - Version compilerVersion; - - List importModules = new List (); - List operators = new List (); - List> functions = new List> (); - List extensions = new List (); - Dictionary moduleFlags = new Dictionary (); - List nominalTypes = new List (); - List classes = new List (); - List associatedTypesWithConformance = new List (); - List unknownInheritance = new List (); - List typeAliasMap = new List (); - string moduleName; - TypeDatabase typeDatabase; - IModuleLoader moduleLoader; - ICharStream inputStream; - - public SwiftInterfaceReflector (TypeDatabase typeDatabase, IModuleLoader moduleLoader) - { - this.typeDatabase = typeDatabase; - this.moduleLoader = moduleLoader; - } - - public async Task ReflectAsync (string inFile, Stream outStm) - { - Exceptions.ThrowOnNull (inFile, nameof (inFile)); - Exceptions.ThrowOnNull (outStm, nameof (outStm)); - - - await Task.Run (() => { - var xDocument = Reflect (inFile); - xDocument.Save (outStm); - currentElement.Clear (); - }); - } - - public void Reflect (string inFile, Stream outStm) - { - Exceptions.ThrowOnNull (inFile, nameof (inFile)); - Exceptions.ThrowOnNull (outStm, nameof (outStm)); - - var xDocument = Reflect (inFile); - - xDocument.Save (outStm); - currentElement.Clear (); - } - - public async Task ReflectAsync (string inFile) - { - return await Task.Run (() => { - return Reflect (inFile); - }); - } - - public XDocument Reflect (string inFile) - { - // try { - Exceptions.ThrowOnNull (inFile, nameof (inFile)); - - if (!File.Exists (inFile)) - throw new ParseException ($"Input file {inFile} not found"); - - - var fileName = Path.GetFileName (inFile); - moduleName = fileName.Split ('.') [0]; - - var module = new XElement (kModule); - currentElement.Push (module); - - var desugarer = new SyntaxDesugaringParser (inFile); - var desugaredResult = desugarer.Desugar (); - inputStream = CharStreams.fromString (desugaredResult); - - var lexer = new SwiftInterfaceLexer (inputStream); - var tokenStream = new CommonTokenStream (lexer); - var parser = new SwiftInterfaceParser (tokenStream); - var walker = new ParseTreeWalker (); - walker.Walk (this, parser.swiftinterface ()); - - if (currentElement.Count != 1) - throw new ParseException ("At end of parse, stack should contain precisely one element"); - - if (module != currentElement.Peek ()) - throw new ParseException ("Expected the final element to be the initial module"); - - // LoadReferencedModules (); - - // PatchPossibleOperators (); - // PatchExtensionShortNames (); - // PatchExtensionSelfArgs (); - // PatchPossibleBadInheritance (); - // PatchAssociatedTypeConformance (); - - if (typeAliasMap.Count > 0) { - module.Add (new XElement (kTypeAliases, typeAliasMap.ToArray ())); - } - - module.Add (new XAttribute (kName, moduleName)); - SetLanguageVersion (module); - - var tlElement = new XElement ("xamreflect", new XAttribute ("version", "1.0"), - new XElement ("modulelist", module)); - var xDocument = new XDocument (new XDeclaration ("1.0", "utf-8", "yes"), tlElement); - return xDocument; - // } catch (ParseException parseException) { - // throw; - // } catch (Exception e) { - // throw new ParseException ($"Unknown error parsing {inFile}: {e.Message}", e.InnerException); - // } - } - - public override void EnterComment ([NotNull] CommentContext context) - { - var commentText = context.GetText (); - InterpretCommentText (commentText); - } - - public override void EnterClass_declaration ([NotNull] Class_declarationContext context) - { - var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: false); - var attributes = GatherAttributes (context.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isObjC = AttributesContains (context.attributes (), kObjC); - var accessibility = ToAccess (context.access_level_modifier ()); - var isFinal = context.final_clause () != null || accessibility != kOpenCap; - var typeDecl = ToTypeDeclaration (kClass, UnTick (context.class_name ().GetText ()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false); - if (generics != null) - typeDecl.Add (generics); - currentElement.Push (typeDecl); - } - - public override void ExitClass_declaration ([NotNull] Class_declarationContext context) - { - var classElem = currentElement.Pop (); - var givenClassName = classElem.Attribute (kName).Value; - var actualClassName = UnTick (context.class_name ().GetText ()); - if (givenClassName != actualClassName) - throw new ParseException ($"class name mismatch on exit declaration: expected {actualClassName} but got {givenClassName}"); - AddClassToCurrentElement (classElem); - } - - public override void EnterStruct_declaration ([NotNull] Struct_declarationContext context) - { - var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); - var attributes = GatherAttributes (context.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isFinal = true; // structs are always final - var isObjC = AttributesContains (context.attributes (), kObjC); - var accessibility = ToAccess (context.access_level_modifier ()); - var typeDecl = ToTypeDeclaration (kStruct, UnTick (context.struct_name ().GetText ()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), false); - if (generics != null) - typeDecl.Add (generics); - currentElement.Push (typeDecl); - } - - public override void ExitStruct_declaration ([NotNull] Struct_declarationContext context) - { - var structElem = currentElement.Pop (); - var givenStructName = structElem.Attribute (kName).Value; - var actualStructName = UnTick (context.struct_name ().GetText ()); - if (givenStructName != actualStructName) - throw new ParseException ($"struct name mismatch on exit declaration: expected {actualStructName} but got {givenStructName}"); - AddStructToCurrentElement (structElem); - } - - public override void EnterEnum_declaration ([NotNull] Enum_declarationContext context) - { - var inheritanceClause = context.union_style_enum ()?.type_inheritance_clause () ?? - context.raw_value_style_enum ()?.type_inheritance_clause (); - var inheritance = GatherInheritance (inheritanceClause, forceProtocolInheritance: true, removeNonProtocols: true); - var attributes = GatherAttributes (context.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isFinal = true; // enums are always final - var isObjC = AttributesContains (context.attributes (), kObjC); - var accessibility = ToAccess (context.access_level_modifier ()); - var typeDecl = ToTypeDeclaration (kEnum, EnumName (context), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics (EnumGenericParameters (context), EnumGenericWhere (context), false); - if (generics != null) - typeDecl.Add (generics); - currentElement.Push (typeDecl); - } - - public override void ExitEnum_declaration ([NotNull] Enum_declarationContext context) - { - var enumElem = currentElement.Pop (); - var givenEnumName = enumElem.Attribute (kName).Value; - var actualEnumName = EnumName (context); - if (givenEnumName != actualEnumName) - throw new ParseException ($"enum name mismatch on exit declaration: expected {actualEnumName} but got {givenEnumName}"); - - var rawType = GetEnumRawType (context); - if (rawType != null) - enumElem.Add (rawType); - - AddEnumToCurrentElement (enumElem); - } - - static string EnumName (Enum_declarationContext context) - { - return UnTick (context.union_style_enum () != null ? - context.union_style_enum ().enum_name ().GetText () : - context.raw_value_style_enum ().enum_name ().GetText ()); - } - - XAttribute GetEnumRawType (Enum_declarationContext context) - { - var alias = EnumTypeAliases (context).FirstOrDefault (ta => ta.typealias_name ().GetText () == kRawValue); - if (alias == null) - return null; - var rawType = TypeText (alias.typealias_assignment ().type ()); - return new XAttribute (kRawType, rawType); - } - - IEnumerable EnumTypeAliases (Enum_declarationContext context) - { - if (context.union_style_enum () != null) - return UnionTypeAliases (context.union_style_enum ()); - else - return RawTypeAliases (context.raw_value_style_enum ()); - } - - IEnumerable UnionTypeAliases (Union_style_enumContext context) - { - var members = context.union_style_enum_members (); - while (members != null) { - if (members.union_style_enum_member () != null) { - var member = members.union_style_enum_member (); - if (member.nominal_declaration ()?.typealias_declaration () != null) - yield return member.nominal_declaration ().typealias_declaration (); - } - members = members.union_style_enum_members (); - } - yield break; - } - - IEnumerable RawTypeAliases (Raw_value_style_enumContext context) - { - var members = context.raw_value_style_enum_members (); - while (members != null) { - if (members.raw_value_style_enum_member () != null) { - var member = members.raw_value_style_enum_member (); - if (member.nominal_declaration ()?.typealias_declaration () != null) - yield return member.nominal_declaration ().typealias_declaration (); - } - members = members.raw_value_style_enum_members (); - } - yield break; - } - - public override void EnterRaw_value_style_enum_case_clause ([NotNull] Raw_value_style_enum_case_clauseContext context) - { - var enumElements = new XElement (kElements); - foreach (var enumCase in RawCases (context.raw_value_style_enum_case_list ())) { - var enumElement = ToRawEnumElement (enumCase); - enumElements.Add (enumElement); - } - AddEnumNonEmptyElements (enumElements); - } - - public override void EnterUnion_style_enum_case_clause ([NotNull] Union_style_enum_case_clauseContext context) - { - var enumElements = new XElement (kElements); - foreach (var enumCase in UnionCases (context.union_style_enum_case_list ())) { - var enumElement = ToUnionEnumElement (enumCase); - enumElements.Add (enumElement); - } - AddEnumNonEmptyElements (enumElements); - } - - void AddEnumNonEmptyElements (XElement enumElements) - { - if (enumElements.HasElements) { - var currentEnum = currentElement.Peek (); - if (currentEnum.Attribute (kKind)?.Value != kEnum) - throw new ParseException ("Current element needs to be an enum"); - - var existingElements = currentEnum.Element (kElements); - if (existingElements != null) { - foreach (var elem in enumElements.Elements ()) { - existingElements.Add (elem); - } - } else { - currentEnum.Add (enumElements); - } - } - } - - IEnumerable RawCases (Raw_value_style_enum_case_listContext context) - { - while (context != null) { - if (context.raw_value_style_enum_case () != null) { - yield return context.raw_value_style_enum_case (); - } - context = context.raw_value_style_enum_case_list (); - } - yield break; - } - - XElement ToRawEnumElement (Raw_value_style_enum_caseContext context) - { - var enumElem = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ()))); - var value = context.raw_value_assignment (); - if (value != null) - enumElem.Add (new XAttribute (kIntValue, value.raw_value_literal ().GetText ())); - return enumElem; - } - - IEnumerable UnionCases (Union_style_enum_case_listContext context) - { - while (context != null) { - if (context.union_style_enum_case () != null) { - yield return context.union_style_enum_case (); - } - context = context.union_style_enum_case_list (); - } - yield break; - } - - XElement ToUnionEnumElement (Union_style_enum_caseContext context) - { - var enumElement = new XElement (kElement, new XAttribute (kName, UnTick (context.enum_case_name ().GetText ()))); - if (context.tuple_type () != null) { - var tupString = TypeText (context.tuple_type ()); - // special casing: - // the type of a union case is a tuple, but we special case - // unit tuples to be just the type of the unit - // which may be something like ((((((())))))) - // in which case we want to let it come through as is. - // a unit tuple may also have a type label which we don't care - // about so make that go away too. - - if (tupString.IndexOf (',') < 0 && tupString.IndexOf (':') < 0) { - var pastLastOpen = tupString.LastIndexOf ('(') + 1; - var firstClosed = tupString.IndexOf (')'); - if (pastLastOpen != firstClosed) { - tupString = tupString.Substring (pastLastOpen, firstClosed - pastLastOpen); - var colonIndex = tupString.IndexOf (':'); - if (colonIndex >= 0) { - tupString = tupString.Substring (colonIndex + 1); - } - } - } - enumElement.Add (new XAttribute (kType, tupString)); - } - return enumElement; - } - - public override void EnterProtocol_declaration ([NotNull] Protocol_declarationContext context) - { - var inheritance = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); - var attributes = GatherAttributes (context.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isFinal = true; // protocols don't have final - var isObjC = AttributesContains (context.attributes (), kObjC); - var accessibility = ToAccess (context.access_level_modifier ()); - var typeDecl = ToTypeDeclaration (kProtocol, UnTick (context.protocol_name ().GetText ()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - currentElement.Push (typeDecl); - } - - public override void ExitProtocol_declaration ([NotNull] Protocol_declarationContext context) - { - var protocolElem = currentElement.Pop (); - var givenProtocolName = protocolElem.Attribute (kName).Value; - var actualProtocolName = UnTick (context.protocol_name ().GetText ()); - if (givenProtocolName != actualProtocolName) - throw new ParseException ($"protocol name mismatch on exit declaration: expected {actualProtocolName} but got {givenProtocolName}"); - if (currentElement.Peek ().Name != kModule) - throw new ParseException ($"Expected a module on the element stack but found {currentElement.Peek ()}"); - currentElement.Peek ().Add (protocolElem); - } - - public override void EnterProtocol_associated_type_declaration ([NotNull] Protocol_associated_type_declarationContext context) - { - var conformingProtocols = GatherConformingProtocols (context.type_inheritance_clause ()); - var defaultDefn = TypeText (context.typealias_assignment ()?.type ()); - var assocType = new XElement (kAssociatedType, - new XAttribute (kName, UnTick (context.typealias_name ().GetText ()))); - if (defaultDefn != null) - assocType.Add (new XAttribute (kDefaultType, UnTick (defaultDefn))); - if (conformingProtocols != null && conformingProtocols.Count > 0) { - var confomingElem = new XElement (kConformingProtocols, conformingProtocols.ToArray ()); - assocType.Add (confomingElem); - associatedTypesWithConformance.Add (assocType); - } - AddAssociatedTypeToCurrentElement (assocType); - } - - List GatherConformingProtocols (Type_inheritance_clauseContext context) - { - if (context == null) - return null; - var elems = new List (); - if (context.class_requirement () != null) { - // not sure what to do here - // this is just the keyword 'class' - } - var inheritance = context.type_inheritance_list (); - while (inheritance != null) { - var elem = inheritance.GetText (); - var name = TypeText (inheritance.type_identifier ()); - if (name != null) - elems.Add (new XElement (kConformingProtocol, new XAttribute (kName, UnTick (name)))); - inheritance = inheritance.type_inheritance_list (); - } - return elems; - } - - static Generic_parameter_clauseContext EnumGenericParameters (Enum_declarationContext context) - { - return context.union_style_enum ()?.generic_parameter_clause () ?? - context.raw_value_style_enum ()?.generic_parameter_clause (); - } - - static Generic_where_clauseContext EnumGenericWhere (Enum_declarationContext context) - { - return context.union_style_enum ()?.generic_where_clause () ?? - context.raw_value_style_enum ()?.generic_where_clause (); - } - - public override void EnterFunction_declaration ([NotNull] Function_declarationContext context) - { - var head = context.function_head (); - var signature = context.function_signature (); - - var name = UnTick (context.function_name ().GetText ()); - var returnType = signature.function_result () != null ? TypeText (signature.function_result ().type ()) : "()"; - var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); - var isStatic = IsStaticOrClass (head.declaration_modifiers ()); - var hasThrows = signature.throws_clause () != null || signature.rethrows_clause () != null; - var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); - var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); - var isConvenienceInit = false; - var operatorKind = kNone; - var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); - var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); - var isProperty = false; - var attributes = GatherAttributes (head.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isAsync = signature.async_clause () != null; - var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync, attributes); - var generics = HandleGenerics (context.generic_parameter_clause (), context.generic_where_clause (), true); - if (generics != null) - functionDecl.Add (generics); - - - functions.Add (new Tuple (context, functionDecl)); - currentElement.Push (functionDecl); - } - - public override void ExitFunction_declaration ([NotNull] Function_declarationContext context) - { - ExitFunctionWithName (UnTick (context.function_name ().GetText ())); - } - - void ExitFunctionWithName (string expectedName) - { - var functionDecl = currentElement.Pop (); - if (functionDecl.Name != kFunc) - throw new ParseException ($"Expected a func node but got a {functionDecl.Name}"); - var givenName = functionDecl.Attribute (kName); - if (givenName == null) - throw new ParseException ("func node doesn't have a name element"); - if (givenName.Value != expectedName) - throw new ParseException ($"Expected a func node with name {expectedName} but got {givenName.Value}"); - - AddObjCSelector (functionDecl); - - AddElementToParentMembers (functionDecl); - } - - void AddObjCSelector (XElement functionDecl) - { - var selectorFactory = new ObjCSelectorFactory (functionDecl); - var selector = selectorFactory.Generate (); - if (!String.IsNullOrEmpty (selector)) { - functionDecl.Add (new XAttribute (kObjCSelector, selector)); - } - } - - XElement PeekAsFunction () - { - var functionDecl = currentElement.Peek (); - if (functionDecl.Name != kFunc) - throw new ParseException ($"Expected a func node but got a {functionDecl.Name}"); - return functionDecl; - } - - void AddElementToParentMembers (XElement elem) - { - var parent = currentElement.Peek (); - if (parent.Name == kModule) { - parent.Add (elem); - return; - } - var memberElem = GetOrCreate (parent, kMembers); - memberElem.Add (elem); - } - - bool IsInInstance () - { - var parent = currentElement.Peek (); - return parent.Name != kModule; - } - - bool HasObjCElement (XElement elem) - { - var objcAttr = elem.Descendants () - .FirstOrDefault (el => el.Name == kAttribute && el.Attribute ("name")?.Value == kObjC); - return objcAttr != null; - } - - public override void EnterInitializer_declaration ([NotNull] Initializer_declarationContext context) - { - var head = context.initializer_head (); - - var name = kDotCtor; - - // may be optional, otherwise return type is the instance type - var returnType = GetInstanceName () + (head.OpQuestion () != null ? "?" : ""); - var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); - var isStatic = true; - var hasThrows = context.throws_clause () != null || context.rethrows_clause () != null; - var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); - var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); - var isConvenienceInit = ModifiersContains (head.declaration_modifiers (), kConvenience); - var operatorKind = kNone; - var attributes = GatherAttributes (head.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); - var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); - var isProperty = false; - var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, - isAsync: false, attributes); - currentElement.Push (functionDecl); - } - - public override void ExitInitializer_declaration ([NotNull] Initializer_declarationContext context) - { - ExitFunctionWithName (kDotCtor); - } - - public override void EnterDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context) - { - var name = kDotDtor; - var returnType = "()"; - // this might have to be forced to public, otherwise deinit is always internal, which it - // decidedly is NOT. - var accessibility = kPublic; - var isStatic = false; - var hasThrows = false; - var isFinal = ModifiersContains (context.declaration_modifiers (), kFinal); - var isOptional = ModifiersContains (context.declaration_modifiers (), kOptional); - var isConvenienceInit = false; - var operatorKind = kNone; - var attributes = GatherAttributes (context.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isMutating = ModifiersContains (context.declaration_modifiers (), kMutating); - var isRequired = ModifiersContains (context.declaration_modifiers (), kRequired); - var isProperty = false; - var functionDecl = ToFunctionDeclaration (name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - // always has two parameter lists: (instance)() - currentElement.Push (functionDecl); - var parameterLists = new XElement (kParameterLists, MakeInstanceParameterList ()); - currentElement.Pop (); - - parameterLists.Add (new XElement (kParameterList, new XAttribute (kIndex, "1"))); - functionDecl.Add (parameterLists); - - currentElement.Push (functionDecl); - } - - public override void ExitDeinitializer_declaration ([NotNull] Deinitializer_declarationContext context) - { - ExitFunctionWithName (kDotDtor); - } - - public override void EnterSubscript_declaration ([NotNull] Subscript_declarationContext context) - { - // subscripts are...funny. - // They have one parameter list but expand out to two function declarations - // To handle this, we process the parameter list here for the getter - // If there's a setter, we make one of those too. - // Then since we're effectively done, we push a special XElement on the stack - // named IGNORE which will make the parameter list event handler exit. - // On ExitSubscript_declaration, we remove the IGNORE tag - - var head = context.subscript_head (); - var resultType = TypeText (context.subscript_result ().type ()); - var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); - var attributes = GatherAttributes (head.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isStatic = false; - var hasThrows = false; - var isAsync = HasAsync (context.getter_setter_keyword_block ()?.getter_keyword_clause ()); - var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); - var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); - var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); - var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); - var isProperty = true; - - var getParamList = MakeParameterList (head.parameter_clause ().parameter_list (), 1, true); - var getFunc = ToFunctionDeclaration (kGetSubscript, resultType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); - - currentElement.Push (getFunc); - var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList); - currentElement.Pop (); - - getFunc.Add (getParamLists); - AddObjCSelector (getFunc); - - AddElementToParentMembers (getFunc); - - var setParamList = context.getter_setter_keyword_block ()?.setter_keyword_clause () != null - ? MakeParameterList (head.parameter_clause ().parameter_list (), 1, true, startIndex: 1) : null; - - - if (setParamList != null) { - var index = 0; - var parmName = context.getter_setter_keyword_block ().setter_keyword_clause ().new_value_name ()?.GetText () - ?? kNewValue; - var newValueParam = new XElement (kParameter, new XAttribute (nameof (index), index.ToString ()), - new XAttribute (kType, resultType), new XAttribute (kPublicName, ""), - new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false)); - setParamList.AddFirst (newValueParam); - - var setFunc = ToFunctionDeclaration (kSetSubscript, "()", accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - currentElement.Push (setFunc); - var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList); - currentElement.Pop (); - - setFunc.Add (setParamLists); - AddObjCSelector (setFunc); - AddElementToParentMembers (setFunc); - } - - // this makes the subscript parameter list get ignored because we already handled it. - PushIgnore (); - } - - public override void ExitSubscript_declaration ([NotNull] Subscript_declarationContext context) - { - PopIgnore (); - } - - string TypeText (ParserRuleContext ty) - { - return SyntaxDesugaringParser.TypeText (inputStream, ty); - } - - public override void EnterVariable_declaration ([NotNull] Variable_declarationContext context) - { - var head = context.variable_declaration_head (); - var accessibility = AccessibilityFromModifiers (head.declaration_modifiers ()); - var attributes = GatherAttributes (head.attributes ()); - var isDeprecated = CheckForDeprecated (attributes); - var isUnavailable = CheckForUnavailable (attributes); - var isStatic = ModifiersContains (head.declaration_modifiers (), kStatic); - var isFinal = ModifiersContains (head.declaration_modifiers (), kFinal); - var isLet = head.let_clause () != null; - var isOptional = ModifiersContains (head.declaration_modifiers (), kOptional); - var isMutating = ModifiersContains (head.declaration_modifiers (), kMutating); - var isRequired = ModifiersContains (head.declaration_modifiers (), kRequired); - var isProperty = true; - - foreach (var tail in context.variable_declaration_tail ()) { - var name = UnTick (tail.variable_name ().GetText ()); - var resultType = TypeText (tail.type_annotation ().type ()); - var hasThrows = false; - var isAsync = HasAsync (tail.getter_setter_keyword_block ()?.getter_keyword_clause ()); - - var getParamList = new XElement (kParameterList, new XAttribute (kIndex, "1")); - var getFunc = ToFunctionDeclaration ("get_" + name, - resultType, accessibility, isStatic, hasThrows, isFinal, isOptional, - isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, - isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); - - currentElement.Push (getFunc); - var getParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), getParamList); - currentElement.Pop (); - getFunc.Add (getParamLists); - AddElementToParentMembers (getFunc); - AddObjCSelector (getFunc); - - var setParamList = HasSetter (tail, isLet) ? - new XElement (kParameterList, new XAttribute (kIndex, "1")) : null; - - if (setParamList != null) { - var parmName = tail.getter_setter_keyword_block ()?.setter_keyword_clause ().new_value_name ()?.GetText () - ?? kNewValue; - var setterType = EscapePossibleClosureType (resultType); - var newValueParam = new XElement (kParameter, new XAttribute (kIndex, "0"), - new XAttribute (kType, setterType), new XAttribute (kPublicName, parmName), - new XAttribute (kPrivateName, parmName), new XAttribute (kIsVariadic, false)); - setParamList.Add (newValueParam); - var setFunc = ToFunctionDeclaration ("set_" + name, - "()", accessibility, isStatic, hasThrows, isFinal, isOptional, - isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, - isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - currentElement.Push (setFunc); - var setParamLists = new XElement (kParameterLists, MakeInstanceParameterList (), setParamList); - currentElement.Pop (); - - setFunc.Add (setParamLists); - AddElementToParentMembers (setFunc); - AddObjCSelector (setFunc); - } - - var prop = new XElement (kProperty, new XAttribute (kName, name), - new XAttribute (nameof (accessibility), accessibility), - new XAttribute (kType, resultType), - new XAttribute (kStorage, kComputed), - new XAttribute (nameof (isStatic), XmlBool (isStatic)), - new XAttribute (nameof (isLet), XmlBool (isLet)), - new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated)), - new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable)), - new XAttribute (nameof (isOptional), XmlBool (isOptional))); - AddElementToParentMembers (prop); - } - - PushIgnore (); - } - - bool HasSetter (Variable_declaration_tailContext context, bool isLet) - { - // conditions for having a setter: - // defaultInitializer and getter_setter_keyword are both null (public var foo: Type) - // defaultInitializer is not null (public var foo: Type = initialValue) - // getter_setter_keyword_block is non-null and the getter_setter_keyword_block - // has a non-null setter_keyword_clause (public var foo:Type { get; set; }, public foo: Type { set } - - var defaultInitializer = context.defaultInitializer (); - var gettersetter = context.getter_setter_keyword_block (); - - return !isLet && ((defaultInitializer == null && gettersetter == null) || - defaultInitializer != null || - gettersetter?.setter_keyword_clause () != null); - } - - public override void EnterExtension_declaration ([NotNull] Extension_declarationContext context) - { - var onType = UnTick (TypeText (context.type_identifier ())); - var inherits = GatherInheritance (context.type_inheritance_clause (), forceProtocolInheritance: true); - // why, you say, why put a kKind tag into an extension? - // The reason is simple: this is a hack. Most of the contents - // of an extension are the same as a class and as a result we can - // pretend that it's a class and everything will work to fill it out - // using the class/struct/enum code for members. - var extensionElem = new XElement (kExtension, - new XAttribute (nameof (onType), onType), - new XAttribute (kKind, kClass)); - if (inherits?.Count > 0) - extensionElem.Add (new XElement (nameof (inherits), inherits.ToArray ())); - currentElement.Push (extensionElem); - extensions.Add (extensionElem); - } - - public override void ExitExtension_declaration ([NotNull] Extension_declarationContext context) - { - var extensionElem = currentElement.Pop (); - var onType = extensionElem.Attribute (kOnType); - var givenOnType = onType.Value; - var actualOnType = UnTick (TypeText (context.type_identifier ())); - if (givenOnType != actualOnType) - throw new Exception ($"extension type mismatch on exit declaration: expected {actualOnType} but got {givenOnType}"); - // remove the kKind attribute - you've done your job. - extensionElem.Attribute (kKind)?.Remove (); - - currentElement.Peek ().Add (extensionElem); - } - - public override void ExitImport_statement ([NotNull] Import_statementContext context) - { - // this is something like: import class Foo.Bar - // and we're not handling that yet - if (context.import_kind () != null) - return; - importModules.Add (context.import_path ().GetText ()); - } - - public override void EnterOperator_declaration ([NotNull] Operator_declarationContext context) - { - var operatorElement = InfixOperator (context.infix_operator_declaration ()) - ?? PostfixOperator (context.postfix_operator_declaration ()) - ?? PrefixOperator (context.prefix_operator_declaration ()); - operators.Add (operatorElement); - - currentElement.Peek ().Add (operatorElement); - } - - public override void EnterOptional_type ([NotNull] Optional_typeContext context) - { - } - - XElement InfixOperator (Infix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator (kInfix, context.@operator (), - context.infix_operator_group ()?.precedence_group_name ()?.GetText () ?? ""); - } - - XElement PostfixOperator (Postfix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator (kPostfix, context.@operator (), ""); - } - - XElement PrefixOperator (Prefix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator (kPrefix, context.@operator (), ""); - } - - XElement GeneralOperator (string operatorKind, OperatorContext context, string precedenceGroup) - { - return new XElement (kOperator, - new XAttribute (kName, context.Operator ().GetText ()), - new XAttribute (nameof (operatorKind), operatorKind), - new XAttribute (nameof (precedenceGroup), precedenceGroup)); - } - - XElement HandleGenerics (Generic_parameter_clauseContext genericContext, Generic_where_clauseContext whereContext, bool addParentGenerics) - { - if (genericContext == null) - return null; - var genericElem = new XElement (kGenericParameters); - if (addParentGenerics) - AddParentGenerics (genericElem); - foreach (var generic in genericContext.generic_parameter_list ().generic_parameter ()) { - var name = UnTick (TypeText (generic.type_name ())); - var genParam = new XElement (kParam, new XAttribute (kName, name)); - genericElem.Add (genParam); - var whereType = TypeText (generic.type_identifier ()) ?? - TypeText (generic.protocol_composition_type ()); - if (whereType != null) { - genericElem.Add (MakeConformanceWhere (name, whereType)); - } - } - - if (whereContext == null) - return genericElem; - - foreach (var requirement in whereContext.requirement_list ().requirement ()) { - if (requirement.conformance_requirement () != null) { - var name = UnTick (TypeText (requirement.conformance_requirement ().type_identifier () [0])); - - // if there is no protocol composition type, then it's the second type identifier - var from = TypeText (requirement.conformance_requirement ().protocol_composition_type ()) - ?? TypeText (requirement.conformance_requirement ().type_identifier () [1]); - genericElem.Add (MakeConformanceWhere (name, from)); - } else { - var name = UnTick (TypeText (requirement.same_type_requirement ().type_identifier ())); - var type = TypeText (requirement.same_type_requirement ().type ()); - genericElem.Add (MakeEqualityWhere (name, type)); - } - } - - return genericElem; - } - - public override void ExitTypealias_declaration ([NotNull] Typealias_declarationContext context) - { - var name = UnTick (context.typealias_name ().GetText ()); - var generics = TypeText (context.generic_parameter_clause ()) ?? ""; - var targetType = TypeText (context.typealias_assignment ().type ()); - var access = ToAccess (context.access_level_modifier ()); - var map = new XElement (kTypeAlias, new XAttribute (kName, name + generics), - new XAttribute (kAccessibility, access), - new XAttribute (kType, targetType)); - if (access != null) { - if (currentElement.Peek ().Name == kModule) { - typeAliasMap.Add (map); - } else { - var curr = currentElement.Peek (); - var aliaslist = curr.Element (kTypeAliases); - if (aliaslist == null) { - aliaslist = new XElement (kTypeAliases); - curr.Add (aliaslist); - } - aliaslist.Add (map); - } - } - } - - XElement MakeConformanceWhere (string name, string from) - { - return new XElement (kWhere, new XAttribute (nameof (name), name), - new XAttribute (kRelationship, kInherits), - new XAttribute (nameof (from), from)); - } - - XElement MakeEqualityWhere (string firsttype, string secondtype) - { - return new XElement (kWhere, new XAttribute (nameof (firsttype), firsttype), - new XAttribute (kRelationship, kEquals), - new XAttribute (nameof (secondtype), secondtype)); - } - - public override void ExitVariable_declaration ([NotNull] Variable_declarationContext context) - { - PopIgnore (); - } - - void PushIgnore () - { - currentElement.Push (new XElement (kIgnore)); - } - - void PopIgnore () - { - var elem = currentElement.Pop (); - if (elem.Name != kIgnore) - throw new ParseException ($"Expected an {kIgnore} element, but got {elem}"); - } - - bool ShouldIgnore () - { - return currentElement.Peek ().Name == kIgnore; - } - - public override void EnterParameter_clause ([NotNull] Parameter_clauseContext context) - { - if (ShouldIgnore ()) - return; - - var parameterLists = new XElement (kParameterLists); - XElement instanceList = MakeInstanceParameterList (); - var formalIndex = 0; - if (instanceList != null) { - parameterLists.Add (instanceList); - formalIndex = 1; - } - - var formalArguments = MakeParameterList (context.parameter_list (), formalIndex, false); - - parameterLists.Add (formalArguments); - currentElement.Peek ().Add (parameterLists); - } - - XElement MakeParameterList (Parameter_listContext parmList, int index, bool isSubscript, int startIndex = 0) - { - var formalArguments = new XElement (kParameterList, new XAttribute (kIndex, index.ToString ())); - - if (parmList != null) { - var i = startIndex; - foreach (var parameter in parmList.parameter ()) { - var parameterElement = ToParameterElement (parameter, i, isSubscript); - formalArguments.Add (parameterElement); - i++; - } - } - return formalArguments; - } - - XElement MakeInstanceParameterList () - { - var topElem = currentElement.Peek (); - if (topElem.Name == kModule) - return null; - if (topElem.Name != kFunc) - throw new ParseException ($"Expecting a func node but got {topElem.Name}"); - if (NominalParentAfter (0) == null) - return null; - var funcName = topElem.Attribute (kName).Value; - var isStatic = topElem.Attribute (kIsStatic).Value == "true"; - var isCtorDtor = IsCtorDtor (funcName); - var isClass = NominalParentAfter (0).Attribute (kKind).Value == kClass; - var instanceName = GetInstanceName (); - var type = $"{(isClass ? "" : "inout ")}{instanceName}{(isCtorDtor ? ".Type" : "")}"; - var parameter = new XElement (kParameter, new XAttribute (kType, type), - new XAttribute (kIndex, "0"), new XAttribute (kPublicName, "self"), - new XAttribute (kPrivateName, "self"), new XAttribute (kIsVariadic, "false")); - return new XElement (kParameterList, new XAttribute (kIndex, "0"), parameter); - } - - void AddParentGenerics (XElement genericResult) - { - var parentGenerics = new List (); - for (int i =0; i < currentElement.Count; i++) { - var elem = currentElement.ElementAt (i); - if (!IsNominal (elem)) - continue; - var elemGenerics = elem.Element (kGenericParameters); - if (elemGenerics == null) - continue; - foreach (var param in elemGenerics.Descendants (kParam)) { - parentGenerics.Add (new XElement (param)); - } - } - genericResult.Add (parentGenerics.ToArray ()); - } - - XElement NominalParentAfter (int start) - { - for (var i = start + 1; i < currentElement.Count; i++) { - var elem = currentElement.ElementAt (i); - if (IsNominal (elem)) - return elem; - } - return null; - } - - bool IsNominal (XElement elem) - { - var kind = elem.Attribute (kKind)?.Value; - return kind != null && (kind == kClass || kind == kStruct || kind == kEnum || kind == kProtocol); - } - - string GetInstanceName () - { - var nameBuffer = new StringBuilder (); - for (int i = 0; i < currentElement.Count; i++) { - var elem = currentElement.ElementAt (i); - if (IsNominal (elem)) { - if (elem.Name == kExtension) - return elem.Attribute (kOnType).Value; - if (nameBuffer.Length > 0) - nameBuffer.Insert (0, '.'); - nameBuffer.Insert (0, elem.Attribute (kName).Value); - var generics = elem.Element (kGenericParameters); - if (generics != null) { - AddGenericsToName (nameBuffer, generics); - } - } - } - nameBuffer.Insert (0, '.'); - var module = currentElement.Last (); - nameBuffer.Insert (0, moduleName); - return nameBuffer.ToString (); - } - - void AddGenericsToName (StringBuilder nameBuffer, XElement generics) - { - var isFirst = true; - foreach (var name in GenericNames (generics)) { - if (isFirst) { - nameBuffer.Append ("<"); - isFirst = false; - } else { - nameBuffer.Append (", "); - } - nameBuffer.Append (name); - } - if (!isFirst) - nameBuffer.Append (">"); - } - - IEnumerable GenericNames (XElement generics) - { - return generics.Elements ().Where (elem => elem.Name == kParam).Select (elem => elem.Attribute (kName).Value); - } - - XElement ToParameterElement (ParameterContext context, int index, bool isSubscript) - { - var typeAnnotation = context.type_annotation (); - var isInOut = typeAnnotation.inout_clause () != null; - var type = TypeText (typeAnnotation.type ()); - var privateName = NoUnderscore (UnTick (context.local_parameter_name ()?.GetText ()) ?? ""); - var replacementPublicName = isSubscript ? "" : privateName; - var publicName = NoUnderscore (UnTick (context.external_parameter_name ()?.GetText ()) ?? replacementPublicName); - var isVariadic = context.range_operator () != null; - if (isVariadic) - type = $"Swift.Array<{type}>"; - var isEscaping = AttributesContains (typeAnnotation.attributes (), kEscaping); - var isAutoClosure = AttributesContains (typeAnnotation.attributes (), kAutoClosure); - var typeBuilder = new StringBuilder (); - if (isEscaping) - typeBuilder.Append ("@escaping[] "); - if (isAutoClosure) - typeBuilder.Append ("@autoclosure[] "); - if (isInOut) - typeBuilder.Append ("inout "); - typeBuilder.Append (type); - type = typeBuilder.ToString (); - - var paramElement = new XElement (kParameter, new XAttribute (nameof (index), index.ToString ()), - new XAttribute (nameof (type), type), new XAttribute (nameof (publicName), publicName), - new XAttribute (nameof (privateName), privateName), new XAttribute (nameof (isVariadic), XmlBool (isVariadic))); - return paramElement; - } - - static string NoUnderscore (string s) - { - return s == "_" ? "" : s; - } - - XElement GatherAttributes (AttributesContext context) - { - if (context == null) - return null; - var attributes = new XElement (kAttributes); - foreach (var attr in context.attribute ()) { - var attrElement = GatherAttribute (attr); - if (attrElement != null) - attributes.Add (attrElement); - } - return attributes.HasElements ? attributes : null; - } - - XElement GatherAttribute (AttributeContext context) - { - var attribute = new XElement (kAttribute, new XAttribute (kName, context.attribute_name ().GetText ())); - if (context.attribute_argument_clause () != null) { - var parameters = GatherParameters (context.attribute_argument_clause ()?.balanced_tokens ()); - if (parameters != null) - attribute.Add (parameters); - } - return attribute; - } - - XElement GatherParameters (Balanced_tokensContext context) - { - if (context == null) - return null; - var parameterlist = new XElement (kAttributeParameterList); - - foreach (var balancedToken in context.balanced_token ()) { - var parameter = ToAttributeParameter (balancedToken); - if (parameter != null) - parameterlist.Add (parameter); - } - return parameterlist.HasElements ? parameterlist : null; - } - - XElement ToAttributeParameter (Balanced_tokenContext context) - { - if (context.balanced_tokens () != null) { - var sublist = new XElement (kAttributeParameter, new XAttribute (kKind, kSublist)); - var subparams = GatherParameters (context.balanced_tokens ()); - if (subparams != null) - sublist.Add (subparams); - return sublist; - } - - if (context.label_identifier () != null) { - var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), - new XAttribute (kValue, context.label_identifier ().GetText ())); - return label; - } - - if (context.literal () != null) { - var literal = new XElement (kAttributeParameter, new XAttribute (kKind, kLiteral), - new XAttribute (kValue, context.literal ().GetText ())); - return literal; - } - - // make the operator look like a label - if (context.@operator () != null) { - var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), - new XAttribute (kValue, context.@operator ().GetText ())); - return label; - } - - if (context.any_punctuation_for_balanced_token () != null) { - var label = new XElement (kAttributeParameter, new XAttribute (kKind, kLabel), - new XAttribute (kValue, context.any_punctuation_for_balanced_token ().GetText ())); - return label; - } - - return null; - } - - List GatherInheritance (Type_inheritance_clauseContext context, bool forceProtocolInheritance, - bool removeNonProtocols = false) - { - var inheritance = new List (); - if (context == null) - return inheritance; - var list = context.type_inheritance_list (); - bool first = true; - while (list != null) { - var inheritanceKind = forceProtocolInheritance ? kProtocol : - (inheritance.Count > 0 ? kProtocol : kLittleUnknown); - var type = TypeText (list.type_identifier ()); - if (!(first && removeNonProtocols && TypeIsNotProtocol (type))) { - var elem = new XElement (kInherit, new XAttribute (kType, type), - new XAttribute (nameof (inheritanceKind), inheritanceKind)); - inheritance.Add (elem); - if (inheritanceKind == kLittleUnknown) - unknownInheritance.Add (elem); - } - first = false; - list = list.type_inheritance_list (); - } - - return inheritance; - } - - bool TypeIsNotProtocol (string type) - { - // special case this - the type database as this as "other" - // which is technically not a protocol, but it is a protocol. - if (type == "Swift.Error") - return false; - var parts = type.Split ('.'); - if (parts.Length == 1) - return true; // generic - var module = parts [0]; - if (!typeDatabase.ModuleNames.Contains (module)) { - moduleLoader.Load (module, typeDatabase); - } - var entity = typeDatabase.TryGetEntityForSwiftName (type); - if (entity != null && entity.EntityType != EntityType.Protocol) - return true; - return false; - } - - XElement ToTypeDeclaration (string kind, string name, string accessibility, bool isObjC, - bool isFinal, bool isDeprecated, bool isUnavailable, List inherits, XElement generics, - XElement attributes) - { - var xobjects = new List (); - if (generics != null) - xobjects.Add (generics); - xobjects.Add (new XAttribute (nameof (kind), kind)); - xobjects.Add (new XAttribute (nameof (name), name)); - xobjects.Add (new XAttribute (nameof (accessibility), accessibility)); - xobjects.Add (new XAttribute (nameof (isObjC), XmlBool (isObjC))); - xobjects.Add (new XAttribute (nameof (isFinal), XmlBool (isFinal))); - xobjects.Add (new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated))); - xobjects.Add (new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable))); - - xobjects.Add (new XElement (kMembers)); - if (inherits != null && inherits.Count > 0) - xobjects.Add (new XElement (nameof (inherits), inherits.ToArray ())); - if (attributes != null) - xobjects.Add (attributes); - return new XElement (kTypeDeclaration, xobjects.ToArray ()); - } - - - XElement ToFunctionDeclaration (string name, string returnType, string accessibility, - bool isStatic, bool hasThrows, bool isFinal, bool isOptional, bool isConvenienceInit, - string objCSelector, string operatorKind, bool isDeprecated, bool isUnavailable, - bool isMutating, bool isRequired, bool isProperty, bool isAsync, XElement attributes) - { - var decl = new XElement (kFunc, new XAttribute (nameof (name), name), new XAttribute (nameof (returnType), returnType), - new XAttribute (nameof (accessibility), accessibility), new XAttribute (nameof (isStatic), XmlBool (isStatic)), - new XAttribute (nameof (hasThrows), XmlBool (hasThrows)), new XAttribute (nameof (isFinal), XmlBool (isFinal)), - new XAttribute (nameof (isOptional), XmlBool (isOptional)), - new XAttribute (nameof (isConvenienceInit), XmlBool (isConvenienceInit)), - new XAttribute (nameof (isDeprecated), XmlBool (isDeprecated)), - new XAttribute (nameof (isUnavailable), XmlBool (isUnavailable)), - new XAttribute (nameof (isRequired), XmlBool (isRequired)), - new XAttribute (kIsAsync, XmlBool (isAsync)), - new XAttribute (kIsProperty, XmlBool (isProperty)), - new XAttribute (nameof (isMutating), XmlBool (isMutating))); - - if (operatorKind != null) { - decl.Add (new XAttribute (nameof (operatorKind), operatorKind)); - } - if (objCSelector != null) { - decl.Add (new XAttribute (nameof (objCSelector), objCSelector)); - } - if (attributes != null) { - decl.Add (attributes); - } - return decl; - } - - bool CheckForDeprecated (XElement attributes) - { - var availableTags = AvailableAttributes (attributes); - foreach (var attribute in availableTags) { - var args = AttrbuteParameters (attribute); - var platform = args [0]; - if (!PlatformMatches (platform)) - continue; - - var deprecatedIndex = args.IndexOf (kDeprecated); - if (deprecatedIndex < 0) - continue; - var deprecatedVersion = GetVersionAfter (args, deprecatedIndex); - if (TargetVersionIsLessOrEqual (deprecatedVersion)) - return true; - } - return false; - } - - bool CheckForUnavailable (XElement attributes) - { - var availableTags = AvailableAttributes (attributes); - foreach (var attribute in availableTags) { - var args = AttrbuteParameters (attribute); - // if unavailable exists, need to match platform - if (args.IndexOf (kUnavailable) >= 0 && PlatformMatches (args [0])) - return true; - - } - return !CheckForAvailable (attributes); - } - - bool CheckForAvailable (XElement attributes) - { - var availableTags = AvailableAttributes (attributes); - foreach (var attribute in availableTags) { - var args = AttrbuteParameters (attribute); - if (IsShortHand (args)) { - return AvailableShorthand (args); - } else { - return AvailableLonghand (args); - } - } - return true; - } - - bool AvailableLonghand (List args) - { - // args will be plat , specifiers - // specificers will be: - // introduced: version - // deprecated: version - // obsoleted: version - // unavailable - var platform = args [0]; - if (!PlatformMatches (platform)) - return true; - - // if unavailable is present, it's not there. - if (args.IndexOf (kUnavailable) >= 0) - return false; - - var introIndex = args.IndexOf (kIntroduced); - if (introIndex >= 0) { - var introVersion = GetVersionAfter (args, introIndex); - if (TargetVersionIsGreaterOrEqual (introVersion)) - return false; - } - - var obsoletedIndex = args.IndexOf (kObsoleted); - if (obsoletedIndex >= 0) { - var obsoletedVersion = GetVersionAfter (args, obsoletedIndex); - if (TargetVersionIsLessOrEqual (obsoletedVersion)) - return false; - } - return true; - } - - bool AvailableShorthand (List args) - { - // args will be: plat ver . x . y , plat ver , ... * - - var startIndex = 0; - while (startIndex < args.Count) { - if (args [startIndex] == "*") - return false; - var platform = args [startIndex]; - if (PlatformMatches (platform)) { - var endIndex = args.IndexOf (",", startIndex + 1); - var versionNumber = args.GetRange (startIndex + 1, endIndex - startIndex); - if (TargetVersionIsGreaterOrEqual (versionNumber)) - return true; - } else { - startIndex = args.IndexOf (",", startIndex + 1); - } - } - return false; - } - - bool IsShortHand (List args) - { - if (args [1] == ",") - return false; - return args.Last () == "*"; - } - - Version GetVersionAfter (List pieces, int indexAfter) - { - var colonIndex = ColonAfter (pieces, indexAfter); - if (colonIndex < 0) - return new Version (0, 0); - var start = colonIndex + 1; - var end = start + 1; - while (end < pieces.Count && pieces [end] != ",") - end++; - var versionPieces = pieces.GetRange (start, end - start); - return VersionPiecesToVersion (versionPieces); - } - - int ColonAfter (List pieces, int start) - { - for (int i = start + 1; i < pieces.Count; i++) { - if (pieces [i] == ":") - return i; - if (pieces [i] == ",") - return -1; - } - return -1; - } - - bool TargetVersionIsGreaterOrEqual (List versionPieces) - { - var expectedVersion = VersionPiecesToVersion (versionPieces); - return TargetVersionIsGreaterOrEqual (expectedVersion); - } - - bool TargetVersionIsGreaterOrEqual (Version expectedVersion) - { - var compiledVersionStr = PlatformVersionFromModuleFlags (); - if (String.IsNullOrEmpty (compiledVersionStr)) - return true; // no version, I guess it's good? - var compiledVersion = new Version (compiledVersionStr); - return expectedVersion >= compiledVersion; - } - - bool TargetVersionIsLessOrEqual (List versionPieces) - { - var expectedVersion = VersionPiecesToVersion (versionPieces); - return TargetVersionIsLessOrEqual (expectedVersion); - } - - bool TargetVersionIsLessOrEqual (Version expectedVersion) - { - var compiledVersionStr = PlatformVersionFromModuleFlags (); - if (String.IsNullOrEmpty (compiledVersionStr)) - return true; // no version, I guess it's good? - var compiledVersion = new Version (compiledVersionStr); - return expectedVersion <= compiledVersion; - } - - Version VersionPiecesToVersion (List pieces) - { - var sb = new StringBuilder (); - for (int i = 0; i < pieces.Count; i++) { - if (pieces [i] == "." && i + 1 < pieces.Count && pieces [i + 1] == "*") - break; - sb.Append (pieces [i]); - } - return new Version (sb.ToString ()); - } - - IEnumerable AvailableAttributes (XElement attributes) - { - if (attributes == null) - return Enumerable.Empty (); - return attributes.Descendants (kAttribute).Where (el => el.Attribute (kName).Value == kAvailable); - - } - - List AttrbuteParameters (XElement attribute) - { - return attribute.Descendants (kAttributeParameter).Select (at => - at.Attribute (kValue)?.Value ?? "").ToList (); - } - - bool PlatformMatches (string platform) - { - var currentPlatform = PlatformFromModuleFlags (); - switch (platform) { - case "*": - case "swift": - return true; - case "iOS": - case "iOSApplicationExtension": - return currentPlatform.StartsWith ("ios", StringComparison.Ordinal) && - !currentPlatform.StartsWith ("ios-macabi", StringComparison.Ordinal); - case "macOS": - case "macOSApplicationExtension": - return currentPlatform.StartsWith ("macos", StringComparison.Ordinal); - case "macCatalyst": - case "macCatalystExtension": - return currentPlatform.StartsWith ("ios-macabi", StringComparison.Ordinal); - case "watchOS": - case "watchOSApplicationExtension": - return currentPlatform.StartsWith ("watch", StringComparison.Ordinal); - case "tvOS": - case "tvOSApplicationExtension": - return currentPlatform.StartsWith ("tv", StringComparison.Ordinal); - default: - return false; - } - } - - string PlatformFromModuleFlags () - { - var flagsValue = TargetFromModuleFlags (); - var os = flagsValue.ClangTargetOS (); - var digitIndex = FirstDigitIndex (os); - if (digitIndex < 0) - return os; - return os.Substring (0, digitIndex); - } - - static int FirstDigitIndex (string s) - { - var index = 0; - foreach (char c in s) { - if (Char.IsDigit (c)) - return index; - index++; - } - return -1; - } - - string PlatformVersionFromModuleFlags () - { - var flagsValue = TargetFromModuleFlags (); - var os = flagsValue.ClangTargetOS (); - var digitIndex = FirstDigitIndex (os); - if (digitIndex < 0) - return ""; - return os.Substring (digitIndex); - } - - string TargetFromModuleFlags () - { - string flagsValue = null; - if (!moduleFlags.TryGetValue ("target", out flagsValue)) { - return ""; - } - return flagsValue; - } - - static HashSet ModulesThatWeCanSkip = new HashSet () { - "XamGlue", - "RegisterAccess", - "_StringProcessing", - "_Concurrency", - }; - - void LoadReferencedModules () - { - var failures = new StringBuilder (); - foreach (var module in importModules) { - // XamGlue and RegisterAccess may very well get - // used, but the functions/types exported from these - // should never need to be loaded. - if (ModulesThatWeCanSkip.Contains (module)) - continue; - // if (!moduleLoader.Load (module, typeDatabase)) { - // if (failures.Length > 0) - // failures.Append (", "); - // failures.Append (module); - // } - } - if (failures.Length > 0) - throw new ParseException ($"Unable to load the following module(s): {failures.ToString ()}"); - } - - void PatchPossibleOperators () - { - foreach (var func in functions) { - var operatorKind = GetOperatorType (func.Item1); - if (operatorKind != OperatorType.None) { - func.Item2.Attribute (nameof (operatorKind))?.Remove (); - func.Item2.SetAttributeValue (nameof (operatorKind), operatorKind.ToString ()); - } - } - } - - void PatchPossibleBadInheritance () - { - foreach (var inh in unknownInheritance) { - var type = inh.Attribute (kType).Value; - if (IsLocalClass (type) || IsGlobalClass (type) || IsNSObject (type)) - inh.Attribute (kInheritanceKind).Value = kClass; - else - inh.Attribute (kInheritanceKind).Value = kProtocol; - } - } - - void PatchAssociatedTypeConformance () - { - foreach (var assoc in associatedTypesWithConformance) { - var conformances = assoc.Element (kConformingProtocols); - var first = conformances.Element (kConformingProtocol); - var className = (string)first.Attribute (kName); - if (IsLocalClass (className) || IsGlobalClass (className)) { - first.Remove (); - if (conformances.Nodes ().Count () == 0) - conformances.Remove (); - assoc.Add (new XElement (kSuperclass, new XAttribute (kName, className))); - } - } - } - - bool IsNSObject (string typeName) - { - return typeName == "ObjectiveC.NSObject"; - } - - bool IsLocalClass (string typeName) - { - return classes.Contains (typeName); - } - - bool IsGlobalClass (string typeName) - { - return typeDatabase.EntityForSwiftName (typeName)?.EntityType == EntityType.Class; - } - - void PatchExtensionSelfArgs () - { - foreach (var ext in extensions) { - var onType = (string)ext.Attribute (kOnType).Value; - var parts = onType.Split ('.'); - if (parts [0] == "XamGlue") - continue; - if (parts.Length > 1 && !typeDatabase.ModuleNames.Contains (parts [0])) { - moduleLoader.Load (parts [0], typeDatabase); - } - var entity = typeDatabase.EntityForSwiftName (onType); - if (entity != null) { - PatchExtensionSelfArgs (ext, entity); - } - } - } - - void PatchExtensionSelfArgs (XElement ext, Entity entity) - { - var isStructOrScalar = entity.IsStructOrEnum || entity.EntityType == EntityType.Scalar; - foreach (var func in ext.Descendants (kFunc)) { - var selfArg = SelfParameter (func); - if (selfArg == null) - continue; - var attr = selfArg.Attribute (kType); - var type = (string)attr.Value; - if (entity.Type.ContainsGenericParameters) { - type = entity.Type.ToFullyQualifiedNameWithGenerics (); - attr.Value = type; - var generics = entity.Type.Generics.ToXElement (); - if (func.Element (kGenericParameters) != null) { - var funcGenerics = func.Element (kGenericParameters); - funcGenerics.Remove (); - foreach (var generic in funcGenerics.Elements ()) - generics.Add (generic); - } - func.Add (generics); - } - if (isStructOrScalar && !type.StartsWith ("inout", StringComparison.Ordinal)) { - attr.Value = "inout " + type; - } - } - } - - XElement SelfParameter (XElement func) - { - var selfList = WhereIndexZero (func.Descendants (kParameterList)); - if (selfList == null) - return null; - var selfArg = WhereIndexZero (selfList.Descendants (kParameter)); - return selfArg; - } - - static XElement WhereIndexZero (IEnumerable elems) - { - return elems.FirstOrDefault (el => (string)el.Attribute (kIndex).Value == "0"); - } - - void PatchExtensionShortNames () - { - foreach (var ext in extensions) { - var onType = TypeSpecParser.Parse (ext.Attribute (kOnType).Value); - var replacementType = FullyQualify (onType); - ext.Attribute (kOnType).Value = replacementType.ToString (); - foreach (var func in ext.Descendants (kFunc)) { - var selfArg = SelfParameter (func); - if (selfArg == null) - continue; - onType = TypeSpecParser.Parse (selfArg.Attribute (kType).Value); - replacementType = FullyQualify (onType); - selfArg.Attribute (kType).Value = replacementType.ToString (); - } - } - } - - TypeSpec FullyQualify (TypeSpec spec) - { - switch (spec.Kind) { - case TypeSpecKind.Named: - return FullyQualify (spec as NamedTypeSpec); - case TypeSpecKind.Closure: - return FullyQualify (spec as ClosureTypeSpec); - case TypeSpecKind.ProtocolList: - return FullyQualify (spec as ProtocolListTypeSpec); - case TypeSpecKind.Tuple: - return FullyQualify (spec as TupleTypeSpec); - default: - throw new NotImplementedException ($"unknown TypeSpec kind {spec.Kind}"); - } - } - - TypeSpec FullyQualify (NamedTypeSpec named) - { - var dirty = false; - var newName = named.Name; - - if (!named.Name.Contains (".")) { - newName = ReplaceName (named.Name); - dirty = true; - } - - var genParts = new TypeSpec [named.GenericParameters.Count]; - var index = 0; - foreach (var gen in named.GenericParameters) { - var newGen = FullyQualify (gen); - genParts[index++] = newGen; - if (newGen != gen) - dirty = true; - } - - if (dirty) { - var newNamed = new NamedTypeSpec (newName, genParts); - newNamed.Attributes.AddRange (named.Attributes); - return newNamed; - } - - return named; - } - - TypeSpec FullyQualify (TupleTypeSpec tuple) - { - var dirty = false; - var parts = new TypeSpec [tuple.Elements.Count]; - var index = 0; - foreach (var spec in tuple.Elements) { - var newSpec = FullyQualify (spec); - if (newSpec != spec) - dirty = true; - parts [index++] = newSpec; - } - - if (dirty) { - var newTup = new TupleTypeSpec (parts); - newTup.Attributes.AddRange (tuple.Attributes); - return newTup; - } - - return tuple; - } - - TypeSpec FullyQualify (ProtocolListTypeSpec protolist) - { - var dirty = false; - var parts = new List (); - foreach (var named in protolist.Protocols.Keys) { - var newNamed = FullyQualify (named); - parts.Add (newNamed as NamedTypeSpec); - if (newNamed != named) - dirty = true; - } - - if (dirty) { - var newProto = new ProtocolListTypeSpec (parts); - newProto.Attributes.AddRange (protolist.Attributes); - return newProto; - } - - return protolist; - } - - TypeSpec FullyQualify (ClosureTypeSpec clos) - { - var dirty = false; - var args = FullyQualify (clos.Arguments); - if (args != clos.Arguments) - dirty = true; - var returnType = FullyQualify (clos.ReturnType); - if (returnType != clos.ReturnType) - dirty = true; - - if (dirty) { - var newClosure = new ClosureTypeSpec (args, returnType); - newClosure.Attributes.AddRange (clos.Attributes); - return newClosure; - } - - return clos; - } - - string ReplaceName (string nonQualified) - { - Exceptions.ThrowOnNull (nonQualified, nameof (nonQualified)); - - var localName = ReplaceLocalName (nonQualified); - if (localName != null) - return localName; - var globalName = ReplaceGlobalName (nonQualified); - if (globalName == null) - throw new ParseException ($"Unable to find fully qualified name for non qualified type {nonQualified}"); - return globalName; - } - - string ReplaceLocalName (string nonQualified) - { - foreach (var candidate in nominalTypes) { - var candidateWithoutModule = StripModule (candidate); - if (nonQualified == candidateWithoutModule) - return candidate; - } - return null; - } - - string ReplaceGlobalName (string nonQualified) - { - foreach (var module in importModules) { - var candidateName = $"{module}.{nonQualified}"; - var entity = typeDatabase.TryGetEntityForSwiftName (candidateName); - if (entity != null) - return candidateName; - } - if (nonQualified == "EveryProtocol") - return "XamGlue.EveryProtocol"; - return null; - } - - string StripModule (string fullyQualifiedName) - { - if (fullyQualifiedName.StartsWith (moduleName, StringComparison.Ordinal)) - // don't forget the '.' - return fullyQualifiedName.Substring (moduleName.Length + 1); - return fullyQualifiedName; - } - - static bool AttributesContains (AttributesContext context, string key) - { - if (context == null) - return false; - foreach (var attr in context.attribute ()) { - if (attr.attribute_name ().GetText () == key) - return true; - } - return false; - } - - static bool AttributesContainsAny (AttributesContext context, string [] keys) - { - foreach (var attr in context.attribute ()) { - var attrName = attr.attribute_name ().GetText (); - foreach (var key in keys) { - if (key == attrName) - return true; - } - } - return false; - } - - string EscapePossibleClosureType (string type) - { - var typeSpec = TypeSpecParser.Parse (type); - return typeSpec is ClosureTypeSpec ? "@escaping[] " + type : type; - } - - static Dictionary accessMap = new Dictionary () { - { kPublic, kPublicCap }, - { kPrivate, kPrivateCap }, - { kOpen, kOpenCap }, - { kInternal, kInternalCap }, - }; - - string AccessibilityFromModifiers (Declaration_modifiersContext context) - { - // If there is no context, we need to search for the appropriate context - // Swift has a number of "interesting" rules for implicitly defined accessibility - // If the parent element is a protocol, it's public - // If the parent is public, internal, or open then it's open - // If the parent is private or fileprivate, then it's private - - // Note that I don't make any distinction between private and fileprivate - // From our point of view, they're the same: they're things that we don't - // have access to and don't care about in writing a reflector of the public - // API. - if (context == null) { - var parentElem = NominalParentAfter (-1); - if (parentElem == null) - return kInternalCap; - if (parentElem.Attribute (kKind).Value == kProtocol) - return kPublicCap; - switch (parentElem.Attribute (kAccessibility).Value) { - case kPublic: - case kInternal: - case kOpen: - return kInternalCap; - case kPrivate: - case kFilePrivate: - return kPrivateCap; - } - } - foreach (var modifer in context.declaration_modifier ()) { - string result; - if (accessMap.TryGetValue (modifer.GetText (), out result)) - return result; - } - return kInternalCap; - } - - static bool HasAsync (Getter_keyword_clauseContext context) - { - return context == null ? false : context.async_clause () != null; - } - - static bool ModifiersContains (Declaration_modifiersContext context, string match) - { - if (context == null) - return false; - foreach (var modifier in context.declaration_modifier ()) { - var text = modifier.GetText (); - if (text == match) - return true; - } - return false; - } - - public override void EnterDeclaration_modifier ([NotNull] Declaration_modifierContext context) - { - var modifier = context.GetText (); - - } - - static bool ModifiersContainsAny (Declaration_modifiersContext context, string [] matches) - { - if (context == null) - return false; - foreach (var modifier in context.declaration_modifier ()) { - var text = modifier.GetText (); - foreach (var match in matches) - if (text == match) - return true; - } - return false; - } - - static bool IsStaticOrClass (Declaration_modifiersContext context) - { - return ModifiersContainsAny (context, new string [] { kStatic, kClass }); - } - - static bool IsFinal (Declaration_modifiersContext context) - { - return ModifiersContains (context, kFinal); - } - - void AddStructToCurrentElement (XElement elem) - { - var parentElement = GetOrCreateParentElement (kInnerStructs); - parentElement.Add (elem); - RegisterNominal (elem); - } - - void AddEnumToCurrentElement (XElement elem) - { - var parentElement = GetOrCreateParentElement (kInnerEnums); - parentElement.Add (elem); - RegisterNominal (elem); - } - - void AddClassToCurrentElement (XElement elem) - { - var parentElement = GetOrCreateParentElement (kInnerClasses); - parentElement.Add (elem); - RegisterNominal (elem); - } - - void RegisterNominal (XElement elem) - { - var isClass = elem.Attribute (kKind).Value == kClass; - var builder = new StringBuilder (); - while (elem != null) { - if (builder.Length > 0) - builder.Insert (0, '.'); - var namePart = elem.Attribute (kName)?.Value ?? moduleName; - builder.Insert (0, namePart); - elem = elem.Parent; - } - var typeName = builder.ToString (); - nominalTypes.Add (typeName); - if (isClass) - classes.Add (typeName); - } - - void AddAssociatedTypeToCurrentElement (XElement elem) - { - var parentElement = GetOrCreateParentElement (kAssociatedTypes); - parentElement.Add (elem); - } - - XElement GetOrCreateParentElement (string parentContainerName) - { - var current = currentElement.Peek (); - if (current.Name == kModule) { - return current; - } - var container = GetOrCreate (current, parentContainerName); - return container; - } - - OperatorType GetOperatorType (Function_declarationContext context) - { - var localOp = LocalOperatorType (context); - return localOp == OperatorType.None ? GlobalOperatorType (context.function_name ().GetText ()) - : localOp; - } - - OperatorType LocalOperatorType (Function_declarationContext context) - { - var head = context.function_head (); - - - // if the function declaration contains prefix - if (ModifiersContains (head.declaration_modifiers (), kLittlePrefix)) { - return OperatorType.Prefix; - } else if (ModifiersContains (head.declaration_modifiers (), kLittlePostfix)) { - return OperatorType.Postfix; - } - - var opName = context.function_name ().GetText (); - - foreach (var op in operators) { - var targetName = op.Attribute (kName).Value; - var targetKind = op.Attribute (kOperatorKind).Value; - if (opName == targetName && targetKind == kInfix) - return OperatorType.Infix; - } - return OperatorType.None; - } - - OperatorType GlobalOperatorType (string name) - { - foreach (var op in typeDatabase.FindOperators (importModules)) { - if (op.Name == name) - return op.OperatorType; - } - return OperatorType.None; - } - - void InterpretCommentText (string commentText) - { - if (commentText.StartsWith (kSwiftInterfaceFormatVersion)) { - AssignSwiftInterfaceFormat (commentText.Substring (kSwiftInterfaceFormatVersion.Length)); - } else if (commentText.StartsWith (kSwiftCompilerVersion)) { - AssignSwiftCompilerVersion (commentText.Substring (kSwiftCompilerVersion.Length)); - } else if (commentText.StartsWith (kSwiftModuleFlags)) { - ExtractModuleFlags (commentText.Substring (kSwiftModuleFlags.Length)); - moduleFlags.TryGetValue (kModuleName, out moduleName); - } - } - - void AssignSwiftInterfaceFormat (string formatVersion) - { - // when we get here, we should see something like - // [white-space]*VERSION[white-space] - formatVersion = formatVersion.Trim (); - if (!Version.TryParse (formatVersion, out interfaceVersion)) - throw new ArgumentOutOfRangeException (nameof (formatVersion), $"Expected a version string in the interface format but got {formatVersion}"); - } - - void AssignSwiftCompilerVersion (string compilerVersion) - { - // when we get here, we should see something like: - // [white-space]*Apple? Swift version VERSION (swiftlang-VERSION clang-VERSION) - var parts = compilerVersion.Trim ().Split (' ', '\t'); // don't know if tab is a thing - // expect in the array: - // 0: Apple - // 1: Swift - // 2: verion - // 3: VERSION - - var swiftIndex = Array.IndexOf (parts, "Swift"); - if (swiftIndex < 0) - throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected 'Swift' in the version string, but got {compilerVersion}"); - if (parts [swiftIndex + 1] != "version") - throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected a compiler version string but got {compilerVersion}"); - var version = parts [swiftIndex + 2]; - if (version.EndsWith ("-dev", StringComparison.Ordinal)) - version = version.Substring (0, version.Length - "-dev".Length); - if (!Version.TryParse (version, out this.compilerVersion)) - throw new ArgumentOutOfRangeException (nameof (compilerVersion), $"Expected a compiler version number but got {compilerVersion}"); - } - - void ExtractModuleFlags (string commentText) - { - var args = commentText.Trim ().Split (' ', '\t'); - int index = 0; - while (index < args.Length) { - var arg = args [index++]; - if (arg [0] != '-') - throw new ArgumentOutOfRangeException (nameof (CommentContext), - $"Expected argument {index - 1} to start with a '-' but got {arg} (args: {commentText}"); - var key = arg.Substring (1); - var val = ""; - if (index < args.Length && args [index] [0] != '-') { - val = args [index++]; - } - moduleFlags [key] = val; - } - } - - void SetLanguageVersion (XElement module) - { - if (compilerVersion != null) { - module.Add (new XAttribute ("swiftVersion", compilerVersion.ToString ())); - } - } - - static string XmlBool (bool b) - { - return b ? "true" : "false"; - } - - static string ToAccess (Access_level_modifierContext access) - { - var accessstr = access != null ? access.GetText () : kInternalCap; - switch (accessstr) { - case kPublic: - return kPublicCap; - case kPrivate: - return kPrivateCap; - case kOpen: - return kOpenCap; - case kInternal: - case kInternalCap: - return kInternalCap; - default: - return kUnknown; - } - } - - - static XElement GetOrCreate (XElement elem, string key) - { - var members = elem.Element (key); - if (members == null) { - members = new XElement (key); - elem.Add (members); - } - return members; - } - - static string [] ctorDtorNames = new string [] { - kDotCtor, kDotDtor - }; - - static bool IsCtorDtor (string name) - { - return ctorDtorNames.Contains (name); - } - - public static string UnTick (string str) - { - // a back-ticked string will start and end with ` - // the swift grammar guarantees this. - // Identifier : - // Identifier_head Identifier_characters? - // | OpBackTick Identifier_head Identifier_characters? OpBackTick - // | ImplicitParameterName - // There will be no starting and ending whitespace. - // - // There are some edge cases that we can take advantage of: - // 1. If it starts with `, it *has* to end with back tick, so we don't need to check - // 2. `` will never exist, so the minimum length *has* to be 3 - // In generalized string manipulation, we couldn't make these assumptions, - // but in this case the grammar works for us. - // first weed out the easy cases: - // null, too short, does start and end with back tick - // then just substring it - if (str is null || str.Length < 3 || str [0] != '`') - return str; - return str.Substring (1, str.Length - 2); - } - - - public List ImportModules { get { return importModules; } } - } +namespace SwiftReflector.SwiftInterfaceReflector +{ + public class SwiftInterfaceReflector : SwiftInterfaceBaseListener + { + // swift-interface-format-version: 1.0 + const string kSwiftInterfaceFormatVersion = "// swift-interface-format-version:"; + // swift-compiler-version: Apple Swift version 5.3 (swiftlang-1200.0.29.2 clang-1200.0.30.1) + const string kSwiftCompilerVersion = "// swift-compiler-version: "; + // swift-module-flags: -target x86_64-apple-macosx10.9 -enable-objc-interop -ena + const string kSwiftModuleFlags = "// swift-module-flags:"; + + internal const string kModuleName = "module-name"; + internal const string kTarget = "target"; + internal const string kIgnore = "IGNORE"; + internal const string kInheritanceKind = "inheritanceKind"; + internal const string kModule = "module"; + internal const string kFunc = "func"; + internal const string kType = "type"; + internal const string kName = "name"; + internal const string kFinal = "final"; + internal const string kPublic = "public"; + internal const string kPrivate = "private"; + internal const string kInternal = "internal"; + internal const string kOpen = "open"; + internal const string kPublicCap = "Public"; + internal const string kPrivateCap = "Private"; + internal const string kInternalCap = "Internal"; + internal const string kOpenCap = "Open"; + internal const string kFilePrivate = "fileprivate"; + internal const string kStatic = "static"; + internal const string kIsStatic = "isStatic"; + internal const string kOptional = "optional"; + internal const string kObjC = "objc"; + internal const string kExtension = "extension"; + internal const string kProtocol = "protocol"; + internal const string kClass = "class"; + internal const string kInnerClasses = "innerclasses"; + internal const string kStruct = "struct"; + internal const string kInnerStructs = "innerstructs"; + internal const string kEnum = "enum"; + internal const string kInnerEnums = "innerenums"; + internal const string kMutating = "mutating"; + internal const string kRequired = "required"; + internal const string kAssociatedTypes = "associatedtypes"; + internal const string kAssociatedType = "associatedtype"; + internal const string kDefaultType = "defaulttype"; + internal const string kConformingProtocols = "conformingprotocols"; + internal const string kConformingProtocol = "conformingprotocol"; + internal const string kMembers = "members"; + internal const string kConvenience = "convenience"; + internal const string kParameterLists = "parameterlists"; + internal const string kParameterList = "parameterlist"; + internal const string kParameter = "parameter"; + internal const string kParam = "param"; + internal const string kGenericParameters = "genericparameters"; + internal const string kWhere = "where"; + internal const string kRelationship = "relationship"; + internal const string kEquals = "equals"; + internal const string kInherits = "inherits"; + internal const string kInherit = "inherit"; + internal const string kIndex = "index"; + internal const string kGetSubscript = "get_subscript"; + internal const string kSetSubscript = "set_subscript"; + internal const string kOperator = "operator"; + internal const string kLittlePrefix = "prefix"; + internal const string kLittlePostfix = "postfix"; + internal const string kPrefix = "Prefix"; + internal const string kPostfix = "Postfix"; + internal const string kInfix = "Infix"; + internal const string kDotCtor = ".ctor"; + internal const string kDotDtor = ".dtor"; + internal const string kNewValue = "newValue"; + internal const string kOperatorKind = "operatorKind"; + internal const string kPublicName = "publicName"; + internal const string kPrivateName = "privateName"; + internal const string kKind = "kind"; + internal const string kNone = "None"; + internal const string kLittleUnknown = "unknown"; + internal const string kUnknown = "Unknown"; + internal const string kOnType = "onType"; + internal const string kAccessibility = "accessibility"; + internal const string kIsVariadic = "isVariadic"; + internal const string kTypeDeclaration = "typedeclaration"; + internal const string kIsAsync = "isAsync"; + internal const string kProperty = "property"; + internal const string kIsProperty = "isProperty"; + internal const string kStorage = "storage"; + internal const string kComputed = "Computed"; + internal const string kEscaping = "escaping"; + internal const string kAutoClosure = "autoclosure"; + internal const string kAttributes = "attributes"; + internal const string kAttribute = "attribute"; + internal const string kAttributeParameterList = "attributeparameterlist"; + internal const string kAttributeParameter = "attributeparameter"; + internal const string kLabel = "Label"; + internal const string kLiteral = "Literal"; + internal const string kSeparator = "Separator"; + internal const string kSublist = "Sublist"; + internal const string kValue = "Value"; + internal const string kObjCSelector = "objcSelector"; + internal const string kDeprecated = "deprecated"; + internal const string kUnavailable = "unavailable"; + internal const string kAvailable = "available"; + internal const string kIntroduced = "introduced"; + internal const string kObsoleted = "obsoleted"; + internal const string kElements = "elements"; + internal const string kElement = "element"; + internal const string kIntValue = "intValue"; + internal const string kRawType = "rawType"; + internal const string kRawValue = "RawValue"; + internal const string kTypeAliases = "typealiases"; + internal const string kTypeAlias = "typealias"; + internal const string kSuperclass = "superclass"; + + Stack currentElement = new Stack(); + Version interfaceVersion; + Version compilerVersion; + + List importModules = new List(); + List operators = new List(); + List> functions = new List>(); + List extensions = new List(); + Dictionary moduleFlags = new Dictionary(); + List nominalTypes = new List(); + List classes = new List(); + List associatedTypesWithConformance = new List(); + List unknownInheritance = new List(); + List typeAliasMap = new List(); + string moduleName; + TypeDatabase typeDatabase; + IModuleLoader moduleLoader; + ICharStream inputStream; + + public SwiftInterfaceReflector(TypeDatabase typeDatabase, IModuleLoader moduleLoader) + { + this.typeDatabase = typeDatabase; + this.moduleLoader = moduleLoader; + } + + public async Task ReflectAsync(string inFile, Stream outStm) + { + Exceptions.ThrowOnNull(inFile, nameof(inFile)); + Exceptions.ThrowOnNull(outStm, nameof(outStm)); + + + await Task.Run(() => + { + var xDocument = Reflect(inFile); + xDocument.Save(outStm); + currentElement.Clear(); + }); + } + + public void Reflect(string inFile, Stream outStm) + { + Exceptions.ThrowOnNull(inFile, nameof(inFile)); + Exceptions.ThrowOnNull(outStm, nameof(outStm)); + + var xDocument = Reflect(inFile); + + xDocument.Save(outStm); + currentElement.Clear(); + } + + public async Task ReflectAsync(string inFile) + { + return await Task.Run(() => + { + return Reflect(inFile); + }); + } + + public XDocument Reflect(string inFile) + { + // try { + Exceptions.ThrowOnNull(inFile, nameof(inFile)); + + if (!File.Exists(inFile)) + throw new ParseException($"Input file {inFile} not found"); + + + var fileName = Path.GetFileName(inFile); + moduleName = fileName.Split('.')[0]; + + var module = new XElement(kModule); + currentElement.Push(module); + + var desugarer = new SyntaxDesugaringParser(inFile); + var desugaredResult = desugarer.Desugar(); + inputStream = CharStreams.fromString(desugaredResult); + + var lexer = new SwiftInterfaceLexer(inputStream); + var tokenStream = new CommonTokenStream(lexer); + var parser = new SwiftInterfaceParser(tokenStream); + var walker = new ParseTreeWalker(); + walker.Walk(this, parser.swiftinterface()); + + if (currentElement.Count != 1) + throw new ParseException("At end of parse, stack should contain precisely one element"); + + if (module != currentElement.Peek()) + throw new ParseException("Expected the final element to be the initial module"); + + // LoadReferencedModules (); + + // PatchPossibleOperators (); + // PatchExtensionShortNames (); + // PatchExtensionSelfArgs (); + // PatchPossibleBadInheritance (); + // PatchAssociatedTypeConformance (); + + if (typeAliasMap.Count > 0) + { + module.Add(new XElement(kTypeAliases, typeAliasMap.ToArray())); + } + + module.Add(new XAttribute(kName, moduleName)); + SetLanguageVersion(module); + + var tlElement = new XElement("xamreflect", new XAttribute("version", "1.0"), + new XElement("modulelist", module)); + var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), tlElement); + return xDocument; + // } catch (ParseException parseException) { + // throw; + // } catch (Exception e) { + // throw new ParseException ($"Unknown error parsing {inFile}: {e.Message}", e.InnerException); + // } + } + + public override void EnterComment([NotNull] CommentContext context) + { + var commentText = context.GetText(); + InterpretCommentText(commentText); + } + + public override void EnterClass_declaration([NotNull] Class_declarationContext context) + { + var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: false); + var attributes = GatherAttributes(context.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isObjC = AttributesContains(context.attributes(), kObjC); + var accessibility = ToAccess(context.access_level_modifier()); + var isFinal = context.final_clause() != null || accessibility != kOpenCap; + var typeDecl = ToTypeDeclaration(kClass, UnTick(context.class_name().GetText()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), false); + if (generics != null) + typeDecl.Add(generics); + currentElement.Push(typeDecl); + } + + public override void ExitClass_declaration([NotNull] Class_declarationContext context) + { + var classElem = currentElement.Pop(); + var givenClassName = classElem.Attribute(kName).Value; + var actualClassName = UnTick(context.class_name().GetText()); + if (givenClassName != actualClassName) + throw new ParseException($"class name mismatch on exit declaration: expected {actualClassName} but got {givenClassName}"); + AddClassToCurrentElement(classElem); + } + + public override void EnterStruct_declaration([NotNull] Struct_declarationContext context) + { + var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); + var attributes = GatherAttributes(context.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isFinal = true; // structs are always final + var isObjC = AttributesContains(context.attributes(), kObjC); + var accessibility = ToAccess(context.access_level_modifier()); + var typeDecl = ToTypeDeclaration(kStruct, UnTick(context.struct_name().GetText()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), false); + if (generics != null) + typeDecl.Add(generics); + currentElement.Push(typeDecl); + } + + public override void ExitStruct_declaration([NotNull] Struct_declarationContext context) + { + var structElem = currentElement.Pop(); + var givenStructName = structElem.Attribute(kName).Value; + var actualStructName = UnTick(context.struct_name().GetText()); + if (givenStructName != actualStructName) + throw new ParseException($"struct name mismatch on exit declaration: expected {actualStructName} but got {givenStructName}"); + AddStructToCurrentElement(structElem); + } + + public override void EnterEnum_declaration([NotNull] Enum_declarationContext context) + { + var inheritanceClause = context.union_style_enum()?.type_inheritance_clause() ?? + context.raw_value_style_enum()?.type_inheritance_clause(); + var inheritance = GatherInheritance(inheritanceClause, forceProtocolInheritance: true, removeNonProtocols: true); + var attributes = GatherAttributes(context.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isFinal = true; // enums are always final + var isObjC = AttributesContains(context.attributes(), kObjC); + var accessibility = ToAccess(context.access_level_modifier()); + var typeDecl = ToTypeDeclaration(kEnum, EnumName(context), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + var generics = HandleGenerics(EnumGenericParameters(context), EnumGenericWhere(context), false); + if (generics != null) + typeDecl.Add(generics); + currentElement.Push(typeDecl); + } + + public override void ExitEnum_declaration([NotNull] Enum_declarationContext context) + { + var enumElem = currentElement.Pop(); + var givenEnumName = enumElem.Attribute(kName).Value; + var actualEnumName = EnumName(context); + if (givenEnumName != actualEnumName) + throw new ParseException($"enum name mismatch on exit declaration: expected {actualEnumName} but got {givenEnumName}"); + + var rawType = GetEnumRawType(context); + if (rawType != null) + enumElem.Add(rawType); + + AddEnumToCurrentElement(enumElem); + } + + static string EnumName(Enum_declarationContext context) + { + return UnTick(context.union_style_enum() != null ? + context.union_style_enum().enum_name().GetText() : + context.raw_value_style_enum().enum_name().GetText()); + } + + XAttribute GetEnumRawType(Enum_declarationContext context) + { + var alias = EnumTypeAliases(context).FirstOrDefault(ta => ta.typealias_name().GetText() == kRawValue); + if (alias == null) + return null; + var rawType = TypeText(alias.typealias_assignment().type()); + return new XAttribute(kRawType, rawType); + } + + IEnumerable EnumTypeAliases(Enum_declarationContext context) + { + if (context.union_style_enum() != null) + return UnionTypeAliases(context.union_style_enum()); + else + return RawTypeAliases(context.raw_value_style_enum()); + } + + IEnumerable UnionTypeAliases(Union_style_enumContext context) + { + var members = context.union_style_enum_members(); + while (members != null) + { + if (members.union_style_enum_member() != null) + { + var member = members.union_style_enum_member(); + if (member.nominal_declaration()?.typealias_declaration() != null) + yield return member.nominal_declaration().typealias_declaration(); + } + members = members.union_style_enum_members(); + } + yield break; + } + + IEnumerable RawTypeAliases(Raw_value_style_enumContext context) + { + var members = context.raw_value_style_enum_members(); + while (members != null) + { + if (members.raw_value_style_enum_member() != null) + { + var member = members.raw_value_style_enum_member(); + if (member.nominal_declaration()?.typealias_declaration() != null) + yield return member.nominal_declaration().typealias_declaration(); + } + members = members.raw_value_style_enum_members(); + } + yield break; + } + + public override void EnterRaw_value_style_enum_case_clause([NotNull] Raw_value_style_enum_case_clauseContext context) + { + var enumElements = new XElement(kElements); + foreach (var enumCase in RawCases(context.raw_value_style_enum_case_list())) + { + var enumElement = ToRawEnumElement(enumCase); + enumElements.Add(enumElement); + } + AddEnumNonEmptyElements(enumElements); + } + + public override void EnterUnion_style_enum_case_clause([NotNull] Union_style_enum_case_clauseContext context) + { + var enumElements = new XElement(kElements); + foreach (var enumCase in UnionCases(context.union_style_enum_case_list())) + { + var enumElement = ToUnionEnumElement(enumCase); + enumElements.Add(enumElement); + } + AddEnumNonEmptyElements(enumElements); + } + + void AddEnumNonEmptyElements(XElement enumElements) + { + if (enumElements.HasElements) + { + var currentEnum = currentElement.Peek(); + if (currentEnum.Attribute(kKind)?.Value != kEnum) + throw new ParseException("Current element needs to be an enum"); + + var existingElements = currentEnum.Element(kElements); + if (existingElements != null) + { + foreach (var elem in enumElements.Elements()) + { + existingElements.Add(elem); + } + } + else + { + currentEnum.Add(enumElements); + } + } + } + + IEnumerable RawCases(Raw_value_style_enum_case_listContext context) + { + while (context != null) + { + if (context.raw_value_style_enum_case() != null) + { + yield return context.raw_value_style_enum_case(); + } + context = context.raw_value_style_enum_case_list(); + } + yield break; + } + + XElement ToRawEnumElement(Raw_value_style_enum_caseContext context) + { + var enumElem = new XElement(kElement, new XAttribute(kName, UnTick(context.enum_case_name().GetText()))); + var value = context.raw_value_assignment(); + if (value != null) + enumElem.Add(new XAttribute(kIntValue, value.raw_value_literal().GetText())); + return enumElem; + } + + IEnumerable UnionCases(Union_style_enum_case_listContext context) + { + while (context != null) + { + if (context.union_style_enum_case() != null) + { + yield return context.union_style_enum_case(); + } + context = context.union_style_enum_case_list(); + } + yield break; + } + + XElement ToUnionEnumElement(Union_style_enum_caseContext context) + { + var enumElement = new XElement(kElement, new XAttribute(kName, UnTick(context.enum_case_name().GetText()))); + if (context.tuple_type() != null) + { + var tupString = TypeText(context.tuple_type()); + // special casing: + // the type of a union case is a tuple, but we special case + // unit tuples to be just the type of the unit + // which may be something like ((((((())))))) + // in which case we want to let it come through as is. + // a unit tuple may also have a type label which we don't care + // about so make that go away too. + + if (tupString.IndexOf(',') < 0 && tupString.IndexOf(':') < 0) + { + var pastLastOpen = tupString.LastIndexOf('(') + 1; + var firstClosed = tupString.IndexOf(')'); + if (pastLastOpen != firstClosed) + { + tupString = tupString.Substring(pastLastOpen, firstClosed - pastLastOpen); + var colonIndex = tupString.IndexOf(':'); + if (colonIndex >= 0) + { + tupString = tupString.Substring(colonIndex + 1); + } + } + } + enumElement.Add(new XAttribute(kType, tupString)); + } + return enumElement; + } + + public override void EnterProtocol_declaration([NotNull] Protocol_declarationContext context) + { + var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); + var attributes = GatherAttributes(context.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isFinal = true; // protocols don't have final + var isObjC = AttributesContains(context.attributes(), kObjC); + var accessibility = ToAccess(context.access_level_modifier()); + var typeDecl = ToTypeDeclaration(kProtocol, UnTick(context.protocol_name().GetText()), + accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, + attributes); + currentElement.Push(typeDecl); + } + + public override void ExitProtocol_declaration([NotNull] Protocol_declarationContext context) + { + var protocolElem = currentElement.Pop(); + var givenProtocolName = protocolElem.Attribute(kName).Value; + var actualProtocolName = UnTick(context.protocol_name().GetText()); + if (givenProtocolName != actualProtocolName) + throw new ParseException($"protocol name mismatch on exit declaration: expected {actualProtocolName} but got {givenProtocolName}"); + if (currentElement.Peek().Name != kModule) + throw new ParseException($"Expected a module on the element stack but found {currentElement.Peek()}"); + currentElement.Peek().Add(protocolElem); + } + + public override void EnterProtocol_associated_type_declaration([NotNull] Protocol_associated_type_declarationContext context) + { + var conformingProtocols = GatherConformingProtocols(context.type_inheritance_clause()); + var defaultDefn = TypeText(context.typealias_assignment()?.type()); + var assocType = new XElement(kAssociatedType, + new XAttribute(kName, UnTick(context.typealias_name().GetText()))); + if (defaultDefn != null) + assocType.Add(new XAttribute(kDefaultType, UnTick(defaultDefn))); + if (conformingProtocols != null && conformingProtocols.Count > 0) + { + var confomingElem = new XElement(kConformingProtocols, conformingProtocols.ToArray()); + assocType.Add(confomingElem); + associatedTypesWithConformance.Add(assocType); + } + AddAssociatedTypeToCurrentElement(assocType); + } + + List GatherConformingProtocols(Type_inheritance_clauseContext context) + { + if (context == null) + return null; + var elems = new List(); + if (context.class_requirement() != null) + { + // not sure what to do here + // this is just the keyword 'class' + } + var inheritance = context.type_inheritance_list(); + while (inheritance != null) + { + var elem = inheritance.GetText(); + var name = TypeText(inheritance.type_identifier()); + if (name != null) + elems.Add(new XElement(kConformingProtocol, new XAttribute(kName, UnTick(name)))); + inheritance = inheritance.type_inheritance_list(); + } + return elems; + } + + static Generic_parameter_clauseContext EnumGenericParameters(Enum_declarationContext context) + { + return context.union_style_enum()?.generic_parameter_clause() ?? + context.raw_value_style_enum()?.generic_parameter_clause(); + } + + static Generic_where_clauseContext EnumGenericWhere(Enum_declarationContext context) + { + return context.union_style_enum()?.generic_where_clause() ?? + context.raw_value_style_enum()?.generic_where_clause(); + } + + public override void EnterFunction_declaration([NotNull] Function_declarationContext context) + { + var head = context.function_head(); + var signature = context.function_signature(); + + var name = UnTick(context.function_name().GetText()); + var returnType = signature.function_result() != null ? TypeText(signature.function_result().type()) : "()"; + var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); + var isStatic = IsStaticOrClass(head.declaration_modifiers()); + var hasThrows = signature.throws_clause() != null || signature.rethrows_clause() != null; + var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); + var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); + var isConvenienceInit = false; + var operatorKind = kNone; + var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); + var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); + var isProperty = false; + var attributes = GatherAttributes(head.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isAsync = signature.async_clause() != null; + var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync, attributes); + var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), true); + if (generics != null) + functionDecl.Add(generics); + + + functions.Add(new Tuple(context, functionDecl)); + currentElement.Push(functionDecl); + } + + public override void ExitFunction_declaration([NotNull] Function_declarationContext context) + { + ExitFunctionWithName(UnTick(context.function_name().GetText())); + } + + void ExitFunctionWithName(string expectedName) + { + var functionDecl = currentElement.Pop(); + if (functionDecl.Name != kFunc) + throw new ParseException($"Expected a func node but got a {functionDecl.Name}"); + var givenName = functionDecl.Attribute(kName); + if (givenName == null) + throw new ParseException("func node doesn't have a name element"); + if (givenName.Value != expectedName) + throw new ParseException($"Expected a func node with name {expectedName} but got {givenName.Value}"); + + AddObjCSelector(functionDecl); + + AddElementToParentMembers(functionDecl); + } + + void AddObjCSelector(XElement functionDecl) + { + var selectorFactory = new ObjCSelectorFactory(functionDecl); + var selector = selectorFactory.Generate(); + if (!String.IsNullOrEmpty(selector)) + { + functionDecl.Add(new XAttribute(kObjCSelector, selector)); + } + } + + XElement PeekAsFunction() + { + var functionDecl = currentElement.Peek(); + if (functionDecl.Name != kFunc) + throw new ParseException($"Expected a func node but got a {functionDecl.Name}"); + return functionDecl; + } + + void AddElementToParentMembers(XElement elem) + { + var parent = currentElement.Peek(); + if (parent.Name == kModule) + { + parent.Add(elem); + return; + } + var memberElem = GetOrCreate(parent, kMembers); + memberElem.Add(elem); + } + + bool IsInInstance() + { + var parent = currentElement.Peek(); + return parent.Name != kModule; + } + + bool HasObjCElement(XElement elem) + { + var objcAttr = elem.Descendants() + .FirstOrDefault(el => el.Name == kAttribute && el.Attribute("name")?.Value == kObjC); + return objcAttr != null; + } + + public override void EnterInitializer_declaration([NotNull] Initializer_declarationContext context) + { + var head = context.initializer_head(); + + var name = kDotCtor; + + // may be optional, otherwise return type is the instance type + var returnType = GetInstanceName() + (head.OpQuestion() != null ? "?" : ""); + var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); + var isStatic = true; + var hasThrows = context.throws_clause() != null || context.rethrows_clause() != null; + var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); + var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); + var isConvenienceInit = ModifiersContains(head.declaration_modifiers(), kConvenience); + var operatorKind = kNone; + var attributes = GatherAttributes(head.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); + var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); + var isProperty = false; + var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, + isAsync: false, attributes); + currentElement.Push(functionDecl); + } + + public override void ExitInitializer_declaration([NotNull] Initializer_declarationContext context) + { + ExitFunctionWithName(kDotCtor); + } + + public override void EnterDeinitializer_declaration([NotNull] Deinitializer_declarationContext context) + { + var name = kDotDtor; + var returnType = "()"; + // this might have to be forced to public, otherwise deinit is always internal, which it + // decidedly is NOT. + var accessibility = kPublic; + var isStatic = false; + var hasThrows = false; + var isFinal = ModifiersContains(context.declaration_modifiers(), kFinal); + var isOptional = ModifiersContains(context.declaration_modifiers(), kOptional); + var isConvenienceInit = false; + var operatorKind = kNone; + var attributes = GatherAttributes(context.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isMutating = ModifiersContains(context.declaration_modifiers(), kMutating); + var isRequired = ModifiersContains(context.declaration_modifiers(), kRequired); + var isProperty = false; + var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + // always has two parameter lists: (instance)() + currentElement.Push(functionDecl); + var parameterLists = new XElement(kParameterLists, MakeInstanceParameterList()); + currentElement.Pop(); + + parameterLists.Add(new XElement(kParameterList, new XAttribute(kIndex, "1"))); + functionDecl.Add(parameterLists); + + currentElement.Push(functionDecl); + } + + public override void ExitDeinitializer_declaration([NotNull] Deinitializer_declarationContext context) + { + ExitFunctionWithName(kDotDtor); + } + + public override void EnterSubscript_declaration([NotNull] Subscript_declarationContext context) + { + // subscripts are...funny. + // They have one parameter list but expand out to two function declarations + // To handle this, we process the parameter list here for the getter + // If there's a setter, we make one of those too. + // Then since we're effectively done, we push a special XElement on the stack + // named IGNORE which will make the parameter list event handler exit. + // On ExitSubscript_declaration, we remove the IGNORE tag + + var head = context.subscript_head(); + var resultType = TypeText(context.subscript_result().type()); + var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); + var attributes = GatherAttributes(head.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isStatic = false; + var hasThrows = false; + var isAsync = HasAsync(context.getter_setter_keyword_block()?.getter_keyword_clause()); + var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); + var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); + var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); + var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); + var isProperty = true; + + var getParamList = MakeParameterList(head.parameter_clause().parameter_list(), 1, true); + var getFunc = ToFunctionDeclaration(kGetSubscript, resultType, accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); + + currentElement.Push(getFunc); + var getParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), getParamList); + currentElement.Pop(); + + getFunc.Add(getParamLists); + AddObjCSelector(getFunc); + + AddElementToParentMembers(getFunc); + + var setParamList = context.getter_setter_keyword_block()?.setter_keyword_clause() != null + ? MakeParameterList(head.parameter_clause().parameter_list(), 1, true, startIndex: 1) : null; + + + if (setParamList != null) + { + var index = 0; + var parmName = context.getter_setter_keyword_block().setter_keyword_clause().new_value_name()?.GetText() + ?? kNewValue; + var newValueParam = new XElement(kParameter, new XAttribute(nameof(index), index.ToString()), + new XAttribute(kType, resultType), new XAttribute(kPublicName, ""), + new XAttribute(kPrivateName, parmName), new XAttribute(kIsVariadic, false)); + setParamList.AddFirst(newValueParam); + + var setFunc = ToFunctionDeclaration(kSetSubscript, "()", accessibility, isStatic, hasThrows, + isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, + isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + currentElement.Push(setFunc); + var setParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), setParamList); + currentElement.Pop(); + + setFunc.Add(setParamLists); + AddObjCSelector(setFunc); + AddElementToParentMembers(setFunc); + } + + // this makes the subscript parameter list get ignored because we already handled it. + PushIgnore(); + } + + public override void ExitSubscript_declaration([NotNull] Subscript_declarationContext context) + { + PopIgnore(); + } + + string TypeText(ParserRuleContext ty) + { + return SyntaxDesugaringParser.TypeText(inputStream, ty); + } + + public override void EnterVariable_declaration([NotNull] Variable_declarationContext context) + { + var head = context.variable_declaration_head(); + var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); + var attributes = GatherAttributes(head.attributes()); + var isDeprecated = CheckForDeprecated(attributes); + var isUnavailable = CheckForUnavailable(attributes); + var isStatic = ModifiersContains(head.declaration_modifiers(), kStatic); + var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); + var isLet = head.let_clause() != null; + var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); + var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); + var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); + var isProperty = true; + + foreach (var tail in context.variable_declaration_tail()) + { + var name = UnTick(tail.variable_name().GetText()); + var resultType = TypeText(tail.type_annotation().type()); + var hasThrows = false; + var isAsync = HasAsync(tail.getter_setter_keyword_block()?.getter_keyword_clause()); + + var getParamList = new XElement(kParameterList, new XAttribute(kIndex, "1")); + var getFunc = ToFunctionDeclaration("get_" + name, + resultType, accessibility, isStatic, hasThrows, isFinal, isOptional, + isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, + isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); + + currentElement.Push(getFunc); + var getParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), getParamList); + currentElement.Pop(); + getFunc.Add(getParamLists); + AddElementToParentMembers(getFunc); + AddObjCSelector(getFunc); + + var setParamList = HasSetter(tail, isLet) ? + new XElement(kParameterList, new XAttribute(kIndex, "1")) : null; + + if (setParamList != null) + { + var parmName = tail.getter_setter_keyword_block()?.setter_keyword_clause().new_value_name()?.GetText() + ?? kNewValue; + var setterType = EscapePossibleClosureType(resultType); + var newValueParam = new XElement(kParameter, new XAttribute(kIndex, "0"), + new XAttribute(kType, setterType), new XAttribute(kPublicName, parmName), + new XAttribute(kPrivateName, parmName), new XAttribute(kIsVariadic, false)); + setParamList.Add(newValueParam); + var setFunc = ToFunctionDeclaration("set_" + name, + "()", accessibility, isStatic, hasThrows, isFinal, isOptional, + isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, + isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); + + currentElement.Push(setFunc); + var setParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), setParamList); + currentElement.Pop(); + + setFunc.Add(setParamLists); + AddElementToParentMembers(setFunc); + AddObjCSelector(setFunc); + } + + var prop = new XElement(kProperty, new XAttribute(kName, name), + new XAttribute(nameof(accessibility), accessibility), + new XAttribute(kType, resultType), + new XAttribute(kStorage, kComputed), + new XAttribute(nameof(isStatic), XmlBool(isStatic)), + new XAttribute(nameof(isLet), XmlBool(isLet)), + new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated)), + new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable)), + new XAttribute(nameof(isOptional), XmlBool(isOptional))); + AddElementToParentMembers(prop); + } + + PushIgnore(); + } + + bool HasSetter(Variable_declaration_tailContext context, bool isLet) + { + // conditions for having a setter: + // defaultInitializer and getter_setter_keyword are both null (public var foo: Type) + // defaultInitializer is not null (public var foo: Type = initialValue) + // getter_setter_keyword_block is non-null and the getter_setter_keyword_block + // has a non-null setter_keyword_clause (public var foo:Type { get; set; }, public foo: Type { set } + + var defaultInitializer = context.defaultInitializer(); + var gettersetter = context.getter_setter_keyword_block(); + + return !isLet && ((defaultInitializer == null && gettersetter == null) || + defaultInitializer != null || + gettersetter?.setter_keyword_clause() != null); + } + + public override void EnterExtension_declaration([NotNull] Extension_declarationContext context) + { + var onType = UnTick(TypeText(context.type_identifier())); + var inherits = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); + // why, you say, why put a kKind tag into an extension? + // The reason is simple: this is a hack. Most of the contents + // of an extension are the same as a class and as a result we can + // pretend that it's a class and everything will work to fill it out + // using the class/struct/enum code for members. + var extensionElem = new XElement(kExtension, + new XAttribute(nameof(onType), onType), + new XAttribute(kKind, kClass)); + if (inherits?.Count > 0) + extensionElem.Add(new XElement(nameof(inherits), inherits.ToArray())); + currentElement.Push(extensionElem); + extensions.Add(extensionElem); + } + + public override void ExitExtension_declaration([NotNull] Extension_declarationContext context) + { + var extensionElem = currentElement.Pop(); + var onType = extensionElem.Attribute(kOnType); + var givenOnType = onType.Value; + var actualOnType = UnTick(TypeText(context.type_identifier())); + if (givenOnType != actualOnType) + throw new Exception($"extension type mismatch on exit declaration: expected {actualOnType} but got {givenOnType}"); + // remove the kKind attribute - you've done your job. + extensionElem.Attribute(kKind)?.Remove(); + + currentElement.Peek().Add(extensionElem); + } + + public override void ExitImport_statement([NotNull] Import_statementContext context) + { + // this is something like: import class Foo.Bar + // and we're not handling that yet + if (context.import_kind() != null) + return; + importModules.Add(context.import_path().GetText()); + } + + public override void EnterOperator_declaration([NotNull] Operator_declarationContext context) + { + var operatorElement = InfixOperator(context.infix_operator_declaration()) + ?? PostfixOperator(context.postfix_operator_declaration()) + ?? PrefixOperator(context.prefix_operator_declaration()); + operators.Add(operatorElement); + + currentElement.Peek().Add(operatorElement); + } + + public override void EnterOptional_type([NotNull] Optional_typeContext context) + { + } + + XElement InfixOperator(Infix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator(kInfix, context.@operator(), + context.infix_operator_group()?.precedence_group_name()?.GetText() ?? ""); + } + + XElement PostfixOperator(Postfix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator(kPostfix, context.@operator(), ""); + } + + XElement PrefixOperator(Prefix_operator_declarationContext context) + { + if (context == null) + return null; + return GeneralOperator(kPrefix, context.@operator(), ""); + } + + XElement GeneralOperator(string operatorKind, OperatorContext context, string precedenceGroup) + { + return new XElement(kOperator, + new XAttribute(kName, context.Operator().GetText()), + new XAttribute(nameof(operatorKind), operatorKind), + new XAttribute(nameof(precedenceGroup), precedenceGroup)); + } + + XElement HandleGenerics(Generic_parameter_clauseContext genericContext, Generic_where_clauseContext whereContext, bool addParentGenerics) + { + if (genericContext == null) + return null; + var genericElem = new XElement(kGenericParameters); + if (addParentGenerics) + AddParentGenerics(genericElem); + foreach (var generic in genericContext.generic_parameter_list().generic_parameter()) + { + var name = UnTick(TypeText(generic.type_name())); + var genParam = new XElement(kParam, new XAttribute(kName, name)); + genericElem.Add(genParam); + var whereType = TypeText(generic.type_identifier()) ?? + TypeText(generic.protocol_composition_type()); + if (whereType != null) + { + genericElem.Add(MakeConformanceWhere(name, whereType)); + } + } + + if (whereContext == null) + return genericElem; + + foreach (var requirement in whereContext.requirement_list().requirement()) + { + if (requirement.conformance_requirement() != null) + { + var name = UnTick(TypeText(requirement.conformance_requirement().type_identifier()[0])); + + // if there is no protocol composition type, then it's the second type identifier + var from = TypeText(requirement.conformance_requirement().protocol_composition_type()) + ?? TypeText(requirement.conformance_requirement().type_identifier()[1]); + genericElem.Add(MakeConformanceWhere(name, from)); + } + else + { + var name = UnTick(TypeText(requirement.same_type_requirement().type_identifier())); + var type = TypeText(requirement.same_type_requirement().type()); + genericElem.Add(MakeEqualityWhere(name, type)); + } + } + + return genericElem; + } + + public override void ExitTypealias_declaration([NotNull] Typealias_declarationContext context) + { + var name = UnTick(context.typealias_name().GetText()); + var generics = TypeText(context.generic_parameter_clause()) ?? ""; + var targetType = TypeText(context.typealias_assignment().type()); + var access = ToAccess(context.access_level_modifier()); + var map = new XElement(kTypeAlias, new XAttribute(kName, name + generics), + new XAttribute(kAccessibility, access), + new XAttribute(kType, targetType)); + if (access != null) + { + if (currentElement.Peek().Name == kModule) + { + typeAliasMap.Add(map); + } + else + { + var curr = currentElement.Peek(); + var aliaslist = curr.Element(kTypeAliases); + if (aliaslist == null) + { + aliaslist = new XElement(kTypeAliases); + curr.Add(aliaslist); + } + aliaslist.Add(map); + } + } + } + + XElement MakeConformanceWhere(string name, string from) + { + return new XElement(kWhere, new XAttribute(nameof(name), name), + new XAttribute(kRelationship, kInherits), + new XAttribute(nameof(from), from)); + } + + XElement MakeEqualityWhere(string firsttype, string secondtype) + { + return new XElement(kWhere, new XAttribute(nameof(firsttype), firsttype), + new XAttribute(kRelationship, kEquals), + new XAttribute(nameof(secondtype), secondtype)); + } + + public override void ExitVariable_declaration([NotNull] Variable_declarationContext context) + { + PopIgnore(); + } + + void PushIgnore() + { + currentElement.Push(new XElement(kIgnore)); + } + + void PopIgnore() + { + var elem = currentElement.Pop(); + if (elem.Name != kIgnore) + throw new ParseException($"Expected an {kIgnore} element, but got {elem}"); + } + + bool ShouldIgnore() + { + return currentElement.Peek().Name == kIgnore; + } + + public override void EnterParameter_clause([NotNull] Parameter_clauseContext context) + { + if (ShouldIgnore()) + return; + + var parameterLists = new XElement(kParameterLists); + XElement instanceList = MakeInstanceParameterList(); + var formalIndex = 0; + if (instanceList != null) + { + parameterLists.Add(instanceList); + formalIndex = 1; + } + + var formalArguments = MakeParameterList(context.parameter_list(), formalIndex, false); + + parameterLists.Add(formalArguments); + currentElement.Peek().Add(parameterLists); + } + + XElement MakeParameterList(Parameter_listContext parmList, int index, bool isSubscript, int startIndex = 0) + { + var formalArguments = new XElement(kParameterList, new XAttribute(kIndex, index.ToString())); + + if (parmList != null) + { + var i = startIndex; + foreach (var parameter in parmList.parameter()) + { + var parameterElement = ToParameterElement(parameter, i, isSubscript); + formalArguments.Add(parameterElement); + i++; + } + } + return formalArguments; + } + + XElement MakeInstanceParameterList() + { + var topElem = currentElement.Peek(); + if (topElem.Name == kModule) + return null; + if (topElem.Name != kFunc) + throw new ParseException($"Expecting a func node but got {topElem.Name}"); + if (NominalParentAfter(0) == null) + return null; + var funcName = topElem.Attribute(kName).Value; + var isStatic = topElem.Attribute(kIsStatic).Value == "true"; + var isCtorDtor = IsCtorDtor(funcName); + var isClass = NominalParentAfter(0).Attribute(kKind).Value == kClass; + var instanceName = GetInstanceName(); + var type = $"{(isClass ? "" : "inout ")}{instanceName}{(isCtorDtor ? ".Type" : "")}"; + var parameter = new XElement(kParameter, new XAttribute(kType, type), + new XAttribute(kIndex, "0"), new XAttribute(kPublicName, "self"), + new XAttribute(kPrivateName, "self"), new XAttribute(kIsVariadic, "false")); + return new XElement(kParameterList, new XAttribute(kIndex, "0"), parameter); + } + + void AddParentGenerics(XElement genericResult) + { + var parentGenerics = new List(); + for (int i = 0; i < currentElement.Count; i++) + { + var elem = currentElement.ElementAt(i); + if (!IsNominal(elem)) + continue; + var elemGenerics = elem.Element(kGenericParameters); + if (elemGenerics == null) + continue; + foreach (var param in elemGenerics.Descendants(kParam)) + { + parentGenerics.Add(new XElement(param)); + } + } + genericResult.Add(parentGenerics.ToArray()); + } + + XElement NominalParentAfter(int start) + { + for (var i = start + 1; i < currentElement.Count; i++) + { + var elem = currentElement.ElementAt(i); + if (IsNominal(elem)) + return elem; + } + return null; + } + + bool IsNominal(XElement elem) + { + var kind = elem.Attribute(kKind)?.Value; + return kind != null && (kind == kClass || kind == kStruct || kind == kEnum || kind == kProtocol); + } + + string GetInstanceName() + { + var nameBuffer = new StringBuilder(); + for (int i = 0; i < currentElement.Count; i++) + { + var elem = currentElement.ElementAt(i); + if (IsNominal(elem)) + { + if (elem.Name == kExtension) + return elem.Attribute(kOnType).Value; + if (nameBuffer.Length > 0) + nameBuffer.Insert(0, '.'); + nameBuffer.Insert(0, elem.Attribute(kName).Value); + var generics = elem.Element(kGenericParameters); + if (generics != null) + { + AddGenericsToName(nameBuffer, generics); + } + } + } + nameBuffer.Insert(0, '.'); + var module = currentElement.Last(); + nameBuffer.Insert(0, moduleName); + return nameBuffer.ToString(); + } + + void AddGenericsToName(StringBuilder nameBuffer, XElement generics) + { + var isFirst = true; + foreach (var name in GenericNames(generics)) + { + if (isFirst) + { + nameBuffer.Append("<"); + isFirst = false; + } + else + { + nameBuffer.Append(", "); + } + nameBuffer.Append(name); + } + if (!isFirst) + nameBuffer.Append(">"); + } + + IEnumerable GenericNames(XElement generics) + { + return generics.Elements().Where(elem => elem.Name == kParam).Select(elem => elem.Attribute(kName).Value); + } + + XElement ToParameterElement(ParameterContext context, int index, bool isSubscript) + { + var typeAnnotation = context.type_annotation(); + var isInOut = typeAnnotation.inout_clause() != null; + var type = TypeText(typeAnnotation.type()); + var privateName = NoUnderscore(UnTick(context.local_parameter_name()?.GetText()) ?? ""); + var replacementPublicName = isSubscript ? "" : privateName; + var publicName = NoUnderscore(UnTick(context.external_parameter_name()?.GetText()) ?? replacementPublicName); + var isVariadic = context.range_operator() != null; + if (isVariadic) + type = $"Swift.Array<{type}>"; + var isEscaping = AttributesContains(typeAnnotation.attributes(), kEscaping); + var isAutoClosure = AttributesContains(typeAnnotation.attributes(), kAutoClosure); + var typeBuilder = new StringBuilder(); + if (isEscaping) + typeBuilder.Append("@escaping[] "); + if (isAutoClosure) + typeBuilder.Append("@autoclosure[] "); + if (isInOut) + typeBuilder.Append("inout "); + typeBuilder.Append(type); + type = typeBuilder.ToString(); + + var paramElement = new XElement(kParameter, new XAttribute(nameof(index), index.ToString()), + new XAttribute(nameof(type), type), new XAttribute(nameof(publicName), publicName), + new XAttribute(nameof(privateName), privateName), new XAttribute(nameof(isVariadic), XmlBool(isVariadic))); + return paramElement; + } + + static string NoUnderscore(string s) + { + return s == "_" ? "" : s; + } + + XElement GatherAttributes(AttributesContext context) + { + if (context == null) + return null; + var attributes = new XElement(kAttributes); + foreach (var attr in context.attribute()) + { + var attrElement = GatherAttribute(attr); + if (attrElement != null) + attributes.Add(attrElement); + } + return attributes.HasElements ? attributes : null; + } + + XElement GatherAttribute(AttributeContext context) + { + var attribute = new XElement(kAttribute, new XAttribute(kName, context.attribute_name().GetText())); + if (context.attribute_argument_clause() != null) + { + var parameters = GatherParameters(context.attribute_argument_clause()?.balanced_tokens()); + if (parameters != null) + attribute.Add(parameters); + } + return attribute; + } + + XElement GatherParameters(Balanced_tokensContext context) + { + if (context == null) + return null; + var parameterlist = new XElement(kAttributeParameterList); + + foreach (var balancedToken in context.balanced_token()) + { + var parameter = ToAttributeParameter(balancedToken); + if (parameter != null) + parameterlist.Add(parameter); + } + return parameterlist.HasElements ? parameterlist : null; + } + + XElement ToAttributeParameter(Balanced_tokenContext context) + { + if (context.balanced_tokens() != null) + { + var sublist = new XElement(kAttributeParameter, new XAttribute(kKind, kSublist)); + var subparams = GatherParameters(context.balanced_tokens()); + if (subparams != null) + sublist.Add(subparams); + return sublist; + } + + if (context.label_identifier() != null) + { + var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), + new XAttribute(kValue, context.label_identifier().GetText())); + return label; + } + + if (context.literal() != null) + { + var literal = new XElement(kAttributeParameter, new XAttribute(kKind, kLiteral), + new XAttribute(kValue, context.literal().GetText())); + return literal; + } + + // make the operator look like a label + if (context.@operator() != null) + { + var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), + new XAttribute(kValue, context.@operator().GetText())); + return label; + } + + if (context.any_punctuation_for_balanced_token() != null) + { + var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), + new XAttribute(kValue, context.any_punctuation_for_balanced_token().GetText())); + return label; + } + + return null; + } + + List GatherInheritance(Type_inheritance_clauseContext context, bool forceProtocolInheritance, + bool removeNonProtocols = false) + { + var inheritance = new List(); + if (context == null) + return inheritance; + var list = context.type_inheritance_list(); + bool first = true; + while (list != null) + { + var inheritanceKind = forceProtocolInheritance ? kProtocol : + (inheritance.Count > 0 ? kProtocol : kLittleUnknown); + var type = TypeText(list.type_identifier()); + if (!(first && removeNonProtocols && TypeIsNotProtocol(type))) + { + var elem = new XElement(kInherit, new XAttribute(kType, type), + new XAttribute(nameof(inheritanceKind), inheritanceKind)); + inheritance.Add(elem); + if (inheritanceKind == kLittleUnknown) + unknownInheritance.Add(elem); + } + first = false; + list = list.type_inheritance_list(); + } + + return inheritance; + } + + bool TypeIsNotProtocol(string type) + { + // special case this - the type database as this as "other" + // which is technically not a protocol, but it is a protocol. + if (type == "Swift.Error") + return false; + var parts = type.Split('.'); + if (parts.Length == 1) + return true; // generic + var module = parts[0]; + if (!typeDatabase.ModuleNames.Contains(module)) + { + moduleLoader.Load(module, typeDatabase); + } + var entity = typeDatabase.TryGetEntityForSwiftName(type); + if (entity != null && entity.EntityType != EntityType.Protocol) + return true; + return false; + } + + XElement ToTypeDeclaration(string kind, string name, string accessibility, bool isObjC, + bool isFinal, bool isDeprecated, bool isUnavailable, List inherits, XElement generics, + XElement attributes) + { + var xobjects = new List(); + if (generics != null) + xobjects.Add(generics); + xobjects.Add(new XAttribute(nameof(kind), kind)); + xobjects.Add(new XAttribute(nameof(name), name)); + xobjects.Add(new XAttribute(nameof(accessibility), accessibility)); + xobjects.Add(new XAttribute(nameof(isObjC), XmlBool(isObjC))); + xobjects.Add(new XAttribute(nameof(isFinal), XmlBool(isFinal))); + xobjects.Add(new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated))); + xobjects.Add(new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable))); + + xobjects.Add(new XElement(kMembers)); + if (inherits != null && inherits.Count > 0) + xobjects.Add(new XElement(nameof(inherits), inherits.ToArray())); + if (attributes != null) + xobjects.Add(attributes); + return new XElement(kTypeDeclaration, xobjects.ToArray()); + } + + + XElement ToFunctionDeclaration(string name, string returnType, string accessibility, + bool isStatic, bool hasThrows, bool isFinal, bool isOptional, bool isConvenienceInit, + string objCSelector, string operatorKind, bool isDeprecated, bool isUnavailable, + bool isMutating, bool isRequired, bool isProperty, bool isAsync, XElement attributes) + { + var decl = new XElement(kFunc, new XAttribute(nameof(name), name), new XAttribute(nameof(returnType), returnType), + new XAttribute(nameof(accessibility), accessibility), new XAttribute(nameof(isStatic), XmlBool(isStatic)), + new XAttribute(nameof(hasThrows), XmlBool(hasThrows)), new XAttribute(nameof(isFinal), XmlBool(isFinal)), + new XAttribute(nameof(isOptional), XmlBool(isOptional)), + new XAttribute(nameof(isConvenienceInit), XmlBool(isConvenienceInit)), + new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated)), + new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable)), + new XAttribute(nameof(isRequired), XmlBool(isRequired)), + new XAttribute(kIsAsync, XmlBool(isAsync)), + new XAttribute(kIsProperty, XmlBool(isProperty)), + new XAttribute(nameof(isMutating), XmlBool(isMutating))); + + if (operatorKind != null) + { + decl.Add(new XAttribute(nameof(operatorKind), operatorKind)); + } + if (objCSelector != null) + { + decl.Add(new XAttribute(nameof(objCSelector), objCSelector)); + } + if (attributes != null) + { + decl.Add(attributes); + } + return decl; + } + + bool CheckForDeprecated(XElement attributes) + { + var availableTags = AvailableAttributes(attributes); + foreach (var attribute in availableTags) + { + var args = AttrbuteParameters(attribute); + var platform = args[0]; + if (!PlatformMatches(platform)) + continue; + + var deprecatedIndex = args.IndexOf(kDeprecated); + if (deprecatedIndex < 0) + continue; + var deprecatedVersion = GetVersionAfter(args, deprecatedIndex); + if (TargetVersionIsLessOrEqual(deprecatedVersion)) + return true; + } + return false; + } + + bool CheckForUnavailable(XElement attributes) + { + var availableTags = AvailableAttributes(attributes); + foreach (var attribute in availableTags) + { + var args = AttrbuteParameters(attribute); + // if unavailable exists, need to match platform + if (args.IndexOf(kUnavailable) >= 0 && PlatformMatches(args[0])) + return true; + + } + return !CheckForAvailable(attributes); + } + + bool CheckForAvailable(XElement attributes) + { + var availableTags = AvailableAttributes(attributes); + foreach (var attribute in availableTags) + { + var args = AttrbuteParameters(attribute); + if (IsShortHand(args)) + { + return AvailableShorthand(args); + } + else + { + return AvailableLonghand(args); + } + } + return true; + } + + bool AvailableLonghand(List args) + { + // args will be plat , specifiers + // specificers will be: + // introduced: version + // deprecated: version + // obsoleted: version + // unavailable + var platform = args[0]; + if (!PlatformMatches(platform)) + return true; + + // if unavailable is present, it's not there. + if (args.IndexOf(kUnavailable) >= 0) + return false; + + var introIndex = args.IndexOf(kIntroduced); + if (introIndex >= 0) + { + var introVersion = GetVersionAfter(args, introIndex); + if (TargetVersionIsGreaterOrEqual(introVersion)) + return false; + } + + var obsoletedIndex = args.IndexOf(kObsoleted); + if (obsoletedIndex >= 0) + { + var obsoletedVersion = GetVersionAfter(args, obsoletedIndex); + if (TargetVersionIsLessOrEqual(obsoletedVersion)) + return false; + } + return true; + } + + bool AvailableShorthand(List args) + { + // args will be: plat ver . x . y , plat ver , ... * + + var startIndex = 0; + while (startIndex < args.Count) + { + if (args[startIndex] == "*") + return false; + var platform = args[startIndex]; + if (PlatformMatches(platform)) + { + var endIndex = args.IndexOf(",", startIndex + 1); + var versionNumber = args.GetRange(startIndex + 1, endIndex - startIndex); + if (TargetVersionIsGreaterOrEqual(versionNumber)) + return true; + } + else + { + startIndex = args.IndexOf(",", startIndex + 1); + } + } + return false; + } + + bool IsShortHand(List args) + { + if (args[1] == ",") + return false; + return args.Last() == "*"; + } + + Version GetVersionAfter(List pieces, int indexAfter) + { + var colonIndex = ColonAfter(pieces, indexAfter); + if (colonIndex < 0) + return new Version(0, 0); + var start = colonIndex + 1; + var end = start + 1; + while (end < pieces.Count && pieces[end] != ",") + end++; + var versionPieces = pieces.GetRange(start, end - start); + return VersionPiecesToVersion(versionPieces); + } + + int ColonAfter(List pieces, int start) + { + for (int i = start + 1; i < pieces.Count; i++) + { + if (pieces[i] == ":") + return i; + if (pieces[i] == ",") + return -1; + } + return -1; + } + + bool TargetVersionIsGreaterOrEqual(List versionPieces) + { + var expectedVersion = VersionPiecesToVersion(versionPieces); + return TargetVersionIsGreaterOrEqual(expectedVersion); + } + + bool TargetVersionIsGreaterOrEqual(Version expectedVersion) + { + var compiledVersionStr = PlatformVersionFromModuleFlags(); + if (String.IsNullOrEmpty(compiledVersionStr)) + return true; // no version, I guess it's good? + var compiledVersion = new Version(compiledVersionStr); + return expectedVersion >= compiledVersion; + } + + bool TargetVersionIsLessOrEqual(List versionPieces) + { + var expectedVersion = VersionPiecesToVersion(versionPieces); + return TargetVersionIsLessOrEqual(expectedVersion); + } + + bool TargetVersionIsLessOrEqual(Version expectedVersion) + { + var compiledVersionStr = PlatformVersionFromModuleFlags(); + if (String.IsNullOrEmpty(compiledVersionStr)) + return true; // no version, I guess it's good? + var compiledVersion = new Version(compiledVersionStr); + return expectedVersion <= compiledVersion; + } + + Version VersionPiecesToVersion(List pieces) + { + var sb = new StringBuilder(); + for (int i = 0; i < pieces.Count; i++) + { + if (pieces[i] == "." && i + 1 < pieces.Count && pieces[i + 1] == "*") + break; + sb.Append(pieces[i]); + } + return new Version(sb.ToString()); + } + + IEnumerable AvailableAttributes(XElement attributes) + { + if (attributes == null) + return Enumerable.Empty(); + return attributes.Descendants(kAttribute).Where(el => el.Attribute(kName).Value == kAvailable); + + } + + List AttrbuteParameters(XElement attribute) + { + return attribute.Descendants(kAttributeParameter).Select(at => + at.Attribute(kValue)?.Value ?? "").ToList(); + } + + bool PlatformMatches(string platform) + { + var currentPlatform = PlatformFromModuleFlags(); + switch (platform) + { + case "*": + case "swift": + return true; + case "iOS": + case "iOSApplicationExtension": + return currentPlatform.StartsWith("ios", StringComparison.Ordinal) && + !currentPlatform.StartsWith("ios-macabi", StringComparison.Ordinal); + case "macOS": + case "macOSApplicationExtension": + return currentPlatform.StartsWith("macos", StringComparison.Ordinal); + case "macCatalyst": + case "macCatalystExtension": + return currentPlatform.StartsWith("ios-macabi", StringComparison.Ordinal); + case "watchOS": + case "watchOSApplicationExtension": + return currentPlatform.StartsWith("watch", StringComparison.Ordinal); + case "tvOS": + case "tvOSApplicationExtension": + return currentPlatform.StartsWith("tv", StringComparison.Ordinal); + default: + return false; + } + } + + string PlatformFromModuleFlags() + { + var flagsValue = TargetFromModuleFlags(); + var os = flagsValue.ClangTargetOS(); + var digitIndex = FirstDigitIndex(os); + if (digitIndex < 0) + return os; + return os.Substring(0, digitIndex); + } + + static int FirstDigitIndex(string s) + { + var index = 0; + foreach (char c in s) + { + if (Char.IsDigit(c)) + return index; + index++; + } + return -1; + } + + string PlatformVersionFromModuleFlags() + { + var flagsValue = TargetFromModuleFlags(); + var os = flagsValue.ClangTargetOS(); + var digitIndex = FirstDigitIndex(os); + if (digitIndex < 0) + return ""; + return os.Substring(digitIndex); + } + + string TargetFromModuleFlags() + { + string flagsValue = null; + if (!moduleFlags.TryGetValue("target", out flagsValue)) + { + return ""; + } + return flagsValue; + } + + static HashSet ModulesThatWeCanSkip = new HashSet() { + "XamGlue", + "RegisterAccess", + "_StringProcessing", + "_Concurrency", + }; + + void LoadReferencedModules() + { + var failures = new StringBuilder(); + foreach (var module in importModules) + { + // XamGlue and RegisterAccess may very well get + // used, but the functions/types exported from these + // should never need to be loaded. + if (ModulesThatWeCanSkip.Contains(module)) + continue; + // if (!moduleLoader.Load (module, typeDatabase)) { + // if (failures.Length > 0) + // failures.Append (", "); + // failures.Append (module); + // } + } + if (failures.Length > 0) + throw new ParseException($"Unable to load the following module(s): {failures.ToString()}"); + } + + void PatchPossibleOperators() + { + foreach (var func in functions) + { + var operatorKind = GetOperatorType(func.Item1); + if (operatorKind != OperatorType.None) + { + func.Item2.Attribute(nameof(operatorKind))?.Remove(); + func.Item2.SetAttributeValue(nameof(operatorKind), operatorKind.ToString()); + } + } + } + + void PatchPossibleBadInheritance() + { + foreach (var inh in unknownInheritance) + { + var type = inh.Attribute(kType).Value; + if (IsLocalClass(type) || IsGlobalClass(type) || IsNSObject(type)) + inh.Attribute(kInheritanceKind).Value = kClass; + else + inh.Attribute(kInheritanceKind).Value = kProtocol; + } + } + + void PatchAssociatedTypeConformance() + { + foreach (var assoc in associatedTypesWithConformance) + { + var conformances = assoc.Element(kConformingProtocols); + var first = conformances.Element(kConformingProtocol); + var className = (string)first.Attribute(kName); + if (IsLocalClass(className) || IsGlobalClass(className)) + { + first.Remove(); + if (conformances.Nodes().Count() == 0) + conformances.Remove(); + assoc.Add(new XElement(kSuperclass, new XAttribute(kName, className))); + } + } + } + + bool IsNSObject(string typeName) + { + return typeName == "ObjectiveC.NSObject"; + } + + bool IsLocalClass(string typeName) + { + return classes.Contains(typeName); + } + + bool IsGlobalClass(string typeName) + { + return typeDatabase.EntityForSwiftName(typeName)?.EntityType == EntityType.Class; + } + + void PatchExtensionSelfArgs() + { + foreach (var ext in extensions) + { + var onType = (string)ext.Attribute(kOnType).Value; + var parts = onType.Split('.'); + if (parts[0] == "XamGlue") + continue; + if (parts.Length > 1 && !typeDatabase.ModuleNames.Contains(parts[0])) + { + moduleLoader.Load(parts[0], typeDatabase); + } + var entity = typeDatabase.EntityForSwiftName(onType); + if (entity != null) + { + PatchExtensionSelfArgs(ext, entity); + } + } + } + + void PatchExtensionSelfArgs(XElement ext, Entity entity) + { + var isStructOrScalar = entity.IsStructOrEnum || entity.EntityType == EntityType.Scalar; + foreach (var func in ext.Descendants(kFunc)) + { + var selfArg = SelfParameter(func); + if (selfArg == null) + continue; + var attr = selfArg.Attribute(kType); + var type = (string)attr.Value; + if (entity.Type.ContainsGenericParameters) + { + type = entity.Type.ToFullyQualifiedNameWithGenerics(); + attr.Value = type; + var generics = entity.Type.Generics.ToXElement(); + if (func.Element(kGenericParameters) != null) + { + var funcGenerics = func.Element(kGenericParameters); + funcGenerics.Remove(); + foreach (var generic in funcGenerics.Elements()) + generics.Add(generic); + } + func.Add(generics); + } + if (isStructOrScalar && !type.StartsWith("inout", StringComparison.Ordinal)) + { + attr.Value = "inout " + type; + } + } + } + + XElement SelfParameter(XElement func) + { + var selfList = WhereIndexZero(func.Descendants(kParameterList)); + if (selfList == null) + return null; + var selfArg = WhereIndexZero(selfList.Descendants(kParameter)); + return selfArg; + } + + static XElement WhereIndexZero(IEnumerable elems) + { + return elems.FirstOrDefault(el => (string)el.Attribute(kIndex).Value == "0"); + } + + void PatchExtensionShortNames() + { + foreach (var ext in extensions) + { + var onType = TypeSpecParser.Parse(ext.Attribute(kOnType).Value); + var replacementType = FullyQualify(onType); + ext.Attribute(kOnType).Value = replacementType.ToString(); + foreach (var func in ext.Descendants(kFunc)) + { + var selfArg = SelfParameter(func); + if (selfArg == null) + continue; + onType = TypeSpecParser.Parse(selfArg.Attribute(kType).Value); + replacementType = FullyQualify(onType); + selfArg.Attribute(kType).Value = replacementType.ToString(); + } + } + } + + TypeSpec FullyQualify(TypeSpec spec) + { + switch (spec.Kind) + { + case TypeSpecKind.Named: + return FullyQualify(spec as NamedTypeSpec); + case TypeSpecKind.Closure: + return FullyQualify(spec as ClosureTypeSpec); + case TypeSpecKind.ProtocolList: + return FullyQualify(spec as ProtocolListTypeSpec); + case TypeSpecKind.Tuple: + return FullyQualify(spec as TupleTypeSpec); + default: + throw new NotImplementedException($"unknown TypeSpec kind {spec.Kind}"); + } + } + + TypeSpec FullyQualify(NamedTypeSpec named) + { + var dirty = false; + var newName = named.Name; + + if (!named.Name.Contains(".")) + { + newName = ReplaceName(named.Name); + dirty = true; + } + + var genParts = new TypeSpec[named.GenericParameters.Count]; + var index = 0; + foreach (var gen in named.GenericParameters) + { + var newGen = FullyQualify(gen); + genParts[index++] = newGen; + if (newGen != gen) + dirty = true; + } + + if (dirty) + { + var newNamed = new NamedTypeSpec(newName, genParts); + newNamed.Attributes.AddRange(named.Attributes); + return newNamed; + } + + return named; + } + + TypeSpec FullyQualify(TupleTypeSpec tuple) + { + var dirty = false; + var parts = new TypeSpec[tuple.Elements.Count]; + var index = 0; + foreach (var spec in tuple.Elements) + { + var newSpec = FullyQualify(spec); + if (newSpec != spec) + dirty = true; + parts[index++] = newSpec; + } + + if (dirty) + { + var newTup = new TupleTypeSpec(parts); + newTup.Attributes.AddRange(tuple.Attributes); + return newTup; + } + + return tuple; + } + + TypeSpec FullyQualify(ProtocolListTypeSpec protolist) + { + var dirty = false; + var parts = new List(); + foreach (var named in protolist.Protocols.Keys) + { + var newNamed = FullyQualify(named); + parts.Add(newNamed as NamedTypeSpec); + if (newNamed != named) + dirty = true; + } + + if (dirty) + { + var newProto = new ProtocolListTypeSpec(parts); + newProto.Attributes.AddRange(protolist.Attributes); + return newProto; + } + + return protolist; + } + + TypeSpec FullyQualify(ClosureTypeSpec clos) + { + var dirty = false; + var args = FullyQualify(clos.Arguments); + if (args != clos.Arguments) + dirty = true; + var returnType = FullyQualify(clos.ReturnType); + if (returnType != clos.ReturnType) + dirty = true; + + if (dirty) + { + var newClosure = new ClosureTypeSpec(args, returnType); + newClosure.Attributes.AddRange(clos.Attributes); + return newClosure; + } + + return clos; + } + + string ReplaceName(string nonQualified) + { + Exceptions.ThrowOnNull(nonQualified, nameof(nonQualified)); + + var localName = ReplaceLocalName(nonQualified); + if (localName != null) + return localName; + var globalName = ReplaceGlobalName(nonQualified); + if (globalName == null) + throw new ParseException($"Unable to find fully qualified name for non qualified type {nonQualified}"); + return globalName; + } + + string ReplaceLocalName(string nonQualified) + { + foreach (var candidate in nominalTypes) + { + var candidateWithoutModule = StripModule(candidate); + if (nonQualified == candidateWithoutModule) + return candidate; + } + return null; + } + + string ReplaceGlobalName(string nonQualified) + { + foreach (var module in importModules) + { + var candidateName = $"{module}.{nonQualified}"; + var entity = typeDatabase.TryGetEntityForSwiftName(candidateName); + if (entity != null) + return candidateName; + } + if (nonQualified == "EveryProtocol") + return "XamGlue.EveryProtocol"; + return null; + } + + string StripModule(string fullyQualifiedName) + { + if (fullyQualifiedName.StartsWith(moduleName, StringComparison.Ordinal)) + // don't forget the '.' + return fullyQualifiedName.Substring(moduleName.Length + 1); + return fullyQualifiedName; + } + + static bool AttributesContains(AttributesContext context, string key) + { + if (context == null) + return false; + foreach (var attr in context.attribute()) + { + if (attr.attribute_name().GetText() == key) + return true; + } + return false; + } + + static bool AttributesContainsAny(AttributesContext context, string[] keys) + { + foreach (var attr in context.attribute()) + { + var attrName = attr.attribute_name().GetText(); + foreach (var key in keys) + { + if (key == attrName) + return true; + } + } + return false; + } + + string EscapePossibleClosureType(string type) + { + var typeSpec = TypeSpecParser.Parse(type); + return typeSpec is ClosureTypeSpec ? "@escaping[] " + type : type; + } + + static Dictionary accessMap = new Dictionary() { + { kPublic, kPublicCap }, + { kPrivate, kPrivateCap }, + { kOpen, kOpenCap }, + { kInternal, kInternalCap }, + }; + + string AccessibilityFromModifiers(Declaration_modifiersContext context) + { + // If there is no context, we need to search for the appropriate context + // Swift has a number of "interesting" rules for implicitly defined accessibility + // If the parent element is a protocol, it's public + // If the parent is public, internal, or open then it's open + // If the parent is private or fileprivate, then it's private + + // Note that I don't make any distinction between private and fileprivate + // From our point of view, they're the same: they're things that we don't + // have access to and don't care about in writing a reflector of the public + // API. + if (context == null) + { + var parentElem = NominalParentAfter(-1); + if (parentElem == null) + return kInternalCap; + if (parentElem.Attribute(kKind).Value == kProtocol) + return kPublicCap; + switch (parentElem.Attribute(kAccessibility).Value) + { + case kPublic: + case kInternal: + case kOpen: + return kInternalCap; + case kPrivate: + case kFilePrivate: + return kPrivateCap; + } + } + foreach (var modifer in context.declaration_modifier()) + { + string result; + if (accessMap.TryGetValue(modifer.GetText(), out result)) + return result; + } + return kInternalCap; + } + + static bool HasAsync(Getter_keyword_clauseContext context) + { + return context == null ? false : context.async_clause() != null; + } + + static bool ModifiersContains(Declaration_modifiersContext context, string match) + { + if (context == null) + return false; + foreach (var modifier in context.declaration_modifier()) + { + var text = modifier.GetText(); + if (text == match) + return true; + } + return false; + } + + public override void EnterDeclaration_modifier([NotNull] Declaration_modifierContext context) + { + var modifier = context.GetText(); + + } + + static bool ModifiersContainsAny(Declaration_modifiersContext context, string[] matches) + { + if (context == null) + return false; + foreach (var modifier in context.declaration_modifier()) + { + var text = modifier.GetText(); + foreach (var match in matches) + if (text == match) + return true; + } + return false; + } + + static bool IsStaticOrClass(Declaration_modifiersContext context) + { + return ModifiersContainsAny(context, new string[] { kStatic, kClass }); + } + + static bool IsFinal(Declaration_modifiersContext context) + { + return ModifiersContains(context, kFinal); + } + + void AddStructToCurrentElement(XElement elem) + { + var parentElement = GetOrCreateParentElement(kInnerStructs); + parentElement.Add(elem); + RegisterNominal(elem); + } + + void AddEnumToCurrentElement(XElement elem) + { + var parentElement = GetOrCreateParentElement(kInnerEnums); + parentElement.Add(elem); + RegisterNominal(elem); + } + + void AddClassToCurrentElement(XElement elem) + { + var parentElement = GetOrCreateParentElement(kInnerClasses); + parentElement.Add(elem); + RegisterNominal(elem); + } + + void RegisterNominal(XElement elem) + { + var isClass = elem.Attribute(kKind).Value == kClass; + var builder = new StringBuilder(); + while (elem != null) + { + if (builder.Length > 0) + builder.Insert(0, '.'); + var namePart = elem.Attribute(kName)?.Value ?? moduleName; + builder.Insert(0, namePart); + elem = elem.Parent; + } + var typeName = builder.ToString(); + nominalTypes.Add(typeName); + if (isClass) + classes.Add(typeName); + } + + void AddAssociatedTypeToCurrentElement(XElement elem) + { + var parentElement = GetOrCreateParentElement(kAssociatedTypes); + parentElement.Add(elem); + } + + XElement GetOrCreateParentElement(string parentContainerName) + { + var current = currentElement.Peek(); + if (current.Name == kModule) + { + return current; + } + var container = GetOrCreate(current, parentContainerName); + return container; + } + + OperatorType GetOperatorType(Function_declarationContext context) + { + var localOp = LocalOperatorType(context); + return localOp == OperatorType.None ? GlobalOperatorType(context.function_name().GetText()) + : localOp; + } + + OperatorType LocalOperatorType(Function_declarationContext context) + { + var head = context.function_head(); + + + // if the function declaration contains prefix + if (ModifiersContains(head.declaration_modifiers(), kLittlePrefix)) + { + return OperatorType.Prefix; + } + else if (ModifiersContains(head.declaration_modifiers(), kLittlePostfix)) + { + return OperatorType.Postfix; + } + + var opName = context.function_name().GetText(); + + foreach (var op in operators) + { + var targetName = op.Attribute(kName).Value; + var targetKind = op.Attribute(kOperatorKind).Value; + if (opName == targetName && targetKind == kInfix) + return OperatorType.Infix; + } + return OperatorType.None; + } + + OperatorType GlobalOperatorType(string name) + { + foreach (var op in typeDatabase.FindOperators(importModules)) + { + if (op.Name == name) + return op.OperatorType; + } + return OperatorType.None; + } + + void InterpretCommentText(string commentText) + { + if (commentText.StartsWith(kSwiftInterfaceFormatVersion)) + { + AssignSwiftInterfaceFormat(commentText.Substring(kSwiftInterfaceFormatVersion.Length)); + } + else if (commentText.StartsWith(kSwiftCompilerVersion)) + { + AssignSwiftCompilerVersion(commentText.Substring(kSwiftCompilerVersion.Length)); + } + else if (commentText.StartsWith(kSwiftModuleFlags)) + { + ExtractModuleFlags(commentText.Substring(kSwiftModuleFlags.Length)); + moduleFlags.TryGetValue(kModuleName, out moduleName); + } + } + + void AssignSwiftInterfaceFormat(string formatVersion) + { + // when we get here, we should see something like + // [white-space]*VERSION[white-space] + formatVersion = formatVersion.Trim(); + if (!Version.TryParse(formatVersion, out interfaceVersion)) + throw new ArgumentOutOfRangeException(nameof(formatVersion), $"Expected a version string in the interface format but got {formatVersion}"); + } + + void AssignSwiftCompilerVersion(string compilerVersion) + { + // when we get here, we should see something like: + // [white-space]*Apple? Swift version VERSION (swiftlang-VERSION clang-VERSION) + var parts = compilerVersion.Trim().Split(' ', '\t'); // don't know if tab is a thing + // expect in the array: + // 0: Apple + // 1: Swift + // 2: verion + // 3: VERSION + + var swiftIndex = Array.IndexOf(parts, "Swift"); + if (swiftIndex < 0) + throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected 'Swift' in the version string, but got {compilerVersion}"); + if (parts[swiftIndex + 1] != "version") + throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected a compiler version string but got {compilerVersion}"); + var version = parts[swiftIndex + 2]; + if (version.EndsWith("-dev", StringComparison.Ordinal)) + version = version.Substring(0, version.Length - "-dev".Length); + if (!Version.TryParse(version, out this.compilerVersion)) + throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected a compiler version number but got {compilerVersion}"); + } + + void ExtractModuleFlags(string commentText) + { + var args = commentText.Trim().Split(' ', '\t'); + int index = 0; + while (index < args.Length) + { + var arg = args[index++]; + if (arg[0] != '-') + throw new ArgumentOutOfRangeException(nameof(CommentContext), + $"Expected argument {index - 1} to start with a '-' but got {arg} (args: {commentText}"); + var key = arg.Substring(1); + var val = ""; + if (index < args.Length && args[index][0] != '-') + { + val = args[index++]; + } + moduleFlags[key] = val; + } + } + + void SetLanguageVersion(XElement module) + { + if (compilerVersion != null) + { + module.Add(new XAttribute("swiftVersion", compilerVersion.ToString())); + } + } + + static string XmlBool(bool b) + { + return b ? "true" : "false"; + } + + static string ToAccess(Access_level_modifierContext access) + { + var accessstr = access != null ? access.GetText() : kInternalCap; + switch (accessstr) + { + case kPublic: + return kPublicCap; + case kPrivate: + return kPrivateCap; + case kOpen: + return kOpenCap; + case kInternal: + case kInternalCap: + return kInternalCap; + default: + return kUnknown; + } + } + + + static XElement GetOrCreate(XElement elem, string key) + { + var members = elem.Element(key); + if (members == null) + { + members = new XElement(key); + elem.Add(members); + } + return members; + } + + static string[] ctorDtorNames = new string[] { + kDotCtor, kDotDtor + }; + + static bool IsCtorDtor(string name) + { + return ctorDtorNames.Contains(name); + } + + public static string UnTick(string str) + { + // a back-ticked string will start and end with ` + // the swift grammar guarantees this. + // Identifier : + // Identifier_head Identifier_characters? + // | OpBackTick Identifier_head Identifier_characters? OpBackTick + // | ImplicitParameterName + // There will be no starting and ending whitespace. + // + // There are some edge cases that we can take advantage of: + // 1. If it starts with `, it *has* to end with back tick, so we don't need to check + // 2. `` will never exist, so the minimum length *has* to be 3 + // In generalized string manipulation, we couldn't make these assumptions, + // but in this case the grammar works for us. + // first weed out the easy cases: + // null, too short, does start and end with back tick + // then just substring it + if (str is null || str.Length < 3 || str[0] != '`') + return str; + return str.Substring(1, str.Length - 2); + } + + + public List ImportModules { get { return importModules; } } + } } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs b/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs index 79701c751a34..3f3fbbdd1d23 100644 --- a/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs +++ b/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs @@ -8,113 +8,117 @@ using static SwiftInterfaceParser; using System.Collections.Generic; -namespace SwiftReflector.SwiftInterfaceReflector { - public class SyntaxDesugaringParser : SwiftInterfaceBaseListener { - TokenStreamRewriter rewriter; - SwiftInterfaceParser parser; - ICharStream charStream; - SwiftInterfaceLexer lexer; +namespace SwiftReflector.SwiftInterfaceReflector +{ + public class SyntaxDesugaringParser : SwiftInterfaceBaseListener + { + TokenStreamRewriter rewriter; + SwiftInterfaceParser parser; + ICharStream charStream; + SwiftInterfaceLexer lexer; - public SyntaxDesugaringParser (string inFile) - { - charStream = CharStreams.fromPath (inFile); - lexer = new SwiftInterfaceLexer (charStream); - var tokenStream = new CommonTokenStream (lexer); + public SyntaxDesugaringParser(string inFile) + { + charStream = CharStreams.fromPath(inFile); + lexer = new SwiftInterfaceLexer(charStream); + var tokenStream = new CommonTokenStream(lexer); - rewriter = new TokenStreamRewriter (tokenStream); - this.parser = new SwiftInterfaceParser (tokenStream); - } + rewriter = new TokenStreamRewriter(tokenStream); + this.parser = new SwiftInterfaceParser(tokenStream); + } - public string Desugar () - { - var walker = new ParseTreeWalker (); - walker.Walk (this, parser.swiftinterface ()); - return rewriter.GetText (); - } + public string Desugar() + { + var walker = new ParseTreeWalker(); + walker.Walk(this, parser.swiftinterface()); + return rewriter.GetText(); + } - internal static string TypeText (ICharStream input, ParserRuleContext ty) - { - if (ty is null) - return null; - var start = ty.Start.StartIndex; - var end = ty.Stop.StopIndex; - var interval = new Interval (start, end); - return input.GetText (interval); - } + internal static string TypeText(ICharStream input, ParserRuleContext ty) + { + if (ty is null) + return null; + var start = ty.Start.StartIndex; + var end = ty.Stop.StopIndex; + var interval = new Interval(start, end); + return input.GetText(interval); + } - string TypeText (ParserRuleContext ty) - { - return TypeText (charStream, ty); - } + string TypeText(ParserRuleContext ty) + { + return TypeText(charStream, ty); + } - public override void ExitOptional_type ([NotNull] Optional_typeContext context) - { - var innerType = TypeText (context.type ()); - var replacementType = $"Swift.Optional<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace (startToken, endToken, replacementType); - } + public override void ExitOptional_type([NotNull] Optional_typeContext context) + { + var innerType = TypeText(context.type()); + var replacementType = $"Swift.Optional<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace(startToken, endToken, replacementType); + } - public override void ExitUnwrapped_optional_type ([NotNull] Unwrapped_optional_typeContext context) - { - var innerType = TypeText (context.type ()); - var replacementType = $"Swift.Optional<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace (startToken, endToken, replacementType); - } + public override void ExitUnwrapped_optional_type([NotNull] Unwrapped_optional_typeContext context) + { + var innerType = TypeText(context.type()); + var replacementType = $"Swift.Optional<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace(startToken, endToken, replacementType); + } - public override void ExitArray_type ([NotNull] Array_typeContext context) - { - var innerType = TypeText (context.type ()); - var replacementType = $"Swift.Array<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace (startToken, endToken, replacementType); - } + public override void ExitArray_type([NotNull] Array_typeContext context) + { + var innerType = TypeText(context.type()); + var replacementType = $"Swift.Array<{innerType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace(startToken, endToken, replacementType); + } - public override void ExitDictionary_type ([NotNull] Dictionary_typeContext context) - { - var keyType = TypeText (context.children [1] as ParserRuleContext); - var valueType = TypeText (context.children [3] as ParserRuleContext); - var replacementType = $"Swift.Dictionary<{keyType},{valueType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace (startToken, endToken, replacementType); - } + public override void ExitDictionary_type([NotNull] Dictionary_typeContext context) + { + var keyType = TypeText(context.children[1] as ParserRuleContext); + var valueType = TypeText(context.children[3] as ParserRuleContext); + var replacementType = $"Swift.Dictionary<{keyType},{valueType}>"; + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace(startToken, endToken, replacementType); + } - static Dictionary typeChanges = new Dictionary () { - { "Swift.Void", "()" }, - { "CoreFoundation.CGAffineTransform", "CoreGraphics.CGAffineTransform" }, - { "CoreFoundation.CGColorSapceModel", "CoreGraphics.CGColorSapceModel" }, - { "CoreFoundation.CGPoint", "CoreGraphics.CGPoint" }, - { "CoreFoundation.CGRect", "CoreGraphics.CGRect" }, - { "CoreFoundation.CGSize", "CoreGraphics.CGSize" }, - { "CoreFoundation.CGVector", "CoreGraphics.CGVector" }, - { "CoreFoundation.CGFloat", "CoreGraphics.CGFloat" }, - }; + static Dictionary typeChanges = new Dictionary() { + { "Swift.Void", "()" }, + { "CoreFoundation.CGAffineTransform", "CoreGraphics.CGAffineTransform" }, + { "CoreFoundation.CGColorSapceModel", "CoreGraphics.CGColorSapceModel" }, + { "CoreFoundation.CGPoint", "CoreGraphics.CGPoint" }, + { "CoreFoundation.CGRect", "CoreGraphics.CGRect" }, + { "CoreFoundation.CGSize", "CoreGraphics.CGSize" }, + { "CoreFoundation.CGVector", "CoreGraphics.CGVector" }, + { "CoreFoundation.CGFloat", "CoreGraphics.CGFloat" }, + }; - public override void ExitIdentifier_type ([NotNull] Identifier_typeContext context) - { - if (typeChanges.TryGetValue (context.GetText (), out var substitution)) { - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace (startToken, endToken, substitution); - } - } + public override void ExitIdentifier_type([NotNull] Identifier_typeContext context) + { + if (typeChanges.TryGetValue(context.GetText(), out var substitution)) + { + var startToken = context.Start; + var endToken = context.Stop; + rewriter.Replace(startToken, endToken, substitution); + } + } - public override void ExitFunction_type_argument([NotNull] Function_type_argumentContext context) - { - if (context.argument_label () is Argument_labelContext argContext && argContext.ChildCount == 2) { - // function type argument of the form public_label private_label - // change to public_label - // in a .swiftinterface context, the private label means nothing to us - var startToken = argContext.Start; - var endToken = argContext.Stop; - rewriter.Replace (startToken, endToken, argContext.children [0].GetText ()); - } - } - } + public override void ExitFunction_type_argument([NotNull] Function_type_argumentContext context) + { + if (context.argument_label() is Argument_labelContext argContext && argContext.ChildCount == 2) + { + // function type argument of the form public_label private_label + // change to public_label + // in a .swiftinterface context, the private label means nothing to us + var startToken = argContext.Start; + var endToken = argContext.Stop; + rewriter.Replace(startToken, endToken, argContext.children[0].GetText()); + } + } + } } diff --git a/src/SwiftReflector/SwiftName.cs b/src/SwiftReflector/SwiftName.cs index 6ab63e6fc0fb..9727367110ad 100644 --- a/src/SwiftReflector/SwiftName.cs +++ b/src/SwiftReflector/SwiftName.cs @@ -3,42 +3,44 @@ using System; -namespace SwiftReflector { - public class SwiftName { - public SwiftName (string name, bool isPunyCode) - { - if (name == null) - throw new ArgumentNullException ("name"); - PunyName = name; - Name = isPunyCode ? name.DePunyCode () : name; - } - - public string Name { get; private set; } - public string PunyName { get; private set; } - public bool HasPunyCode { get { return Name != PunyName; } } - - public override string ToString () - { - return HasPunyCode ? String.Format ("{0} ({1})", Name, PunyName) : Name; - } - - static SwiftName emptyName = new SwiftName ("", false); - public static SwiftName Empty { get { return emptyName; } } - - public override bool Equals (object obj) - { - var other = obj as SwiftName; - if (other == null) - return false; - return (PunyName == other.PunyName) && - (HasPunyCode ? Name == other.Name : true); - } - - public override int GetHashCode () - { - return PunyName.GetHashCode () + - (HasPunyCode ? Name.GetHashCode () : 0); - } - } +namespace SwiftReflector +{ + public class SwiftName + { + public SwiftName(string name, bool isPunyCode) + { + if (name == null) + throw new ArgumentNullException("name"); + PunyName = name; + Name = isPunyCode ? name.DePunyCode() : name; + } + + public string Name { get; private set; } + public string PunyName { get; private set; } + public bool HasPunyCode { get { return Name != PunyName; } } + + public override string ToString() + { + return HasPunyCode ? String.Format("{0} ({1})", Name, PunyName) : Name; + } + + static SwiftName emptyName = new SwiftName("", false); + public static SwiftName Empty { get { return emptyName; } } + + public override bool Equals(object obj) + { + var other = obj as SwiftName; + if (other == null) + return false; + return (PunyName == other.PunyName) && + (HasPunyCode ? Name == other.Name : true); + } + + public override int GetHashCode() + { + return PunyName.GetHashCode() + + (HasPunyCode ? Name.GetHashCode() : 0); + } + } } diff --git a/src/SwiftReflector/SwiftType.cs b/src/SwiftReflector/SwiftType.cs index b10eb59d9787..ac253827f0a5 100644 --- a/src/SwiftReflector/SwiftType.cs +++ b/src/SwiftReflector/SwiftType.cs @@ -7,1112 +7,1204 @@ using SwiftReflector.Demangling; using SwiftRuntimeLibrary; -namespace SwiftReflector { - public class SwiftType { - protected SwiftType (CoreCompoundType type, bool isReference, SwiftName name = null) - { - Type = type; - IsReference = isReference; - Name = name; - Attributes = new List (); - IsVariadic = false; - } - - public CoreCompoundType Type { get; private set; } - public SwiftName Name { get; private set; } - public bool IsReference { get; private set; } - public List Attributes { get; private set; } - public bool IsVariadic { get; set; } - - - public SwiftType ReferenceCloneOf () - { - if (IsReference) - return this; - var ty = MemberwiseClone () as SwiftType; - ty.IsReference = true; - return ty; - } - - public SwiftType NonReferenceCloneOf () - { - if (!IsReference) - return this; - var ty = MemberwiseClone () as SwiftType; - ty.IsReference = false; - return ty; - } - - public SwiftType RenamedCloneOf (SwiftName newName) - { - var ty = MemberwiseClone () as SwiftType; - ty.Name = newName; - return ty; - } - - - public bool IsConstructor { get { return this is SwiftConstructorType; } } - - public bool IsOptionalConstructor { - get { - // a SwiftType is an optional ctor if: - // 1 it's a SwiftConstructorType - // 2 its return type is SwiftBoundGenericType - // 3 its return type has a base of Swift.Optional - // 4 its return type has exactly one bound type to the type of - // the metatype of this class - var ctor = this as SwiftConstructorType; - if (ctor == null) - return false; - var returnType = ctor.ReturnType as SwiftBoundGenericType; - if (returnType == null) - return false; - if (returnType.BoundTypes.Count != 1) - return false; - var baseType = returnType.BaseType as SwiftClassType; - if (baseType == null) - return false; - var boundType = returnType.BoundTypes [0] as SwiftClassType; - if (boundType == null) - return false; - var uncurriedParameter = ctor.UncurriedParameter as SwiftMetaClassType; - if (uncurriedParameter == null) - return false; - return baseType.ClassName.ToFullyQualifiedName () == "Swift.Optional" && - boundType.ClassName.ToFullyQualifiedName (true) == uncurriedParameter.Class.ClassName.ToFullyQualifiedName (true); - } - } - - public bool IsEmptyTuple { - get { - var tuple = this as SwiftTupleType; - return tuple == null ? false : tuple.IsEmpty; - } - } - public virtual bool IsClass { get { return false; } } - public virtual bool IsStruct { get { return false; } } - public virtual bool IsEnum { get { return false; } } - public virtual bool IsProtocol { get { return false; } } - - public bool HasAttribute (SwiftTypeAttribute attribute) - { - return Attributes.Any (attr => attr == attribute); - } - - [Obsolete ("this is not supported in Swift 5")] - public bool HasObjCAttribute => HasAttribute (SwiftTypeAttribute.ObjC); - - public override int GetHashCode () - { - return Type.GetHashCode () + - (Name != null ? Name.GetHashCode () : 0); - } - - public override bool Equals (object obj) - { - var type = obj as SwiftType; - if (type == null) - return false; - if (type.Type != Type) - return false; - if (type.IsReference != IsReference) - return false; - if (type.IsVariadic != IsVariadic) - return false; - if (type.GetType () != this.GetType ()) - return false; - // shouldn't do Name equality except in functions - return LLEquals (type); - } - - public virtual bool EqualsReferenceInvaraint (SwiftType type) - { - var a = ProjectAsNonReference (this); - var b = ProjectAsNonReference (type); - - if (b.Type != a.Type) - return false; - if (b.GetType () != a.GetType ()) - return false; - // shouldn't do Name equality except in functions - return a.LLEquals (b); - } - - static SwiftType ProjectAsNonReference (SwiftType a) - { - if (a.IsReference) { - return a.NonReferenceCloneOf (); - } - var bgt = a as SwiftBoundGenericType; - if (bgt != null && bgt.BoundTypes.Count == 1) { - var baseType = bgt.BaseType as SwiftClassType; - if (baseType != null) { - string name = baseType.ClassName.ToFullyQualifiedName (true); - if (name == "Swift.UnsafePointer" || name == "Swift.UnsafeMutablePointer") - return bgt.BoundTypes [0]; - } - } - return a; - } - - protected virtual bool LLEquals (SwiftType other) - { - return true; - } - - - public static bool IsStructScalar (SwiftType st) - { - if (st == null) - return false; - if (st is SwiftBuiltInType) - return true; - var ct = st as SwiftClassType; - if (ct == null) - return false; - return IsStructScalar (ct.ClassName.ToFullyQualifiedName ()); - } - - public static bool IsStructScalar (string fullyQualifiedName) - { - switch (fullyQualifiedName) { - case "Swift.Int64": - case "Swift.UInt64": - case "Swift.Int32": - case "Swift.UInt32": - case "Swift.Int16": - case "Swift.UInt16": - case "Swift.Int8": - case "Swift.UInt8": - case "Swift.Char": - case "CoreGraphics.CGFloat": - case "Swift.UnsafeRawPointer": - case "Swift.UnsafeMutableRawPointer": - case "Swift.OpaquePointer": - return true; - default: - return false; - } - } - } - - public class SwiftModuleNameType : SwiftType { - public SwiftModuleNameType (SwiftName name, bool isReference) - : base (CoreCompoundType.ModuleName, isReference, name) - { - } - public override string ToString() - { - return Name != null ? Name.Name : "(unknown module)"; - } - } - - public abstract class SwiftBaseFunctionType : SwiftType { - public SwiftBaseFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base (CoreCompoundType.Function, isReference, name) - { - Parameters = Exceptions.ThrowOnNull (parms, nameof(parms)); - ReturnType = Exceptions.ThrowOnNull (ret, nameof(ret)); - GenericArguments = new List (); - CanThrow = canThrow; - ExtensionOn = extensionOn; - } - - public bool ContainsGenericParameters { - get { - return GenericArguments.Count () > 0; - } - } - public SwiftType ExtensionOn { get; set; } - public abstract MemberType MemberType { get; } - public SwiftType Parameters { get; private set; } - public SwiftType ReturnType { get; private set; } - public List GenericArguments { get; private set; } - public bool CanThrow { get; private set; } - public bool IsExtension { get { return ExtensionOn != null; } } - public virtual bool IsThunk => false; - public SwiftBaseFunctionType Thunk { get; set; } - - public abstract SwiftBaseFunctionType AsThunk (); - - // for short-lived discretionary storage of information - public string DiscretionaryString { get; set; } - - public IEnumerable EachParameter { - get { - for (int i = 0; i < ParameterCount; i++) { - yield return GetParameter (i); - } - } - } - - public int GenericParameterCount { - get { return EachParameter.Sum (st => st is SwiftGenericArgReferenceType ? 1 : 0); } - } - - - public bool IsVoid { get { return ReturnType.Type == CoreCompoundType.Tuple && ((SwiftTupleType)ReturnType).IsEmpty; } } - - protected override bool LLEquals (SwiftType other) - { - var fn = other as SwiftBaseFunctionType; - if (fn == null) - return false; - if (Name != null) - Name.Equals (fn.Name); - return MemberType == fn.MemberType && Parameters.Equals (fn.Parameters) - && ReturnType.Equals (fn.ReturnType); - } - - public int ParameterCount { - get { - var tt = Parameters as SwiftTupleType; - if (tt == null) { - return 1; - } else { - return tt.Contents.Count; - } - } - } - - public SwiftType GetParameter (int index) - { - var tt = Parameters as SwiftTupleType; - if (tt == null) { - if (index == 0) - return Parameters; - else - throw new ArgumentOutOfRangeException (nameof(index)); - } else { - if (index < 0 || index >= tt.Contents.Count) - throw new ArgumentOutOfRangeException (nameof (index)); - return tt.Contents [index]; - } - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return $"{name}{Parameters.ToString ()}->{ReturnType.ToString ()}"; - } - } - - public class SwiftCFunctionType : SwiftBaseFunctionType { - public SwiftCFunctionType (SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) - : base (parms, ret, isReference, false, name, null) - { - } - - public override MemberType MemberType { - get { - return MemberType.CFunction; - } - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftCFunctionTypeThunk (Parameters, ReturnType, IsReference, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftCFunctionTypeThunk : SwiftCFunctionType { - public SwiftCFunctionTypeThunk (SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) - : base (parms, ret, isReference, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftAddressorType : SwiftBaseFunctionType { - public SwiftAddressorType (AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) - : base (SwiftTupleType.Empty, ret, isReference, false, name, null) - { - AddressorType = addressor; - } - public AddressorType AddressorType { get; private set; } - public override MemberType MemberType { - get { - return MemberType.Addressor; - } - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftAddressorThunkType (AddressorType, ReturnType, IsReference, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftAddressorThunkType : SwiftAddressorType { - public SwiftAddressorThunkType (AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) - : base (addressor, ret, isReference, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftInitializerType : SwiftBaseFunctionType { - public SwiftInitializerType (InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) - : base (SwiftTupleType.Empty, ret, false, false, name, null) - { - Owner = Exceptions.ThrowOnNull (owner, nameof (owner)); - InitializerType = initType; - } - - public InitializerType InitializerType { get; private set; } - public SwiftClassType Owner { get; private set; } - public override MemberType MemberType { - get { - return MemberType.Initializer; - } - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftInitializerThunkType (InitializerType, ReturnType, Owner, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftInitializerThunkType : SwiftInitializerType { - public SwiftInitializerThunkType (InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) - : base (initType, ret, owner, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftFunctionType : SwiftBaseFunctionType { - public SwiftFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) - : base (parms, ret, isReference, canThrow, name, extensionOn) - { - IsEscaping = isEscaping; - } - - public override MemberType MemberType { get { return MemberType.Function; } } - public bool IsEscaping { get; private set; } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftFunctionThunkType (Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn, IsEscaping); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftFunctionThunkType : SwiftFunctionType { - public SwiftFunctionThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) - : base (parms, ret, isReference, canThrow, name, extensionOn, isEscaping) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftCFunctionPointerType : SwiftFunctionType { - public SwiftCFunctionPointerType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) - : base (parms, ret, isReference, canThrow, name, null) - { - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftCFunctionPointerThunkType (Parameters, ReturnType, IsReference, CanThrow, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftCFunctionPointerThunkType : SwiftCFunctionPointerType { - public SwiftCFunctionPointerThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) - : base (parms, ret, isReference, canThrow, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftStaticFunctionType : SwiftFunctionType { - public SwiftStaticFunctionType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) - : base (parms, ret, isReference, canThrow, name, extensionOn) - { - OfClass = ofClass; - } - - public SwiftClassType OfClass { get; private set; } - - public override SwiftBaseFunctionType AsThunk () - { - var func = new SwiftStaticFunctionThunkType (Parameters, ReturnType, IsReference, CanThrow, OfClass, Name, ExtensionOn); - func.DiscretionaryString = DiscretionaryString; - return func; - } - } - - public class SwiftStaticFunctionThunkType : SwiftStaticFunctionType { - public SwiftStaticFunctionThunkType (SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) - : base (parms, ret, isReference, canThrow, ofClass, name, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - - public class SwiftClassConstructorType : SwiftFunctionType { - public SwiftClassConstructorType (SwiftMetaClassType meta, bool isReference) - : base (SwiftTupleType.Empty, Exceptions.ThrowOnNull (meta, "meta"), isReference, false, Decomposer.kSwiftClassConstructorName) - { - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftClassConstructorThunkType (ReturnType as SwiftMetaClassType, IsReference); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftClassConstructorThunkType : SwiftClassConstructorType { - public SwiftClassConstructorThunkType (SwiftMetaClassType meta, bool isReference) - : base (meta, isReference) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftUncurriedFunctionType : SwiftBaseFunctionType { - public SwiftUncurriedFunctionType (SwiftType unCurriedParameter, - SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : this (MemberType.UncurriedFunction, unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) - { - } - - protected SwiftUncurriedFunctionType (MemberType memberType, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base (parms, ret, isReference, canThrow, name, extensionOn) - { - // oddly enough, this is allowed to be null - UncurriedParameter = unCurriedParameter; - this.memberType = memberType; - } - MemberType memberType; - public override MemberType MemberType { get { return memberType; } } - public SwiftType UncurriedParameter { get; private set; } - - protected override bool LLEquals (SwiftType other) - { - var ucf = other as SwiftUncurriedFunctionType; - return ucf != null && ucf.UncurriedParameter.Equals (UncurriedParameter) && base.LLEquals(other); - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftUncurriedFunctionThunkType (UncurriedParameter, Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftUncurriedFunctionThunkType : SwiftUncurriedFunctionType - { - public SwiftUncurriedFunctionThunkType (SwiftType unCurriedParameter, - SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base (unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - - public class SwiftConstructorType : SwiftUncurriedFunctionType { - public SwiftConstructorType (bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) - : base (isAllocating ? MemberType.Allocator : MemberType.Constructor, - unCurriedParameter, parms, ret, isReference, canThrow, isAllocating ? Decomposer.kSwiftAllocatingConstructorName : - Decomposer.kSwiftNonAllocatingConstructorName, extensionOn) - { - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftConstructorThunkType (MemberType == MemberType.Allocator, UncurriedParameter, - Parameters, ReturnType, IsReference, CanThrow, ExtensionOn); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftConstructorThunkType : SwiftConstructorType { - public SwiftConstructorThunkType (bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) - : base (isAllocating, unCurriedParameter, parms, ret, isReference, canThrow, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftDestructorType : SwiftBaseFunctionType { - public SwiftDestructorType (bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) - : base (classType, classType, isReference, canThrow, - isDeallocating ? Decomposer.kSwiftDeallocatingDestructorName : Decomposer.kSwiftNonDeallocatingDestructorName, null) - { - memberType = isDeallocating ? MemberType.Deallocator : MemberType.Destructor; - } - MemberType memberType; - public override MemberType MemberType { get { return memberType; } } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftDestructorThunkType (Name == Decomposer.kSwiftDeallocatingDestructorName, ReturnType as SwiftClassType, IsReference, CanThrow); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftDestructorThunkType : SwiftDestructorType { - public SwiftDestructorThunkType (bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) - : base (isDeallocating, classType, isReference, canThrow) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftPropertyType : SwiftUncurriedFunctionType { - public SwiftPropertyType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base (unCurriedParameter, - (propType == PropertyType.Setter || propType == PropertyType.Materializer) ? ofType : SwiftTupleType.Empty, - (propType == PropertyType.Getter) ? ofType : SwiftTupleType.Empty, - isReference, false, propName, extensionOn) - { - PropertyType = propType; - PrivateName = privateName; - OfType = Exceptions.ThrowOnNull (ofType, "ofType"); - IsSubscript = false; - IsStatic = isStatic; - } - public SwiftPropertyType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base (unCurriedParameter, accessor.Parameters, accessor.ReturnType, isReference, false, propName, extensionOn) - { - PropertyType = propType; - PrivateName = privateName; - OfType = accessor; - IsSubscript = true; - IsStatic = isStatic; - } - - public PropertyType PropertyType { get; private set; } - public SwiftName PrivateName { get; private set; } - public SwiftType OfType { get; private set; } - public bool IsStatic { get; private set; } - - public bool IsSubscript { get; private set; } - public bool IsPublic { get { return PrivateName == null; } } - public bool IsPrivate { get { return PrivateName != null; } } - public bool IsGlobal { get { return UncurriedParameter == null; }} - - public SwiftPropertyType RecastAsStatic() - { - if (IsStatic) - return this; - SwiftPropertyType newProp = null; - if (OfType is SwiftFunctionType) { - if (this is SwiftPropertyThunkType) { - newProp = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, - true, IsReference); - - } else { - newProp = new SwiftPropertyType (UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, - true, IsReference); - } - } else { - if (this is SwiftPropertyThunkType) { - newProp = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); - - } else { - newProp = new SwiftPropertyType (UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); - } - } - newProp.DiscretionaryString = DiscretionaryString; - newProp.ExtensionOn = this.ExtensionOn; - return newProp; - } - - public override SwiftBaseFunctionType AsThunk () - { - if (IsSubscript) { - var pt = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, - PrivateName, OfType as SwiftFunctionType, IsStatic, IsReference, ExtensionOn); - pt.DiscretionaryString = DiscretionaryString; - return pt; - } else { - var pt = new SwiftPropertyThunkType (UncurriedParameter, PropertyType, Name, - PrivateName, OfType, IsStatic, IsReference, ExtensionOn); - pt.DiscretionaryString = DiscretionaryString; - return pt; - } - } - } - - public class SwiftPropertyThunkType : SwiftPropertyType { - public SwiftPropertyThunkType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base (unCurriedParameter, propType, propName, privateName, ofType, isStatic, isReference, extensionOn) - { - } - - public SwiftPropertyThunkType (SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base (unCurriedParameter, propType, propName, privateName, accessor, isStatic, isReference, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftExplicitClosureType : SwiftBaseFunctionType { - public SwiftExplicitClosureType (bool isReference) - : base (SwiftTupleType.Empty, SwiftTupleType.Empty, isReference, false, null) - { - } - - public override MemberType MemberType { - get { - return MemberType.ExplicitClosure; - } - } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftExplicitClosureThunkType (IsReference); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftExplicitClosureThunkType : SwiftExplicitClosureType { - public SwiftExplicitClosureThunkType (bool isReference) - : base (isReference) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftWitnessTableType : SwiftUncurriedFunctionType { - public SwiftWitnessTableType (WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) - : base ((SwiftType)owningType ?? SwiftTupleType.Empty, SwiftTupleType.Empty, SwiftTupleType.Empty, false, false, null) - { - WitnessType = witnessType; - if (WitnessType == WitnessType.Protocol && protocolType == null) - throw new ArgumentNullException (nameof (protocolType)); - ProtocolType = protocolType; - } - public WitnessType WitnessType { get; private set; } - public SwiftClassType ProtocolType { get; private set; } - - public override SwiftBaseFunctionType AsThunk () - { - var thunk = new SwiftWitnessTableThunkType (WitnessType, ProtocolType, UncurriedParameter as SwiftClassType); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftWitnessTableThunkType : SwiftWitnessTableType { - public SwiftWitnessTableThunkType (WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) - : base (witnessType, protocolType, owningType) - { - } - - public override bool IsThunk => true; - public override SwiftBaseFunctionType AsThunk () => this; - } - - public class SwiftTupleType : SwiftType { - public SwiftTupleType (bool isReference) - : this (null, isReference, null) - { - } - - public SwiftTupleType (IEnumerable contents, bool isReference, SwiftName name = null) - : base (CoreCompoundType.Tuple, isReference, name) - { - Contents = new List (); - if (contents != null) - Contents.AddRange (contents); - } - - public SwiftTupleType (bool isReference, SwiftName name, params SwiftType [] contents) - : this (contents, isReference, name) - { - } - - public List Contents { get; private set; } - public bool IsEmpty { get { return Contents.Count == 0; } } - static SwiftTupleType empty = new SwiftTupleType (null, false, null); - public static SwiftTupleType Empty { get { return empty; } } - - public bool HasNames () - { - return Contents.FirstOrDefault (st => st.Name != null) != null; - } - - protected override bool LLEquals (SwiftType other) - { - SwiftTupleType st = other as SwiftTupleType; - if (st == null) - return false; - return Contents.SequenceEqual (st.Contents); - } - - public SwiftType AllButFirst () - { - if (IsEmpty) - throw new ArgumentOutOfRangeException ("tuple is empty"); - // seriously, this is what we want to do. - // If a function has one argument, it will be a the simple type. - // If a function has more than one argument, it will be a tuple. - if (Contents.Count == 2) - return Contents [1]; - return new SwiftTupleType (Contents.TakeWhile ((st, i) => i > 0), IsReference, Name); - } - - public SwiftType AllButFirstN (int n) - { - if (IsEmpty) - throw new ArgumentOutOfRangeException ("tuple is empty"); - // seriously, this is what we want to do. - // If a function has one argument, it will be a the simple type. - // If a function has more than one argument, it will be a tuple. - // So if we are returning the last element, we're returning an single not a tuple. - if (Contents.Count == n + 1) - return Contents [n]; - return new SwiftTupleType (Contents.Skip (n), IsReference, Name); - } - - public override string ToString() - { - var contents = Contents.Select (el => { - var elname = el.Name != null ? el.Name.Name + ": " : ""; - return elname + el.ToString (); - }).InterleaveCommas (); - return $"({contents})"; - } - } - - public class SwiftBuiltInType : SwiftType { - public SwiftBuiltInType (CoreBuiltInType scalarType, bool isReference, SwiftName name = null) - : base (CoreCompoundType.Scalar, isReference, name) - { - BuiltInType = scalarType; - } - - public CoreBuiltInType BuiltInType { get; private set; } - - protected override bool LLEquals (SwiftType other) - { - SwiftBuiltInType sb = other as SwiftBuiltInType; - return sb != null && BuiltInType == sb.BuiltInType; - } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + BuiltInType.ToString (); - } - - } - - public class SwiftArrayType : SwiftType { - public SwiftArrayType (bool isReference, SwiftName name = null) - : base (CoreCompoundType.Array, isReference, name) - { - } - public override string ToString () - { - var name = Name != null ? Name.Name + ": " : ""; - return $"{name}[]"; - } - } - - public class SwiftClassType : SwiftType { - public SwiftClassType (SwiftClassName className, bool isReference, SwiftName name = null) - : base (CoreCompoundType.Class, isReference, name) - { - ClassName = className; - } - public SwiftClassName ClassName { get; private set; } - public override bool IsClass { get { return EntityKind == MemberNesting.Class; } } - public override bool IsStruct { get { return EntityKind == MemberNesting.Struct; } } - public override bool IsEnum { get { return EntityKind == MemberNesting.Enum; } } - public override bool IsProtocol { get { return EntityKind == MemberNesting.Protocol; } } - - public MemberNesting EntityKind { get { return ClassName.Nesting.Last (); } } - - protected override bool LLEquals (SwiftType other) - { - var sct = other as SwiftClassType; - return sct != null && ClassName.Equals (sct.ClassName); - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + ClassName.ToFullyQualifiedName (); - } - } - - public class SwiftProtocolListType : SwiftType { - public SwiftProtocolListType (IEnumerable protocols, bool isReference, SwiftName name = null) - : base (CoreCompoundType.ProtocolList, isReference, name) - { - Protocols = new List (); - Protocols.AddRange (protocols.Where (p => { - if (p.IsProtocol) { - return true; - } else { - throw new ArgumentOutOfRangeException ("protocols", "protocols must contain only SwiftClassType with EntityKind protocol."); - } - })); - } - - public SwiftProtocolListType (SwiftClassType protocol, bool isReference, SwiftName name = null) - : base (CoreCompoundType.ProtocolList, isReference, name) - { - Protocols = new List (); - if (!protocol.IsProtocol) - throw new ArgumentOutOfRangeException ($"Type {protocol.ClassName.ToFullyQualifiedName ()} is not a protocol"); - Protocols.Add (protocol); - } - - public List Protocols { get; private set; } - - protected override bool LLEquals (SwiftType other) - { - var prot = other as SwiftProtocolListType; - if (other == null) - return false; - if (Protocols.Count != prot.Protocols.Count) - return false; - return Protocols.SequenceEqual (prot.Protocols); - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + Protocols.Select (p => p.ToString ()).InterleaveStrings (" & "); - } - } - - public class SwiftMetaClassType : SwiftType { - public SwiftMetaClassType (SwiftClassType classType, bool isReference, SwiftName name = null) - : base (CoreCompoundType.MetaClass, isReference, name) - { - Class = Exceptions.ThrowOnNull (classType, nameof (classType)); - } - public SwiftMetaClassType (SwiftGenericArgReferenceType classGenericReference, bool isReference, SwiftName name = null) - : base (CoreCompoundType.MetaClass, isReference, name) - { - ClassGenericReference = Exceptions.ThrowOnNull (classGenericReference, nameof (classGenericReference)); - } - public SwiftClassType Class { get; private set; } - public SwiftGenericArgReferenceType ClassGenericReference { get; private set; } - protected override bool LLEquals (SwiftType other) - { - var meta = other as SwiftMetaClassType; - if (meta == null) - return false; - if (Class != null) - return Class.Equals (meta.Class); - else - return ClassGenericReference.Equals (meta.ClassGenericReference); - } - public override string ToString () - { - var name = Name != null ? Name.Name + ": " : ""; - return name + "Meta " + Class; - } - } - - public class SwiftExistentialMetaType : SwiftType { - public SwiftExistentialMetaType (SwiftProtocolListType protocolList, bool isReference, SwiftName name = null) - : base (CoreCompoundType.MetaClass, isReference, name) - { - Protocol = Exceptions.ThrowOnNull (protocolList, nameof (protocolList)); - } - public SwiftProtocolListType Protocol { get; private set; } - protected override bool LLEquals (SwiftType other) - { - var meta = other as SwiftExistentialMetaType; - return meta != null && Protocol.Equals (meta.Protocol); - } - public bool IsAny { get { return Protocol.Protocols.Count == 0; } } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + "Existential Metatype " + Protocol; - } - } - - public class GenericArgument { - public GenericArgument (int depth, int index) - { - Constraints = new List (); - Depth = depth; - Index = index; - } - public int Depth { get; set; } - public int Index { get; set; } - public List Constraints { get; private set; } - public bool IsProtocolConstrained () - { - if (Constraints.Count == 0) - return false; - foreach (SwiftType ty in Constraints) { - var ct = ty as SwiftClassType; - if (ct == null) - throw new NotSupportedException ("Expected a class type, but got " + ty.GetType ().Name); - if (ct.EntityKind != MemberNesting.Protocol) - return false; - } - return true; - } - public bool IsClassConstrained () - { - if (Constraints.Count == 0) - return false; - foreach (SwiftType ty in Constraints) { - var ct = ty as SwiftClassType; - if (ct == null) - throw new NotSupportedException ("Expected a class type, but got " + ty.GetType ().Name); - if (ct.EntityKind != MemberNesting.Protocol) - return true; - } - return false; - } - } - - - public class SwiftUnboundGenericType : SwiftType { - public SwiftUnboundGenericType (SwiftType dependentType, List parms, bool isReference, SwiftName name = null) - : base (CoreCompoundType.UnboundGeneric, isReference, name) - { - DependentType = Exceptions.ThrowOnNull (dependentType, nameof (dependentType)); - Arguments = Exceptions.ThrowOnNull (parms, nameof (parms)); - } - - public SwiftType DependentType { get; private set; } - public List Arguments { get; private set; } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - var genArgs = Arguments.Select ((arg) => $"({arg.Depth},{arg.Index})").InterleaveCommas (); - return $"{name}{DependentType.ToString ()}<{genArgs}>"; - } - } - - public class SwiftGenericArgReferenceType : SwiftType { - public SwiftGenericArgReferenceType (int depth, int index, bool isReference, SwiftName name = null, List associatedTypePath = null) - : base (CoreCompoundType.GenericReference, isReference, name) - { - Depth = depth; - Index = index; - AssociatedTypePath = new List (); - if (associatedTypePath != null) - AssociatedTypePath.AddRange (associatedTypePath); - } - - public int Depth { get; private set; } - public int Index { get; private set; } - public List AssociatedTypePath { get; private set; } - public bool HasAssociatedTypePath => AssociatedTypePath.Count > 0; - - protected override bool LLEquals (SwiftType other) - { - var art = other as SwiftGenericArgReferenceType; - if (art == null) - return false; - if (Depth != art.Depth || Index != art.Index) - return false; - if (AssociatedTypePath.Count != art.AssociatedTypePath.Count) - return false; - return AssociatedTypePath.SequenceEqual (art.AssociatedTypePath); - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - if (HasAssociatedTypePath) { - var path = AssociatedTypePath.InterleaveStrings ("."); - return name + $"({Depth},{Index}){(char)('A' + Depth)}{Index}.{path}"; - } else { - return name + $"({Depth},{Index})"; - } - } - } - - public class SwiftBoundGenericType : SwiftType { - public SwiftBoundGenericType (SwiftType baseType, List boundTypes, bool isReference, SwiftName name = null) - : base (CoreCompoundType.BoundGeneric, isReference, name) - { - BaseType = Exceptions.ThrowOnNull (baseType, "baseType"); - BoundTypes = new List (); - if (boundTypes != null) - BoundTypes.AddRange (boundTypes); - } - public SwiftType BaseType { get; private set; } - public List BoundTypes { get; private set; } - protected override bool LLEquals (SwiftType other) - { - var bgt = other as SwiftBoundGenericType; - return bgt != null && BaseType.Equals (bgt.BaseType) - && BoundTypes.SequenceEqual (bgt.BoundTypes); - } - - public override bool IsClass { get { return BaseType.IsClass; } } - public override bool IsEnum { get { return BaseType.IsEnum; } } - public override bool IsStruct { get { return BaseType.IsStruct; } } - public override string ToString () - { - var name = Name != null ? Name.Name + ": " : ""; - var genArgs = BoundTypes.Select (arg => arg.ToString ()).InterleaveCommas (); - return $"{name}{BaseType.ToString()}<{genArgs}>"; - } - } +namespace SwiftReflector +{ + public class SwiftType + { + protected SwiftType(CoreCompoundType type, bool isReference, SwiftName name = null) + { + Type = type; + IsReference = isReference; + Name = name; + Attributes = new List(); + IsVariadic = false; + } + + public CoreCompoundType Type { get; private set; } + public SwiftName Name { get; private set; } + public bool IsReference { get; private set; } + public List Attributes { get; private set; } + public bool IsVariadic { get; set; } + + + public SwiftType ReferenceCloneOf() + { + if (IsReference) + return this; + var ty = MemberwiseClone() as SwiftType; + ty.IsReference = true; + return ty; + } + + public SwiftType NonReferenceCloneOf() + { + if (!IsReference) + return this; + var ty = MemberwiseClone() as SwiftType; + ty.IsReference = false; + return ty; + } + + public SwiftType RenamedCloneOf(SwiftName newName) + { + var ty = MemberwiseClone() as SwiftType; + ty.Name = newName; + return ty; + } + + + public bool IsConstructor { get { return this is SwiftConstructorType; } } + + public bool IsOptionalConstructor + { + get + { + // a SwiftType is an optional ctor if: + // 1 it's a SwiftConstructorType + // 2 its return type is SwiftBoundGenericType + // 3 its return type has a base of Swift.Optional + // 4 its return type has exactly one bound type to the type of + // the metatype of this class + var ctor = this as SwiftConstructorType; + if (ctor == null) + return false; + var returnType = ctor.ReturnType as SwiftBoundGenericType; + if (returnType == null) + return false; + if (returnType.BoundTypes.Count != 1) + return false; + var baseType = returnType.BaseType as SwiftClassType; + if (baseType == null) + return false; + var boundType = returnType.BoundTypes[0] as SwiftClassType; + if (boundType == null) + return false; + var uncurriedParameter = ctor.UncurriedParameter as SwiftMetaClassType; + if (uncurriedParameter == null) + return false; + return baseType.ClassName.ToFullyQualifiedName() == "Swift.Optional" && + boundType.ClassName.ToFullyQualifiedName(true) == uncurriedParameter.Class.ClassName.ToFullyQualifiedName(true); + } + } + + public bool IsEmptyTuple + { + get + { + var tuple = this as SwiftTupleType; + return tuple == null ? false : tuple.IsEmpty; + } + } + public virtual bool IsClass { get { return false; } } + public virtual bool IsStruct { get { return false; } } + public virtual bool IsEnum { get { return false; } } + public virtual bool IsProtocol { get { return false; } } + + public bool HasAttribute(SwiftTypeAttribute attribute) + { + return Attributes.Any(attr => attr == attribute); + } + + [Obsolete("this is not supported in Swift 5")] + public bool HasObjCAttribute => HasAttribute(SwiftTypeAttribute.ObjC); + + public override int GetHashCode() + { + return Type.GetHashCode() + + (Name != null ? Name.GetHashCode() : 0); + } + + public override bool Equals(object obj) + { + var type = obj as SwiftType; + if (type == null) + return false; + if (type.Type != Type) + return false; + if (type.IsReference != IsReference) + return false; + if (type.IsVariadic != IsVariadic) + return false; + if (type.GetType() != this.GetType()) + return false; + // shouldn't do Name equality except in functions + return LLEquals(type); + } + + public virtual bool EqualsReferenceInvaraint(SwiftType type) + { + var a = ProjectAsNonReference(this); + var b = ProjectAsNonReference(type); + + if (b.Type != a.Type) + return false; + if (b.GetType() != a.GetType()) + return false; + // shouldn't do Name equality except in functions + return a.LLEquals(b); + } + + static SwiftType ProjectAsNonReference(SwiftType a) + { + if (a.IsReference) + { + return a.NonReferenceCloneOf(); + } + var bgt = a as SwiftBoundGenericType; + if (bgt != null && bgt.BoundTypes.Count == 1) + { + var baseType = bgt.BaseType as SwiftClassType; + if (baseType != null) + { + string name = baseType.ClassName.ToFullyQualifiedName(true); + if (name == "Swift.UnsafePointer" || name == "Swift.UnsafeMutablePointer") + return bgt.BoundTypes[0]; + } + } + return a; + } + + protected virtual bool LLEquals(SwiftType other) + { + return true; + } + + + public static bool IsStructScalar(SwiftType st) + { + if (st == null) + return false; + if (st is SwiftBuiltInType) + return true; + var ct = st as SwiftClassType; + if (ct == null) + return false; + return IsStructScalar(ct.ClassName.ToFullyQualifiedName()); + } + + public static bool IsStructScalar(string fullyQualifiedName) + { + switch (fullyQualifiedName) + { + case "Swift.Int64": + case "Swift.UInt64": + case "Swift.Int32": + case "Swift.UInt32": + case "Swift.Int16": + case "Swift.UInt16": + case "Swift.Int8": + case "Swift.UInt8": + case "Swift.Char": + case "CoreGraphics.CGFloat": + case "Swift.UnsafeRawPointer": + case "Swift.UnsafeMutableRawPointer": + case "Swift.OpaquePointer": + return true; + default: + return false; + } + } + } + + public class SwiftModuleNameType : SwiftType + { + public SwiftModuleNameType(SwiftName name, bool isReference) + : base(CoreCompoundType.ModuleName, isReference, name) + { + } + public override string ToString() + { + return Name != null ? Name.Name : "(unknown module)"; + } + } + + public abstract class SwiftBaseFunctionType : SwiftType + { + public SwiftBaseFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base(CoreCompoundType.Function, isReference, name) + { + Parameters = Exceptions.ThrowOnNull(parms, nameof(parms)); + ReturnType = Exceptions.ThrowOnNull(ret, nameof(ret)); + GenericArguments = new List(); + CanThrow = canThrow; + ExtensionOn = extensionOn; + } + + public bool ContainsGenericParameters + { + get + { + return GenericArguments.Count() > 0; + } + } + public SwiftType ExtensionOn { get; set; } + public abstract MemberType MemberType { get; } + public SwiftType Parameters { get; private set; } + public SwiftType ReturnType { get; private set; } + public List GenericArguments { get; private set; } + public bool CanThrow { get; private set; } + public bool IsExtension { get { return ExtensionOn != null; } } + public virtual bool IsThunk => false; + public SwiftBaseFunctionType Thunk { get; set; } + + public abstract SwiftBaseFunctionType AsThunk(); + + // for short-lived discretionary storage of information + public string DiscretionaryString { get; set; } + + public IEnumerable EachParameter + { + get + { + for (int i = 0; i < ParameterCount; i++) + { + yield return GetParameter(i); + } + } + } + + public int GenericParameterCount + { + get { return EachParameter.Sum(st => st is SwiftGenericArgReferenceType ? 1 : 0); } + } + + + public bool IsVoid { get { return ReturnType.Type == CoreCompoundType.Tuple && ((SwiftTupleType)ReturnType).IsEmpty; } } + + protected override bool LLEquals(SwiftType other) + { + var fn = other as SwiftBaseFunctionType; + if (fn == null) + return false; + if (Name != null) + Name.Equals(fn.Name); + return MemberType == fn.MemberType && Parameters.Equals(fn.Parameters) + && ReturnType.Equals(fn.ReturnType); + } + + public int ParameterCount + { + get + { + var tt = Parameters as SwiftTupleType; + if (tt == null) + { + return 1; + } + else + { + return tt.Contents.Count; + } + } + } + + public SwiftType GetParameter(int index) + { + var tt = Parameters as SwiftTupleType; + if (tt == null) + { + if (index == 0) + return Parameters; + else + throw new ArgumentOutOfRangeException(nameof(index)); + } + else + { + if (index < 0 || index >= tt.Contents.Count) + throw new ArgumentOutOfRangeException(nameof(index)); + return tt.Contents[index]; + } + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return $"{name}{Parameters.ToString()}->{ReturnType.ToString()}"; + } + } + + public class SwiftCFunctionType : SwiftBaseFunctionType + { + public SwiftCFunctionType(SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) + : base(parms, ret, isReference, false, name, null) + { + } + + public override MemberType MemberType + { + get + { + return MemberType.CFunction; + } + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftCFunctionTypeThunk(Parameters, ReturnType, IsReference, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftCFunctionTypeThunk : SwiftCFunctionType + { + public SwiftCFunctionTypeThunk(SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) + : base(parms, ret, isReference, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftAddressorType : SwiftBaseFunctionType + { + public SwiftAddressorType(AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) + : base(SwiftTupleType.Empty, ret, isReference, false, name, null) + { + AddressorType = addressor; + } + public AddressorType AddressorType { get; private set; } + public override MemberType MemberType + { + get + { + return MemberType.Addressor; + } + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftAddressorThunkType(AddressorType, ReturnType, IsReference, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftAddressorThunkType : SwiftAddressorType + { + public SwiftAddressorThunkType(AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) + : base(addressor, ret, isReference, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftInitializerType : SwiftBaseFunctionType + { + public SwiftInitializerType(InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) + : base(SwiftTupleType.Empty, ret, false, false, name, null) + { + Owner = Exceptions.ThrowOnNull(owner, nameof(owner)); + InitializerType = initType; + } + + public InitializerType InitializerType { get; private set; } + public SwiftClassType Owner { get; private set; } + public override MemberType MemberType + { + get + { + return MemberType.Initializer; + } + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftInitializerThunkType(InitializerType, ReturnType, Owner, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftInitializerThunkType : SwiftInitializerType + { + public SwiftInitializerThunkType(InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) + : base(initType, ret, owner, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftFunctionType : SwiftBaseFunctionType + { + public SwiftFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) + : base(parms, ret, isReference, canThrow, name, extensionOn) + { + IsEscaping = isEscaping; + } + + public override MemberType MemberType { get { return MemberType.Function; } } + public bool IsEscaping { get; private set; } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftFunctionThunkType(Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn, IsEscaping); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftFunctionThunkType : SwiftFunctionType + { + public SwiftFunctionThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) + : base(parms, ret, isReference, canThrow, name, extensionOn, isEscaping) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftCFunctionPointerType : SwiftFunctionType + { + public SwiftCFunctionPointerType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) + : base(parms, ret, isReference, canThrow, name, null) + { + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftCFunctionPointerThunkType(Parameters, ReturnType, IsReference, CanThrow, Name); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftCFunctionPointerThunkType : SwiftCFunctionPointerType + { + public SwiftCFunctionPointerThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) + : base(parms, ret, isReference, canThrow, name) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftStaticFunctionType : SwiftFunctionType + { + public SwiftStaticFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) + : base(parms, ret, isReference, canThrow, name, extensionOn) + { + OfClass = ofClass; + } + + public SwiftClassType OfClass { get; private set; } + + public override SwiftBaseFunctionType AsThunk() + { + var func = new SwiftStaticFunctionThunkType(Parameters, ReturnType, IsReference, CanThrow, OfClass, Name, ExtensionOn); + func.DiscretionaryString = DiscretionaryString; + return func; + } + } + + public class SwiftStaticFunctionThunkType : SwiftStaticFunctionType + { + public SwiftStaticFunctionThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) + : base(parms, ret, isReference, canThrow, ofClass, name, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + + public class SwiftClassConstructorType : SwiftFunctionType + { + public SwiftClassConstructorType(SwiftMetaClassType meta, bool isReference) + : base(SwiftTupleType.Empty, Exceptions.ThrowOnNull(meta, "meta"), isReference, false, Decomposer.kSwiftClassConstructorName) + { + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftClassConstructorThunkType(ReturnType as SwiftMetaClassType, IsReference); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftClassConstructorThunkType : SwiftClassConstructorType + { + public SwiftClassConstructorThunkType(SwiftMetaClassType meta, bool isReference) + : base(meta, isReference) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftUncurriedFunctionType : SwiftBaseFunctionType + { + public SwiftUncurriedFunctionType(SwiftType unCurriedParameter, + SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : this(MemberType.UncurriedFunction, unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) + { + } + + protected SwiftUncurriedFunctionType(MemberType memberType, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base(parms, ret, isReference, canThrow, name, extensionOn) + { + // oddly enough, this is allowed to be null + UncurriedParameter = unCurriedParameter; + this.memberType = memberType; + } + MemberType memberType; + public override MemberType MemberType { get { return memberType; } } + public SwiftType UncurriedParameter { get; private set; } + + protected override bool LLEquals(SwiftType other) + { + var ucf = other as SwiftUncurriedFunctionType; + return ucf != null && ucf.UncurriedParameter.Equals(UncurriedParameter) && base.LLEquals(other); + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftUncurriedFunctionThunkType(UncurriedParameter, Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftUncurriedFunctionThunkType : SwiftUncurriedFunctionType + { + public SwiftUncurriedFunctionThunkType(SwiftType unCurriedParameter, + SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) + : base(unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + + public class SwiftConstructorType : SwiftUncurriedFunctionType + { + public SwiftConstructorType(bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) + : base(isAllocating ? MemberType.Allocator : MemberType.Constructor, + unCurriedParameter, parms, ret, isReference, canThrow, isAllocating ? Decomposer.kSwiftAllocatingConstructorName : + Decomposer.kSwiftNonAllocatingConstructorName, extensionOn) + { + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftConstructorThunkType(MemberType == MemberType.Allocator, UncurriedParameter, + Parameters, ReturnType, IsReference, CanThrow, ExtensionOn); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftConstructorThunkType : SwiftConstructorType + { + public SwiftConstructorThunkType(bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) + : base(isAllocating, unCurriedParameter, parms, ret, isReference, canThrow, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftDestructorType : SwiftBaseFunctionType + { + public SwiftDestructorType(bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) + : base(classType, classType, isReference, canThrow, + isDeallocating ? Decomposer.kSwiftDeallocatingDestructorName : Decomposer.kSwiftNonDeallocatingDestructorName, null) + { + memberType = isDeallocating ? MemberType.Deallocator : MemberType.Destructor; + } + MemberType memberType; + public override MemberType MemberType { get { return memberType; } } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftDestructorThunkType(Name == Decomposer.kSwiftDeallocatingDestructorName, ReturnType as SwiftClassType, IsReference, CanThrow); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftDestructorThunkType : SwiftDestructorType + { + public SwiftDestructorThunkType(bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) + : base(isDeallocating, classType, isReference, canThrow) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftPropertyType : SwiftUncurriedFunctionType + { + public SwiftPropertyType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base(unCurriedParameter, + (propType == PropertyType.Setter || propType == PropertyType.Materializer) ? ofType : SwiftTupleType.Empty, + (propType == PropertyType.Getter) ? ofType : SwiftTupleType.Empty, + isReference, false, propName, extensionOn) + { + PropertyType = propType; + PrivateName = privateName; + OfType = Exceptions.ThrowOnNull(ofType, "ofType"); + IsSubscript = false; + IsStatic = isStatic; + } + public SwiftPropertyType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base(unCurriedParameter, accessor.Parameters, accessor.ReturnType, isReference, false, propName, extensionOn) + { + PropertyType = propType; + PrivateName = privateName; + OfType = accessor; + IsSubscript = true; + IsStatic = isStatic; + } + + public PropertyType PropertyType { get; private set; } + public SwiftName PrivateName { get; private set; } + public SwiftType OfType { get; private set; } + public bool IsStatic { get; private set; } + + public bool IsSubscript { get; private set; } + public bool IsPublic { get { return PrivateName == null; } } + public bool IsPrivate { get { return PrivateName != null; } } + public bool IsGlobal { get { return UncurriedParameter == null; } } + + public SwiftPropertyType RecastAsStatic() + { + if (IsStatic) + return this; + SwiftPropertyType newProp = null; + if (OfType is SwiftFunctionType) + { + if (this is SwiftPropertyThunkType) + { + newProp = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, + true, IsReference); + + } + else + { + newProp = new SwiftPropertyType(UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, + true, IsReference); + } + } + else + { + if (this is SwiftPropertyThunkType) + { + newProp = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); + + } + else + { + newProp = new SwiftPropertyType(UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); + } + } + newProp.DiscretionaryString = DiscretionaryString; + newProp.ExtensionOn = this.ExtensionOn; + return newProp; + } + + public override SwiftBaseFunctionType AsThunk() + { + if (IsSubscript) + { + var pt = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, + PrivateName, OfType as SwiftFunctionType, IsStatic, IsReference, ExtensionOn); + pt.DiscretionaryString = DiscretionaryString; + return pt; + } + else + { + var pt = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, + PrivateName, OfType, IsStatic, IsReference, ExtensionOn); + pt.DiscretionaryString = DiscretionaryString; + return pt; + } + } + } + + public class SwiftPropertyThunkType : SwiftPropertyType + { + public SwiftPropertyThunkType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base(unCurriedParameter, propType, propName, privateName, ofType, isStatic, isReference, extensionOn) + { + } + + public SwiftPropertyThunkType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, + SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) + : base(unCurriedParameter, propType, propName, privateName, accessor, isStatic, isReference, extensionOn) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftExplicitClosureType : SwiftBaseFunctionType + { + public SwiftExplicitClosureType(bool isReference) + : base(SwiftTupleType.Empty, SwiftTupleType.Empty, isReference, false, null) + { + } + + public override MemberType MemberType + { + get + { + return MemberType.ExplicitClosure; + } + } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftExplicitClosureThunkType(IsReference); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftExplicitClosureThunkType : SwiftExplicitClosureType + { + public SwiftExplicitClosureThunkType(bool isReference) + : base(isReference) + { + } + + public override bool IsThunk => true; + + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftWitnessTableType : SwiftUncurriedFunctionType + { + public SwiftWitnessTableType(WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) + : base((SwiftType)owningType ?? SwiftTupleType.Empty, SwiftTupleType.Empty, SwiftTupleType.Empty, false, false, null) + { + WitnessType = witnessType; + if (WitnessType == WitnessType.Protocol && protocolType == null) + throw new ArgumentNullException(nameof(protocolType)); + ProtocolType = protocolType; + } + public WitnessType WitnessType { get; private set; } + public SwiftClassType ProtocolType { get; private set; } + + public override SwiftBaseFunctionType AsThunk() + { + var thunk = new SwiftWitnessTableThunkType(WitnessType, ProtocolType, UncurriedParameter as SwiftClassType); + thunk.DiscretionaryString = DiscretionaryString; + return thunk; + } + } + + public class SwiftWitnessTableThunkType : SwiftWitnessTableType + { + public SwiftWitnessTableThunkType(WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) + : base(witnessType, protocolType, owningType) + { + } + + public override bool IsThunk => true; + public override SwiftBaseFunctionType AsThunk() => this; + } + + public class SwiftTupleType : SwiftType + { + public SwiftTupleType(bool isReference) + : this(null, isReference, null) + { + } + + public SwiftTupleType(IEnumerable contents, bool isReference, SwiftName name = null) + : base(CoreCompoundType.Tuple, isReference, name) + { + Contents = new List(); + if (contents != null) + Contents.AddRange(contents); + } + + public SwiftTupleType(bool isReference, SwiftName name, params SwiftType[] contents) + : this(contents, isReference, name) + { + } + + public List Contents { get; private set; } + public bool IsEmpty { get { return Contents.Count == 0; } } + static SwiftTupleType empty = new SwiftTupleType(null, false, null); + public static SwiftTupleType Empty { get { return empty; } } + + public bool HasNames() + { + return Contents.FirstOrDefault(st => st.Name != null) != null; + } + + protected override bool LLEquals(SwiftType other) + { + SwiftTupleType st = other as SwiftTupleType; + if (st == null) + return false; + return Contents.SequenceEqual(st.Contents); + } + + public SwiftType AllButFirst() + { + if (IsEmpty) + throw new ArgumentOutOfRangeException("tuple is empty"); + // seriously, this is what we want to do. + // If a function has one argument, it will be a the simple type. + // If a function has more than one argument, it will be a tuple. + if (Contents.Count == 2) + return Contents[1]; + return new SwiftTupleType(Contents.TakeWhile((st, i) => i > 0), IsReference, Name); + } + + public SwiftType AllButFirstN(int n) + { + if (IsEmpty) + throw new ArgumentOutOfRangeException("tuple is empty"); + // seriously, this is what we want to do. + // If a function has one argument, it will be a the simple type. + // If a function has more than one argument, it will be a tuple. + // So if we are returning the last element, we're returning an single not a tuple. + if (Contents.Count == n + 1) + return Contents[n]; + return new SwiftTupleType(Contents.Skip(n), IsReference, Name); + } + + public override string ToString() + { + var contents = Contents.Select(el => + { + var elname = el.Name != null ? el.Name.Name + ": " : ""; + return elname + el.ToString(); + }).InterleaveCommas(); + return $"({contents})"; + } + } + + public class SwiftBuiltInType : SwiftType + { + public SwiftBuiltInType(CoreBuiltInType scalarType, bool isReference, SwiftName name = null) + : base(CoreCompoundType.Scalar, isReference, name) + { + BuiltInType = scalarType; + } + + public CoreBuiltInType BuiltInType { get; private set; } + + protected override bool LLEquals(SwiftType other) + { + SwiftBuiltInType sb = other as SwiftBuiltInType; + return sb != null && BuiltInType == sb.BuiltInType; + } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + BuiltInType.ToString(); + } + + } + + public class SwiftArrayType : SwiftType + { + public SwiftArrayType(bool isReference, SwiftName name = null) + : base(CoreCompoundType.Array, isReference, name) + { + } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return $"{name}[]"; + } + } + + public class SwiftClassType : SwiftType + { + public SwiftClassType(SwiftClassName className, bool isReference, SwiftName name = null) + : base(CoreCompoundType.Class, isReference, name) + { + ClassName = className; + } + public SwiftClassName ClassName { get; private set; } + public override bool IsClass { get { return EntityKind == MemberNesting.Class; } } + public override bool IsStruct { get { return EntityKind == MemberNesting.Struct; } } + public override bool IsEnum { get { return EntityKind == MemberNesting.Enum; } } + public override bool IsProtocol { get { return EntityKind == MemberNesting.Protocol; } } + + public MemberNesting EntityKind { get { return ClassName.Nesting.Last(); } } + + protected override bool LLEquals(SwiftType other) + { + var sct = other as SwiftClassType; + return sct != null && ClassName.Equals(sct.ClassName); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + ClassName.ToFullyQualifiedName(); + } + } + + public class SwiftProtocolListType : SwiftType + { + public SwiftProtocolListType(IEnumerable protocols, bool isReference, SwiftName name = null) + : base(CoreCompoundType.ProtocolList, isReference, name) + { + Protocols = new List(); + Protocols.AddRange(protocols.Where(p => + { + if (p.IsProtocol) + { + return true; + } + else + { + throw new ArgumentOutOfRangeException("protocols", "protocols must contain only SwiftClassType with EntityKind protocol."); + } + })); + } + + public SwiftProtocolListType(SwiftClassType protocol, bool isReference, SwiftName name = null) + : base(CoreCompoundType.ProtocolList, isReference, name) + { + Protocols = new List(); + if (!protocol.IsProtocol) + throw new ArgumentOutOfRangeException($"Type {protocol.ClassName.ToFullyQualifiedName()} is not a protocol"); + Protocols.Add(protocol); + } + + public List Protocols { get; private set; } + + protected override bool LLEquals(SwiftType other) + { + var prot = other as SwiftProtocolListType; + if (other == null) + return false; + if (Protocols.Count != prot.Protocols.Count) + return false; + return Protocols.SequenceEqual(prot.Protocols); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + Protocols.Select(p => p.ToString()).InterleaveStrings(" & "); + } + } + + public class SwiftMetaClassType : SwiftType + { + public SwiftMetaClassType(SwiftClassType classType, bool isReference, SwiftName name = null) + : base(CoreCompoundType.MetaClass, isReference, name) + { + Class = Exceptions.ThrowOnNull(classType, nameof(classType)); + } + public SwiftMetaClassType(SwiftGenericArgReferenceType classGenericReference, bool isReference, SwiftName name = null) + : base(CoreCompoundType.MetaClass, isReference, name) + { + ClassGenericReference = Exceptions.ThrowOnNull(classGenericReference, nameof(classGenericReference)); + } + public SwiftClassType Class { get; private set; } + public SwiftGenericArgReferenceType ClassGenericReference { get; private set; } + protected override bool LLEquals(SwiftType other) + { + var meta = other as SwiftMetaClassType; + if (meta == null) + return false; + if (Class != null) + return Class.Equals(meta.Class); + else + return ClassGenericReference.Equals(meta.ClassGenericReference); + } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + "Meta " + Class; + } + } + + public class SwiftExistentialMetaType : SwiftType + { + public SwiftExistentialMetaType(SwiftProtocolListType protocolList, bool isReference, SwiftName name = null) + : base(CoreCompoundType.MetaClass, isReference, name) + { + Protocol = Exceptions.ThrowOnNull(protocolList, nameof(protocolList)); + } + public SwiftProtocolListType Protocol { get; private set; } + protected override bool LLEquals(SwiftType other) + { + var meta = other as SwiftExistentialMetaType; + return meta != null && Protocol.Equals(meta.Protocol); + } + public bool IsAny { get { return Protocol.Protocols.Count == 0; } } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + return name + "Existential Metatype " + Protocol; + } + } + + public class GenericArgument + { + public GenericArgument(int depth, int index) + { + Constraints = new List(); + Depth = depth; + Index = index; + } + public int Depth { get; set; } + public int Index { get; set; } + public List Constraints { get; private set; } + public bool IsProtocolConstrained() + { + if (Constraints.Count == 0) + return false; + foreach (SwiftType ty in Constraints) + { + var ct = ty as SwiftClassType; + if (ct == null) + throw new NotSupportedException("Expected a class type, but got " + ty.GetType().Name); + if (ct.EntityKind != MemberNesting.Protocol) + return false; + } + return true; + } + public bool IsClassConstrained() + { + if (Constraints.Count == 0) + return false; + foreach (SwiftType ty in Constraints) + { + var ct = ty as SwiftClassType; + if (ct == null) + throw new NotSupportedException("Expected a class type, but got " + ty.GetType().Name); + if (ct.EntityKind != MemberNesting.Protocol) + return true; + } + return false; + } + } + + + public class SwiftUnboundGenericType : SwiftType + { + public SwiftUnboundGenericType(SwiftType dependentType, List parms, bool isReference, SwiftName name = null) + : base(CoreCompoundType.UnboundGeneric, isReference, name) + { + DependentType = Exceptions.ThrowOnNull(dependentType, nameof(dependentType)); + Arguments = Exceptions.ThrowOnNull(parms, nameof(parms)); + } + + public SwiftType DependentType { get; private set; } + public List Arguments { get; private set; } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + var genArgs = Arguments.Select((arg) => $"({arg.Depth},{arg.Index})").InterleaveCommas(); + return $"{name}{DependentType.ToString()}<{genArgs}>"; + } + } + + public class SwiftGenericArgReferenceType : SwiftType + { + public SwiftGenericArgReferenceType(int depth, int index, bool isReference, SwiftName name = null, List associatedTypePath = null) + : base(CoreCompoundType.GenericReference, isReference, name) + { + Depth = depth; + Index = index; + AssociatedTypePath = new List(); + if (associatedTypePath != null) + AssociatedTypePath.AddRange(associatedTypePath); + } + + public int Depth { get; private set; } + public int Index { get; private set; } + public List AssociatedTypePath { get; private set; } + public bool HasAssociatedTypePath => AssociatedTypePath.Count > 0; + + protected override bool LLEquals(SwiftType other) + { + var art = other as SwiftGenericArgReferenceType; + if (art == null) + return false; + if (Depth != art.Depth || Index != art.Index) + return false; + if (AssociatedTypePath.Count != art.AssociatedTypePath.Count) + return false; + return AssociatedTypePath.SequenceEqual(art.AssociatedTypePath); + } + + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + if (HasAssociatedTypePath) + { + var path = AssociatedTypePath.InterleaveStrings("."); + return name + $"({Depth},{Index}){(char)('A' + Depth)}{Index}.{path}"; + } + else + { + return name + $"({Depth},{Index})"; + } + } + } + + public class SwiftBoundGenericType : SwiftType + { + public SwiftBoundGenericType(SwiftType baseType, List boundTypes, bool isReference, SwiftName name = null) + : base(CoreCompoundType.BoundGeneric, isReference, name) + { + BaseType = Exceptions.ThrowOnNull(baseType, "baseType"); + BoundTypes = new List(); + if (boundTypes != null) + BoundTypes.AddRange(boundTypes); + } + public SwiftType BaseType { get; private set; } + public List BoundTypes { get; private set; } + protected override bool LLEquals(SwiftType other) + { + var bgt = other as SwiftBoundGenericType; + return bgt != null && BaseType.Equals(bgt.BaseType) + && BoundTypes.SequenceEqual(bgt.BoundTypes); + } + + public override bool IsClass { get { return BaseType.IsClass; } } + public override bool IsEnum { get { return BaseType.IsEnum; } } + public override bool IsStruct { get { return BaseType.IsStruct; } } + public override string ToString() + { + var name = Name != null ? Name.Name + ": " : ""; + var genArgs = BoundTypes.Select(arg => arg.ToString()).InterleaveCommas(); + return $"{name}{BaseType.ToString()}<{genArgs}>"; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs index fe187288b436..8590efeb6add 100644 --- a/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs @@ -6,63 +6,70 @@ using System.Collections.Generic; using System.Xml.Linq; -namespace SwiftReflector.SwiftXmlReflection { - public class AssociatedTypeDeclaration { - public AssociatedTypeDeclaration () - { - ConformingProtocols = new List (); - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class AssociatedTypeDeclaration + { + public AssociatedTypeDeclaration() + { + ConformingProtocols = new List(); + } - public string Name { get; set; } + public string Name { get; set; } - public TypeSpec SuperClass { get; set; } - public TypeSpec DefaultType { get; set; } - public List ConformingProtocols { get; private set; } + public TypeSpec SuperClass { get; set; } + public TypeSpec DefaultType { get; set; } + public List ConformingProtocols { get; private set; } - public static AssociatedTypeDeclaration FromXElement (TypeAliasFolder folder, XElement elem) - { - var assocType = new AssociatedTypeDeclaration (); - assocType.Name = NameAttribute (elem); + public static AssociatedTypeDeclaration FromXElement(TypeAliasFolder folder, XElement elem) + { + var assocType = new AssociatedTypeDeclaration(); + assocType.Name = NameAttribute(elem); - var superClassElem = elem.Element ("superclass"); - if (superClassElem != null) { - var superClassName = NameAttribute (superClassElem); - if (superClassName != null) { - assocType.SuperClass = folder.FoldAlias (null, TypeSpecParser.Parse (superClassName)); - } - } - var defaultDefn = elem.Attribute ("defaulttype"); - if (defaultDefn != null) { - assocType.DefaultType = folder.FoldAlias (null, TypeSpecParser.Parse ((string)defaultDefn)); - } - - if (elem.Element ("conformingprotocols") != null) { - var conforming = from conform in elem.Element ("conformingprotocols").Elements () - select folder.FoldAlias (null, TypeSpecParser.Parse (NameAttribute (conform))) as NamedTypeSpec; - assocType.ConformingProtocols.AddRange (conforming); - } + var superClassElem = elem.Element("superclass"); + if (superClassElem != null) + { + var superClassName = NameAttribute(superClassElem); + if (superClassName != null) + { + assocType.SuperClass = folder.FoldAlias(null, TypeSpecParser.Parse(superClassName)); + } + } + var defaultDefn = elem.Attribute("defaulttype"); + if (defaultDefn != null) + { + assocType.DefaultType = folder.FoldAlias(null, TypeSpecParser.Parse((string)defaultDefn)); + } - return assocType; - } + if (elem.Element("conformingprotocols") != null) + { + var conforming = from conform in elem.Element("conformingprotocols").Elements() + select folder.FoldAlias(null, TypeSpecParser.Parse(NameAttribute(conform))) as NamedTypeSpec; + assocType.ConformingProtocols.AddRange(conforming); + } - public void GatherXObjects (List xobjects) - { - xobjects.Add (new XAttribute ("name", Name)); - if (SuperClass != null) - xobjects.Add (new XElement ("superclass", new XElement ("superclass", new XAttribute ("name", SuperClass.ToString ())))); - if (DefaultType != null) - xobjects.Add (new XAttribute ("defaulttype", DefaultType.ToString ())); - var conforming = new List (); - foreach (var spec in ConformingProtocols) { - conforming.Add (new XElement ("conformingprotocol", new XAttribute ("name", spec.ToString ()))); - } - xobjects.Add (new XElement ("conformingprotocols", conforming.ToArray ())); - } + return assocType; + } - static string NameAttribute(XElement elem) - { - return (string)elem.Attribute ("name"); - } - } + public void GatherXObjects(List xobjects) + { + xobjects.Add(new XAttribute("name", Name)); + if (SuperClass != null) + xobjects.Add(new XElement("superclass", new XElement("superclass", new XAttribute("name", SuperClass.ToString())))); + if (DefaultType != null) + xobjects.Add(new XAttribute("defaulttype", DefaultType.ToString())); + var conforming = new List(); + foreach (var spec in ConformingProtocols) + { + conforming.Add(new XElement("conformingprotocol", new XAttribute("name", spec.ToString()))); + } + xobjects.Add(new XElement("conformingprotocols", conforming.ToArray())); + } + + static string NameAttribute(XElement elem) + { + return (string)elem.Attribute("name"); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs index dafbf9871f79..1c11ba360b15 100644 --- a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs @@ -7,143 +7,155 @@ using SyntaxDynamo; using System.Linq; -namespace SwiftReflector.SwiftXmlReflection { - public class AttributeDeclaration { - public AttributeDeclaration (string typeName) - { - Name = Exceptions.ThrowOnNull (typeName, nameof (typeName)); - Parameters = new List (); - } - - public AttributeDeclaration (AttributeDeclaration other) - : this (other.Name) - { - foreach (var parameter in other.Parameters) - Parameters.Add (DuplicateOf (parameter)); - } - - public static AttributeDeclaration FromXElement (XElement elem) - { - var decl = new AttributeDeclaration (elem.Attribute ("name").Value); - var parameters = elem.Element ("attributeparameterlist"); - if (parameters == null) - return decl; - FromAttributeParameterList (parameters, decl.Parameters); - return decl; - } - - internal static void FromAttributeParameterList (XElement parameters, List outlist) - { - foreach (var parameterElem in parameters.Elements ("attributeparameter")) { - var parameter = AttributeParameter.FromXElement (parameterElem); - outlist.Add (parameter); - } - } - - public static AttributeParameter DuplicateOf(AttributeParameter other) - { - switch (other.Kind) { - case AttributeParameterKind.Label: - return new AttributeParameterLabel ((AttributeParameterLabel)other); - case AttributeParameterKind.Literal: - return new AttributeParameterLiteral ((AttributeParameterLiteral)other); - case AttributeParameterKind.Sublist: - return new AttributeParameterSublist ((AttributeParameterSublist)other); - case AttributeParameterKind.Unknown: - return new AttributeParameter (); - default: - throw new ArgumentOutOfRangeException (nameof (other), other.Kind.ToString ()); - } - } - - public NamedTypeSpec AttributeType { get; private set; } - public string Name { - get { - return AttributeType.ToString (true); - } - private set { - Exceptions.ThrowOnNull (value, nameof (value)); - var ts = TypeSpecParser.Parse (value); - if (ts is NamedTypeSpec named) - AttributeType = named; - else - throw new ArgumentOutOfRangeException ($"TypeSpec for {value} is a {ts.Kind} and not a named type spec"); - } - } - public List Parameters { get; private set; } - } - - public class AttributeParameter { - public static AttributeParameter FromXElement (XElement elem) - { - switch (elem.Attribute ("kind").Value) { - case "Label": - return new AttributeParameterLabel (elem.Attribute ("Value").Value); - case "Literal": - return new AttributeParameterLiteral (elem.Attribute ("Value").Value); - case "Sublist": - return AttributeParameterSublist.SublistFromXElement (elem); - default: - return new AttributeParameter (); - } - } - - public virtual AttributeParameterKind Kind => AttributeParameterKind.Unknown; - } - - public class AttributeParameterLabel : AttributeParameter { - public AttributeParameterLabel (string label) - { - Label = Exceptions.ThrowOnNull (label, nameof (label)); - } - - public AttributeParameterLabel (AttributeParameterLabel other) - : this (other.Label) - { - } - - public override AttributeParameterKind Kind => AttributeParameterKind.Label; - public string Label { get; private set; } - } - - public class AttributeParameterLiteral : AttributeParameter { - public AttributeParameterLiteral (string literal) - { - Literal = Exceptions.ThrowOnNull (literal, nameof (literal)); - } - - public AttributeParameterLiteral (AttributeParameterLiteral other) - : this (other.Literal) - { - } - - public override AttributeParameterKind Kind => AttributeParameterKind.Literal; - public string Literal { get; private set; } - } - - public class AttributeParameterSublist : AttributeParameter { - public AttributeParameterSublist () - { - Parameters = new List (); - } - - public AttributeParameterSublist (AttributeParameterSublist other) - : this () - { - Parameters.AddRange (other.Parameters.Select (prm => AttributeDeclaration.DuplicateOf (prm))); - } - - public static AttributeParameterSublist SublistFromXElement (XElement elem) - { - var sublist = new AttributeParameterSublist (); - var parameters = elem.Element ("attributeparameterlist"); - if (parameters == null) - return sublist; - AttributeDeclaration.FromAttributeParameterList (parameters, sublist.Parameters); - return sublist; - } - - public override AttributeParameterKind Kind => AttributeParameterKind.Sublist; - public List Parameters { get; private set; } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class AttributeDeclaration + { + public AttributeDeclaration(string typeName) + { + Name = Exceptions.ThrowOnNull(typeName, nameof(typeName)); + Parameters = new List(); + } + + public AttributeDeclaration(AttributeDeclaration other) + : this(other.Name) + { + foreach (var parameter in other.Parameters) + Parameters.Add(DuplicateOf(parameter)); + } + + public static AttributeDeclaration FromXElement(XElement elem) + { + var decl = new AttributeDeclaration(elem.Attribute("name").Value); + var parameters = elem.Element("attributeparameterlist"); + if (parameters == null) + return decl; + FromAttributeParameterList(parameters, decl.Parameters); + return decl; + } + + internal static void FromAttributeParameterList(XElement parameters, List outlist) + { + foreach (var parameterElem in parameters.Elements("attributeparameter")) + { + var parameter = AttributeParameter.FromXElement(parameterElem); + outlist.Add(parameter); + } + } + + public static AttributeParameter DuplicateOf(AttributeParameter other) + { + switch (other.Kind) + { + case AttributeParameterKind.Label: + return new AttributeParameterLabel((AttributeParameterLabel)other); + case AttributeParameterKind.Literal: + return new AttributeParameterLiteral((AttributeParameterLiteral)other); + case AttributeParameterKind.Sublist: + return new AttributeParameterSublist((AttributeParameterSublist)other); + case AttributeParameterKind.Unknown: + return new AttributeParameter(); + default: + throw new ArgumentOutOfRangeException(nameof(other), other.Kind.ToString()); + } + } + + public NamedTypeSpec AttributeType { get; private set; } + public string Name + { + get + { + return AttributeType.ToString(true); + } + private set + { + Exceptions.ThrowOnNull(value, nameof(value)); + var ts = TypeSpecParser.Parse(value); + if (ts is NamedTypeSpec named) + AttributeType = named; + else + throw new ArgumentOutOfRangeException($"TypeSpec for {value} is a {ts.Kind} and not a named type spec"); + } + } + public List Parameters { get; private set; } + } + + public class AttributeParameter + { + public static AttributeParameter FromXElement(XElement elem) + { + switch (elem.Attribute("kind").Value) + { + case "Label": + return new AttributeParameterLabel(elem.Attribute("Value").Value); + case "Literal": + return new AttributeParameterLiteral(elem.Attribute("Value").Value); + case "Sublist": + return AttributeParameterSublist.SublistFromXElement(elem); + default: + return new AttributeParameter(); + } + } + + public virtual AttributeParameterKind Kind => AttributeParameterKind.Unknown; + } + + public class AttributeParameterLabel : AttributeParameter + { + public AttributeParameterLabel(string label) + { + Label = Exceptions.ThrowOnNull(label, nameof(label)); + } + + public AttributeParameterLabel(AttributeParameterLabel other) + : this(other.Label) + { + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Label; + public string Label { get; private set; } + } + + public class AttributeParameterLiteral : AttributeParameter + { + public AttributeParameterLiteral(string literal) + { + Literal = Exceptions.ThrowOnNull(literal, nameof(literal)); + } + + public AttributeParameterLiteral(AttributeParameterLiteral other) + : this(other.Literal) + { + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Literal; + public string Literal { get; private set; } + } + + public class AttributeParameterSublist : AttributeParameter + { + public AttributeParameterSublist() + { + Parameters = new List(); + } + + public AttributeParameterSublist(AttributeParameterSublist other) + : this() + { + Parameters.AddRange(other.Parameters.Select(prm => AttributeDeclaration.DuplicateOf(prm))); + } + + public static AttributeParameterSublist SublistFromXElement(XElement elem) + { + var sublist = new AttributeParameterSublist(); + var parameters = elem.Element("attributeparameterlist"); + if (parameters == null) + return sublist; + AttributeDeclaration.FromAttributeParameterList(parameters, sublist.Parameters); + return sublist; + } + + public override AttributeParameterKind Kind => AttributeParameterKind.Sublist; + public List Parameters { get; private set; } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs index c81105ef9b69..0285359cb764 100644 --- a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs +++ b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs @@ -6,185 +6,237 @@ using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class BaseConstraint : IXElementConvertible { - protected BaseConstraint (ConstraintKind kind) - { - Kind = kind; - } - public ConstraintKind Kind { get; private set; } +namespace SwiftReflector.SwiftXmlReflection +{ + public class BaseConstraint : IXElementConvertible + { + protected BaseConstraint(ConstraintKind kind) + { + Kind = kind; + } + public ConstraintKind Kind { get; private set; } - public static BaseConstraint FromXElement (TypeAliasFolder folder, XElement elem) - { - if (elem == null) - return null; - if ((string)elem.Attribute ("relationship") == "inherits") { - return new InheritanceConstraint ((string)elem.Attribute ("name"), (string)elem.Attribute ("from"), folder); - } else { - return new EqualityConstraint ((string)elem.Attribute ("firsttype"), (string)elem.Attribute ("secondtype"), folder); - } - } + public static BaseConstraint FromXElement(TypeAliasFolder folder, XElement elem) + { + if (elem == null) + return null; + if ((string)elem.Attribute("relationship") == "inherits") + { + return new InheritanceConstraint((string)elem.Attribute("name"), (string)elem.Attribute("from"), folder); + } + else + { + return new EqualityConstraint((string)elem.Attribute("firsttype"), (string)elem.Attribute("secondtype"), folder); + } + } - public XElement ToXElement () - { - var inh = this as InheritanceConstraint; - if (inh != null) { - return new XElement ("where", new XAttribute ("relationship", "inherits"), - new XAttribute ("name", inh.Name), - new XAttribute ("from", inh.Inherits)); - } else { - var eq = (EqualityConstraint)this; - return new XElement ("where", new XAttribute ("relationship", "equals"), - new XAttribute ("firsttype", eq.Type1), - new XAttribute ("secondtype", eq.Type2)); - } - } + public XElement ToXElement() + { + var inh = this as InheritanceConstraint; + if (inh != null) + { + return new XElement("where", new XAttribute("relationship", "inherits"), + new XAttribute("name", inh.Name), + new XAttribute("from", inh.Inherits)); + } + else + { + var eq = (EqualityConstraint)this; + return new XElement("where", new XAttribute("relationship", "equals"), + new XAttribute("firsttype", eq.Type1), + new XAttribute("secondtype", eq.Type2)); + } + } - internal string EffectiveTypeName () - { - var inh = this as InheritanceConstraint; - if (inh != null) - return inh.Name; - var eq = (EqualityConstraint)this; - string [] pieces = eq.Type1.Split ('.'); - // T, T.U - if (pieces.Length == 1 || pieces.Length == 2) { - return pieces [0]; - } - // Module.T.U - else if (pieces.Length > 2) { - return pieces [1]; - } - return null; - } + internal string EffectiveTypeName() + { + var inh = this as InheritanceConstraint; + if (inh != null) + return inh.Name; + var eq = (EqualityConstraint)this; + string[] pieces = eq.Type1.Split('.'); + // T, T.U + if (pieces.Length == 1 || pieces.Length == 2) + { + return pieces[0]; + } + // Module.T.U + else if (pieces.Length > 2) + { + return pieces[1]; + } + return null; + } - public static BaseConstraint CopyOf (BaseConstraint baseConstraint) - { - if (baseConstraint is InheritanceConstraint inh) { - return new InheritanceConstraint (inh.Name, inh.Inherits); + public static BaseConstraint CopyOf(BaseConstraint baseConstraint) + { + if (baseConstraint is InheritanceConstraint inh) + { + return new InheritanceConstraint(inh.Name, inh.Inherits); - } else if (baseConstraint is EqualityConstraint eq) { - return new EqualityConstraint (eq.Type1, eq.Type2); - } - throw new NotImplementedException ($"Unknown constraint type {baseConstraint.GetType ().Name}"); - } - } + } + else if (baseConstraint is EqualityConstraint eq) + { + return new EqualityConstraint(eq.Type1, eq.Type2); + } + throw new NotImplementedException($"Unknown constraint type {baseConstraint.GetType().Name}"); + } + } - public class InheritanceConstraint : BaseConstraint { - public InheritanceConstraint (string name, string inheritsTypeSpecString, TypeAliasFolder folder = null) - : base (ConstraintKind.Inherits) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - Inherits = inheritsTypeSpecString; - if (folder != null) - InheritsTypeSpec = folder.FoldAlias (null, InheritsTypeSpec); - } + public class InheritanceConstraint : BaseConstraint + { + public InheritanceConstraint(string name, string inheritsTypeSpecString, TypeAliasFolder folder = null) + : base(ConstraintKind.Inherits) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + Inherits = inheritsTypeSpecString; + if (folder != null) + InheritsTypeSpec = folder.FoldAlias(null, InheritsTypeSpec); + } - public InheritanceConstraint (string name, TypeSpec inheritsTypeSpecString) - : this (name, inheritsTypeSpecString.ToString ()) - { + public InheritanceConstraint(string name, TypeSpec inheritsTypeSpecString) + : this(name, inheritsTypeSpecString.ToString()) + { - } + } - public string Name { get; private set; } - string inheritsStr; - TypeSpec inheritsSpec; - public string Inherits { - get { - return inheritsStr; - } - set { - inheritsStr = value; - if (value != null) { - inheritsSpec = TypeSpecParser.Parse (value); - } else { - inheritsSpec = null; - } - } - } - public TypeSpec InheritsTypeSpec { - get { - return inheritsSpec; - } - set { - inheritsSpec = value; - if (value != null) { - inheritsStr = value.ToString (); - } else { - inheritsStr = null; - } - } - } - } + public string Name { get; private set; } + string inheritsStr; + TypeSpec inheritsSpec; + public string Inherits + { + get + { + return inheritsStr; + } + set + { + inheritsStr = value; + if (value != null) + { + inheritsSpec = TypeSpecParser.Parse(value); + } + else + { + inheritsSpec = null; + } + } + } + public TypeSpec InheritsTypeSpec + { + get + { + return inheritsSpec; + } + set + { + inheritsSpec = value; + if (value != null) + { + inheritsStr = value.ToString(); + } + else + { + inheritsStr = null; + } + } + } + } - public class EqualityConstraint : BaseConstraint { - public EqualityConstraint (string type1, string type2, TypeAliasFolder folder = null) - : base (ConstraintKind.Equal) - { - Type1 = type1; - Type2 = type2; - if (folder != null) { - Type1Spec = folder.FoldAlias (null, Type1Spec); - Type2Spec = folder.FoldAlias (null, Type2Spec); - } - } - string type1Str; - TypeSpec type1Spec; - public string Type1 { - get { - return type1Str; - } - set { - type1Str = value; - if (value != null) { - type1Spec = TypeSpecParser.Parse (value); - } else { - type1Spec = null; - } - } - } - public TypeSpec Type1Spec { - get { - return type1Spec; - } - set { - type1Spec = value; - if (value != null) { - type1Str = value.ToString (); - } else { - type1Str = null; - } - } - } - string type2Str; - TypeSpec type2Spec; - public string Type2 { - get { - return type2Str; - } - set { - type2Str = value; - if (value != null) { - type2Spec = TypeSpecParser.Parse (value); - } else { - type2Spec = null; - } - } - } - public TypeSpec Type2Spec { - get { - return type2Spec; - } - set { - type2Spec = value; - if (value != null) { - type2Str = value.ToString (); - } else { - type2Str = null; - } - } - } + public class EqualityConstraint : BaseConstraint + { + public EqualityConstraint(string type1, string type2, TypeAliasFolder folder = null) + : base(ConstraintKind.Equal) + { + Type1 = type1; + Type2 = type2; + if (folder != null) + { + Type1Spec = folder.FoldAlias(null, Type1Spec); + Type2Spec = folder.FoldAlias(null, Type2Spec); + } + } + string type1Str; + TypeSpec type1Spec; + public string Type1 + { + get + { + return type1Str; + } + set + { + type1Str = value; + if (value != null) + { + type1Spec = TypeSpecParser.Parse(value); + } + else + { + type1Spec = null; + } + } + } + public TypeSpec Type1Spec + { + get + { + return type1Spec; + } + set + { + type1Spec = value; + if (value != null) + { + type1Str = value.ToString(); + } + else + { + type1Str = null; + } + } + } + string type2Str; + TypeSpec type2Spec; + public string Type2 + { + get + { + return type2Str; + } + set + { + type2Str = value; + if (value != null) + { + type2Spec = TypeSpecParser.Parse(value); + } + else + { + type2Spec = null; + } + } + } + public TypeSpec Type2Spec + { + get + { + return type2Spec; + } + set + { + type2Spec = value; + if (value != null) + { + type2Str = value.ToString(); + } + else + { + type2Str = null; + } + } + } - } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs index d5b2dc0c64b7..e7b68c39063e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs @@ -9,553 +9,618 @@ using SwiftReflector.ExceptionTools; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftXmlReflection { - public class BaseDeclaration { - protected BaseDeclaration () - { - Generics = new GenericDeclarationCollection (); - Attributes = new List (); - } - - protected BaseDeclaration (BaseDeclaration other) - { - Name = other.Name; - Access = other.Access; - Module = other.Module; - Parent = other.Parent; - ParentExtension = other.ParentExtension; - Generics = new GenericDeclarationCollection (); - Attributes = new List (); - } - - public string Name { get; set; } - public Accessibility Access { get; set; } - public ModuleDeclaration Module { get; set; } - public BaseDeclaration Parent { get; set; } - public GenericDeclarationCollection Generics { get; private set; } - public ExtensionDeclaration ParentExtension { get; set; } - public bool IsExtension { get { return ParentExtension != null; } } - public bool ContainsGenericParameters { - get { - return Generics.Count () > 0; - } - } - public List Attributes { get; private set; } - - public bool IsTypeSpecBoundGeneric (TypeSpec sp) - { - if (sp.ContainsGenericParameters) { - foreach (var gen in sp.GenericParameters) { - if (IsTypeSpecGeneric (gen)) - return false; - } - return true; - } - return false; - } - - public bool IsTypeSpecAssociatedType (NamedTypeSpec named) - { - var proto = ThisOrParentProtocol (this); - if (proto == null) - return false; - if (named.ContainsGenericParameters) { - foreach (var gen in named.GenericParameters) { - if (gen is NamedTypeSpec namedGen && IsTypeSpecAssociatedType (namedGen)) - return true; - } - } - return proto.AssociatedTypeNamed (named.NameWithoutModule) != null; - } - - public bool IsNested => this is TypeDeclaration && Parent != null; - - public ProtocolDeclaration GetConstrainedProtocolWithAssociatedType (NamedTypeSpec named, TypeMapper typeMapper) - { - var depthIndex = GetGenericDepthAndIndex (named); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - return null; - var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); - if (genDecl == null) - return null; - if (genDecl.Constraints.Count != 1) - return null; - var inheritance = genDecl.Constraints [0] as InheritanceConstraint; - if (inheritance == null) - return null; - var entity = typeMapper.GetEntityForTypeSpec (inheritance.InheritsTypeSpec); - if (entity == null) - return null; - var proto = entity.Type as ProtocolDeclaration; - if (proto == null || !proto.HasAssociatedTypes) - return null; - return proto; - } - - public AssociatedTypeDeclaration AssociatedTypeDeclarationFromNamedTypeSpec (NamedTypeSpec named) - { - var proto = ThisOrParentProtocol (this); - return proto.AssociatedTypeNamed (named.NameWithoutModule); - } - - public ProtocolDeclaration AsProtocolOrParentAsProtocol () - { - return ThisOrParentProtocol (this); - } - - public BaseDeclaration AsTypeDeclaration () - { - return ThisOrParentTypeDeclaration (this); - } - - static ProtocolDeclaration ThisOrParentProtocol (BaseDeclaration self) - { - if (self == null) - return null; - - do { - if (self is ProtocolDeclaration decl) - return decl; - self = self.Parent; - } while (self != null); - return null; - } - - static TypeDeclaration ThisOrParentTypeDeclaration (BaseDeclaration self) - { - if (self == null) - return null; - - do { - if (self is TypeDeclaration decl) - return decl; - self = self.Parent; - } while (self != null); - return null; - } - - - public bool IsProtocolWithAssociatedTypesFullPath (NamedTypeSpec named, TypeMapper typeMap) - { - if (named == null) - return false; - return OwningProtocolFromGenericWithFullPath (named, typeMap) != null; - } - - public ProtocolDeclaration OwningProtocolFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap) - { - AssociatedTypeDeclaration assoc = null; - return OwningProtocolAndAssociateTypeFromGenericWithFullPath (named, typeMap, out assoc); - } - - public AssociatedTypeDeclaration AssociatedTypeDeclarationFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap) - { - AssociatedTypeDeclaration assoc = null; - OwningProtocolAndAssociateTypeFromGenericWithFullPath (named, typeMap, out assoc); - return assoc; - } - - ProtocolDeclaration OwningProtocolAndAssociateTypeFromGenericWithFullPath (NamedTypeSpec named, TypeMapper typeMap, out AssociatedTypeDeclaration assoc) - { - assoc = null; - if (named.Name.Contains (".")) { - var parts = named.Name.Split ('.'); - if (IsTypeSpecGeneric (parts [0])) { - // I make assertions about why things can't happen. Here's why: - // If we have func foo(a:T b:T.Foo) - // it means that if the T part of T.Foo is a generic, then T HAS to be - // constrained to a protocol with associated types - // If T.Foo is a path to an associated type, then it - var depthIndex = GetGenericDepthAndIndex (parts [0]); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - return null; - var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); - if (genDecl.Constraints.Count != 1) // pretty sure this can't ever happen - return null; - var inh = genDecl.Constraints [0] as InheritanceConstraint; - if (inh == null) // pretty sure this also can't ever happen - return null; - var entity = typeMap.GetEntityForTypeSpec (inh.InheritsTypeSpec); - if (entity == null) // Also can't happen - return null; - if (entity.EntityType != EntityType.Protocol) - return null; // Also can't happen - var protocol = entity.Type as ProtocolDeclaration; - if (protocol != null && protocol.HasAssociatedTypes && (assoc = protocol.AssociatedTypeNamed (parts [1])) != null) { - return protocol; - } - } - } - return null; - } - - public ProtocolDeclaration OwningProtocolFromConstrainedGeneric (NamedTypeSpec named, TypeMapper typeMap) - { - var depthIndex = GetGenericDepthAndIndex (named); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - return null; - var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); - return OwningProtocolFromConstrainedGeneric (genDecl, typeMap); - } - - public ProtocolDeclaration OwningProtocolFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) - { - var refProto = RefProtoFromConstrainedGeneric (generic, typeMap); - return refProto?.Protocol; - } - - public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric (NamedTypeSpec named, TypeMapper typeMap) - { - var depthIndex = GetGenericDepthAndIndex (named); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - return null; - var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); - return AssociatedTypeDeclarationFromConstrainedGeneric (genDecl, typeMap); - } - - public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) - { - // looking for where U == T.At1[.At2...] - if (generic.Constraints.Count != 1) - return null; - var eqConstraint = generic.Constraints [0] as EqualityConstraint; - if (eqConstraint == null) - return null; - var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; - if (namedSpec == null) - return null; - var parts = namedSpec.Name.Split ('.'); - if (parts.Length <= 1) - return null; - if (!IsTypeSpecGeneric (parts [0])) - return null; - var refProto = GetConstrainedAssociatedTypeProtocol (new NamedTypeSpec (parts [0]), typeMap); - if (refProto == null) - return null; - if (parts.Length > 2) - throw new NotImplementedException ($"Not currently supporting equality constraints of nested associated types (yet) {eqConstraint.Type1} == {eqConstraint.Type2}"); - return refProto.Protocol.AssociatedTypeNamed (parts [1]); - } - - public GenericReferenceAssociatedTypeProtocol RefProtoFromConstrainedGeneric (GenericDeclaration generic, TypeMapper typeMap) - { - // looking for where U == T.At1[.At2...] - if (generic.Constraints.Count != 1) - return null; - var eqConstraint = generic.Constraints [0] as EqualityConstraint; - if (eqConstraint == null) - return null; - var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; - if (namedSpec == null) - return null; - var parts = namedSpec.Name.Split ('.'); - if (parts.Length <= 1) - return null; - if (!IsTypeSpecGeneric (parts [0])) - return null; - return GetConstrainedAssociatedTypeProtocol (new NamedTypeSpec (parts [0]), typeMap); - } - - public bool IsEqualityConstrainedByAssociatedType (NamedTypeSpec name, TypeMapper typeMap) - { - var depthIndex = GetGenericDepthAndIndex (name); - if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) - return false; - var genDecl = GetGeneric (depthIndex.Item1, depthIndex.Item2); - return IsEqualityConstrainedByAssociatedType (genDecl, typeMap); - } - - public bool IsEqualityConstrainedByAssociatedType (GenericDeclaration generic, TypeMapper typeMap) - { - return AssociatedTypeDeclarationFromConstrainedGeneric (generic, typeMap) != null; - } - - public GenericReferenceAssociatedTypeProtocol GetConstrainedAssociatedTypeProtocol (NamedTypeSpec spec, TypeMapper typeMap) - { - // we're looking for the pattern T, where T is a generic or contains a generic (Foo) - // and there exists a where T : SomeProtocol - if (spec == null) - return null; - GenericReferenceAssociatedTypeProtocol result = null; - if (spec.ContainsGenericParameters) { - foreach (var gen in spec.GenericParameters) { - // recurse on generic element - result = GetConstrainedAssociatedTypeProtocol (gen as NamedTypeSpec, typeMap); - if (result != null) - break; - } - } else { - // which declaration has this generic - var owningContext = FindOwningContext (this, spec); - if (owningContext != null) { - foreach (var genPart in Generics) { - if (genPart.Name != spec.Name) - continue; - // genPart is the one we care about - now look for a constraint. - foreach (var constraint in genPart.Constraints) { - // Is it inheritance? - if (constraint is InheritanceConstraint inheritance) { - // Find the entity in the database - var entity = typeMap.TypeDatabase.EntityForSwiftName (inheritance.Inherits); - // Is it a protocol and it has associated types - if (entity != null && entity.Type is ProtocolDeclaration proto && (proto.HasAssociatedTypes || proto.HasDynamicSelfInArguments)) - result = new GenericReferenceAssociatedTypeProtocol () { - GenericPart = spec, - Protocol = proto - }; - } - } - if (result != null) - break; - } - } - } - return result; - } - - static BaseDeclaration FindOwningContext (BaseDeclaration context, NamedTypeSpec spec) - { - while (context != null) { - foreach (var genPart in context.Generics) { - if (genPart.Name == spec.Name) - return context; - } - context = context.Parent; - } - return null; - } - - public bool IsTypeSpecGeneric (TypeSpec sp) - { - if (sp.ContainsGenericParameters) { - foreach (var gen in sp.GenericParameters) { - if (IsTypeSpecGeneric (gen)) - return true; - } - } - - if (sp is NamedTypeSpec named) { - return IsTypeSpecGeneric (named.Name); - } else if (sp is ClosureTypeSpec closure) { - return IsTypeSpecGeneric (closure.Arguments) || IsTypeSpecGeneric (closure.ReturnType); - } else if (sp is TupleTypeSpec tuple) { - foreach (var tupSpec in tuple.Elements) { - if (IsTypeSpecGeneric (tupSpec)) - return true; - } - return false; - } else if (sp is ProtocolListTypeSpec) { - // protocol list type specs can't be generic. - return false; - } else { - throw new NotImplementedException ($"Unknown TypeSpec type {sp.GetType ().Name}"); - } - } - - public bool IsTypeSpecGenericReference (TypeSpec sp) - { - if (sp.ContainsGenericParameters) - return false; - var ns = sp as NamedTypeSpec; - return ns != null && IsTypeSpecGeneric (ns.Name); - } - - public bool IsTypeSpecGenericMetatypeReference (TypeSpec sp) - { - if (sp.ContainsGenericParameters) - return false; - string notUsed; - return sp is NamedTypeSpec ns && IsTypeSpecGenericMetatypeReference (ns.Name, out notUsed); - } - - public bool IsTypeSpecGenericMetatypeReference (string typeSpecName, out string genericPart) - { - if (typeSpecName.Contains ('.')) { - var parts = typeSpecName.Split ('.'); - if (parts.Length == 2 && parts [1] == "Type") { - genericPart = parts [0]; - return true; - } - } - genericPart = null; - return false; - } - - public bool IsTypeSpecGeneric (string typeSpecName) - { - string genericPart; - if (IsTypeSpecGenericMetatypeReference (typeSpecName, out genericPart)) { - return IsTypeSpecGeneric (genericPart); - } else { - foreach (GenericDeclaration gendecl in Generics) { - if (typeSpecName == gendecl.Name) - return true; - } - if (Parent != null) { - return Parent.IsTypeSpecGeneric (typeSpecName); - } else { - return false; - } - } - } - - public int GetTotalDepth () - { - int depth = 0; - BaseDeclaration bd = this; - while (bd.Parent != null) { - if (Parent.ContainsGenericParameters) - depth++; - bd = bd.Parent; - } - return depth; - } - - public Tuple GetGenericDepthAndIndex (string name) - { - return GetGenericDepthAndIndex (name, GetTotalDepth ()); - } - - public Tuple GetGenericDepthAndIndex (TypeSpec spec) - { - var ns = spec as NamedTypeSpec; - if (ns == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 5, $"Can't get generic depth from a {spec.GetType ().Name}."); - return GetGenericDepthAndIndex (ns.Name); - } - - Tuple GetGenericDepthAndIndex (string name, int depth) - { - string genericPart; - if (IsTypeSpecGenericMetatypeReference (name, out genericPart)) { - return GetGenericDepthAndIndex (genericPart, depth); - } else { - for (int i = 0; i < Generics.Count; i++) { - if (Generics [i].Name == name) - return new Tuple (depth, i); - } - if (Parent != null) { - return Parent.GetGenericDepthAndIndex (name, depth - 1); - } - return new Tuple (-1, -1); - } - } - - public GenericDeclaration GetGeneric (int depth, int index) - { - var parentsToWalk = GetMaxDepth () - depth; - BaseDeclaration decl = this; - do { - // skip runs of no generics - while (!decl.ContainsGenericParameters) { - decl = decl.Parent; - } - if (parentsToWalk > 0) { - parentsToWalk--; - decl = decl.Parent; - } - } while (parentsToWalk > 0); - return decl.Generics [index]; - } - - - int GetMaxDepth (int depth) - { - depth += (ContainsGenericParameters ? 1 : 0); - if (Parent == null) - return depth; - return Parent.GetMaxDepth (depth); - } - - public int GetMaxDepth() - { - return GetMaxDepth (-1); - } - - public bool IsPublicOrOpen { - get { - return Access == Accessibility.Public || Access == Accessibility.Open; - } - } - - - public static BaseDeclaration FromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) - { - var generics = GenericDeclaration.FromXElement (folder, elem.Element ("genericparameters")); - BaseDeclaration decl = null; - switch (elem.Name.ToString ()) { - case "func": - decl = FunctionDeclaration.FuncFromXElement (folder, elem, module, parent); - break; - case "typedeclaration": - decl = TypeDeclaration.TypeFromXElement (folder, elem, module, parent); - break; - case "property": - decl = PropertyDeclaration.PropFromXElement (folder, elem, module, parent); - break; - default: - decl = new BaseDeclaration { - Name = (string)elem.Attribute ("name"), - Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")) - }; - break; - } - decl.Generics.AddRange (generics); - decl.Attributes.AddRange (AttributesFromXElement (elem.Element ("attributes"))); - return decl; - } - - internal static IEnumerable AttributesFromXElement (XElement elem) - { - if (elem == null) - return Enumerable.Empty (); - return elem.Elements ("attribute").Select (attr => AttributeDeclaration.FromXElement (attr)); - } - - public virtual string ToFullyQualifiedName (bool includeModule = true) - { - var sb = new StringBuilder (); - BaseDeclaration decl = this; - // recursion? We don't need to stinking recursion! - while (decl != null) { - TypeDeclaration typeDecl = decl as TypeDeclaration; - // unrooted types have no parent, but do have a fully qualified name - if (typeDecl != null && typeDecl.IsUnrooted) { - sb.Insert (0, typeDecl.ToFullyQualifiedName (false)); - break; - } else { - sb.Insert (0, decl.Name); - decl = decl.Parent; - if (decl != null) - sb.Insert (0, '.'); - } - } - if (includeModule) { - sb.Insert (0, '.').Insert (0, Module.Name); - } - return sb.ToString (); - } - - public virtual string ToFullyQualifiedNameWithGenerics () - { - var sb = new StringBuilder (ToFullyQualifiedName ()); - if (ContainsGenericParameters) { - sb.Append ("<"); - for (int i = 0; i < Generics.Count; i++) { - if (i > 0) - sb.Append (", "); - sb.Append (Generics [i].Name); - } - sb.Append (">"); - } - return sb.ToString (); - } - - public override string ToString () - { - return ToFullyQualifiedNameWithGenerics (); - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class BaseDeclaration + { + protected BaseDeclaration() + { + Generics = new GenericDeclarationCollection(); + Attributes = new List(); + } + + protected BaseDeclaration(BaseDeclaration other) + { + Name = other.Name; + Access = other.Access; + Module = other.Module; + Parent = other.Parent; + ParentExtension = other.ParentExtension; + Generics = new GenericDeclarationCollection(); + Attributes = new List(); + } + + public string Name { get; set; } + public Accessibility Access { get; set; } + public ModuleDeclaration Module { get; set; } + public BaseDeclaration Parent { get; set; } + public GenericDeclarationCollection Generics { get; private set; } + public ExtensionDeclaration ParentExtension { get; set; } + public bool IsExtension { get { return ParentExtension != null; } } + public bool ContainsGenericParameters + { + get + { + return Generics.Count() > 0; + } + } + public List Attributes { get; private set; } + + public bool IsTypeSpecBoundGeneric(TypeSpec sp) + { + if (sp.ContainsGenericParameters) + { + foreach (var gen in sp.GenericParameters) + { + if (IsTypeSpecGeneric(gen)) + return false; + } + return true; + } + return false; + } + + public bool IsTypeSpecAssociatedType(NamedTypeSpec named) + { + var proto = ThisOrParentProtocol(this); + if (proto == null) + return false; + if (named.ContainsGenericParameters) + { + foreach (var gen in named.GenericParameters) + { + if (gen is NamedTypeSpec namedGen && IsTypeSpecAssociatedType(namedGen)) + return true; + } + } + return proto.AssociatedTypeNamed(named.NameWithoutModule) != null; + } + + public bool IsNested => this is TypeDeclaration && Parent != null; + + public ProtocolDeclaration GetConstrainedProtocolWithAssociatedType(NamedTypeSpec named, TypeMapper typeMapper) + { + var depthIndex = GetGenericDepthAndIndex(named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric(depthIndex.Item1, depthIndex.Item2); + if (genDecl == null) + return null; + if (genDecl.Constraints.Count != 1) + return null; + var inheritance = genDecl.Constraints[0] as InheritanceConstraint; + if (inheritance == null) + return null; + var entity = typeMapper.GetEntityForTypeSpec(inheritance.InheritsTypeSpec); + if (entity == null) + return null; + var proto = entity.Type as ProtocolDeclaration; + if (proto == null || !proto.HasAssociatedTypes) + return null; + return proto; + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromNamedTypeSpec(NamedTypeSpec named) + { + var proto = ThisOrParentProtocol(this); + return proto.AssociatedTypeNamed(named.NameWithoutModule); + } + + public ProtocolDeclaration AsProtocolOrParentAsProtocol() + { + return ThisOrParentProtocol(this); + } + + public BaseDeclaration AsTypeDeclaration() + { + return ThisOrParentTypeDeclaration(this); + } + + static ProtocolDeclaration ThisOrParentProtocol(BaseDeclaration self) + { + if (self == null) + return null; + + do + { + if (self is ProtocolDeclaration decl) + return decl; + self = self.Parent; + } while (self != null); + return null; + } + + static TypeDeclaration ThisOrParentTypeDeclaration(BaseDeclaration self) + { + if (self == null) + return null; + + do + { + if (self is TypeDeclaration decl) + return decl; + self = self.Parent; + } while (self != null); + return null; + } + + + public bool IsProtocolWithAssociatedTypesFullPath(NamedTypeSpec named, TypeMapper typeMap) + { + if (named == null) + return false; + return OwningProtocolFromGenericWithFullPath(named, typeMap) != null; + } + + public ProtocolDeclaration OwningProtocolFromGenericWithFullPath(NamedTypeSpec named, TypeMapper typeMap) + { + AssociatedTypeDeclaration assoc = null; + return OwningProtocolAndAssociateTypeFromGenericWithFullPath(named, typeMap, out assoc); + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromGenericWithFullPath(NamedTypeSpec named, TypeMapper typeMap) + { + AssociatedTypeDeclaration assoc = null; + OwningProtocolAndAssociateTypeFromGenericWithFullPath(named, typeMap, out assoc); + return assoc; + } + + ProtocolDeclaration OwningProtocolAndAssociateTypeFromGenericWithFullPath(NamedTypeSpec named, TypeMapper typeMap, out AssociatedTypeDeclaration assoc) + { + assoc = null; + if (named.Name.Contains(".")) + { + var parts = named.Name.Split('.'); + if (IsTypeSpecGeneric(parts[0])) + { + // I make assertions about why things can't happen. Here's why: + // If we have func foo(a:T b:T.Foo) + // it means that if the T part of T.Foo is a generic, then T HAS to be + // constrained to a protocol with associated types + // If T.Foo is a path to an associated type, then it + var depthIndex = GetGenericDepthAndIndex(parts[0]); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric(depthIndex.Item1, depthIndex.Item2); + if (genDecl.Constraints.Count != 1) // pretty sure this can't ever happen + return null; + var inh = genDecl.Constraints[0] as InheritanceConstraint; + if (inh == null) // pretty sure this also can't ever happen + return null; + var entity = typeMap.GetEntityForTypeSpec(inh.InheritsTypeSpec); + if (entity == null) // Also can't happen + return null; + if (entity.EntityType != EntityType.Protocol) + return null; // Also can't happen + var protocol = entity.Type as ProtocolDeclaration; + if (protocol != null && protocol.HasAssociatedTypes && (assoc = protocol.AssociatedTypeNamed(parts[1])) != null) + { + return protocol; + } + } + } + return null; + } + + public ProtocolDeclaration OwningProtocolFromConstrainedGeneric(NamedTypeSpec named, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex(named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric(depthIndex.Item1, depthIndex.Item2); + return OwningProtocolFromConstrainedGeneric(genDecl, typeMap); + } + + public ProtocolDeclaration OwningProtocolFromConstrainedGeneric(GenericDeclaration generic, TypeMapper typeMap) + { + var refProto = RefProtoFromConstrainedGeneric(generic, typeMap); + return refProto?.Protocol; + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric(NamedTypeSpec named, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex(named); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return null; + var genDecl = GetGeneric(depthIndex.Item1, depthIndex.Item2); + return AssociatedTypeDeclarationFromConstrainedGeneric(genDecl, typeMap); + } + + public AssociatedTypeDeclaration AssociatedTypeDeclarationFromConstrainedGeneric(GenericDeclaration generic, TypeMapper typeMap) + { + // looking for where U == T.At1[.At2...] + if (generic.Constraints.Count != 1) + return null; + var eqConstraint = generic.Constraints[0] as EqualityConstraint; + if (eqConstraint == null) + return null; + var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; + if (namedSpec == null) + return null; + var parts = namedSpec.Name.Split('.'); + if (parts.Length <= 1) + return null; + if (!IsTypeSpecGeneric(parts[0])) + return null; + var refProto = GetConstrainedAssociatedTypeProtocol(new NamedTypeSpec(parts[0]), typeMap); + if (refProto == null) + return null; + if (parts.Length > 2) + throw new NotImplementedException($"Not currently supporting equality constraints of nested associated types (yet) {eqConstraint.Type1} == {eqConstraint.Type2}"); + return refProto.Protocol.AssociatedTypeNamed(parts[1]); + } + + public GenericReferenceAssociatedTypeProtocol RefProtoFromConstrainedGeneric(GenericDeclaration generic, TypeMapper typeMap) + { + // looking for where U == T.At1[.At2...] + if (generic.Constraints.Count != 1) + return null; + var eqConstraint = generic.Constraints[0] as EqualityConstraint; + if (eqConstraint == null) + return null; + var namedSpec = eqConstraint.Type2Spec as NamedTypeSpec; + if (namedSpec == null) + return null; + var parts = namedSpec.Name.Split('.'); + if (parts.Length <= 1) + return null; + if (!IsTypeSpecGeneric(parts[0])) + return null; + return GetConstrainedAssociatedTypeProtocol(new NamedTypeSpec(parts[0]), typeMap); + } + + public bool IsEqualityConstrainedByAssociatedType(NamedTypeSpec name, TypeMapper typeMap) + { + var depthIndex = GetGenericDepthAndIndex(name); + if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0) + return false; + var genDecl = GetGeneric(depthIndex.Item1, depthIndex.Item2); + return IsEqualityConstrainedByAssociatedType(genDecl, typeMap); + } + + public bool IsEqualityConstrainedByAssociatedType(GenericDeclaration generic, TypeMapper typeMap) + { + return AssociatedTypeDeclarationFromConstrainedGeneric(generic, typeMap) != null; + } + + public GenericReferenceAssociatedTypeProtocol GetConstrainedAssociatedTypeProtocol(NamedTypeSpec spec, TypeMapper typeMap) + { + // we're looking for the pattern T, where T is a generic or contains a generic (Foo) + // and there exists a where T : SomeProtocol + if (spec == null) + return null; + GenericReferenceAssociatedTypeProtocol result = null; + if (spec.ContainsGenericParameters) + { + foreach (var gen in spec.GenericParameters) + { + // recurse on generic element + result = GetConstrainedAssociatedTypeProtocol(gen as NamedTypeSpec, typeMap); + if (result != null) + break; + } + } + else + { + // which declaration has this generic + var owningContext = FindOwningContext(this, spec); + if (owningContext != null) + { + foreach (var genPart in Generics) + { + if (genPart.Name != spec.Name) + continue; + // genPart is the one we care about - now look for a constraint. + foreach (var constraint in genPart.Constraints) + { + // Is it inheritance? + if (constraint is InheritanceConstraint inheritance) + { + // Find the entity in the database + var entity = typeMap.TypeDatabase.EntityForSwiftName(inheritance.Inherits); + // Is it a protocol and it has associated types + if (entity != null && entity.Type is ProtocolDeclaration proto && (proto.HasAssociatedTypes || proto.HasDynamicSelfInArguments)) + result = new GenericReferenceAssociatedTypeProtocol() + { + GenericPart = spec, + Protocol = proto + }; + } + } + if (result != null) + break; + } + } + } + return result; + } + + static BaseDeclaration FindOwningContext(BaseDeclaration context, NamedTypeSpec spec) + { + while (context != null) + { + foreach (var genPart in context.Generics) + { + if (genPart.Name == spec.Name) + return context; + } + context = context.Parent; + } + return null; + } + + public bool IsTypeSpecGeneric(TypeSpec sp) + { + if (sp.ContainsGenericParameters) + { + foreach (var gen in sp.GenericParameters) + { + if (IsTypeSpecGeneric(gen)) + return true; + } + } + + if (sp is NamedTypeSpec named) + { + return IsTypeSpecGeneric(named.Name); + } + else if (sp is ClosureTypeSpec closure) + { + return IsTypeSpecGeneric(closure.Arguments) || IsTypeSpecGeneric(closure.ReturnType); + } + else if (sp is TupleTypeSpec tuple) + { + foreach (var tupSpec in tuple.Elements) + { + if (IsTypeSpecGeneric(tupSpec)) + return true; + } + return false; + } + else if (sp is ProtocolListTypeSpec) + { + // protocol list type specs can't be generic. + return false; + } + else + { + throw new NotImplementedException($"Unknown TypeSpec type {sp.GetType().Name}"); + } + } + + public bool IsTypeSpecGenericReference(TypeSpec sp) + { + if (sp.ContainsGenericParameters) + return false; + var ns = sp as NamedTypeSpec; + return ns != null && IsTypeSpecGeneric(ns.Name); + } + + public bool IsTypeSpecGenericMetatypeReference(TypeSpec sp) + { + if (sp.ContainsGenericParameters) + return false; + string notUsed; + return sp is NamedTypeSpec ns && IsTypeSpecGenericMetatypeReference(ns.Name, out notUsed); + } + + public bool IsTypeSpecGenericMetatypeReference(string typeSpecName, out string genericPart) + { + if (typeSpecName.Contains('.')) + { + var parts = typeSpecName.Split('.'); + if (parts.Length == 2 && parts[1] == "Type") + { + genericPart = parts[0]; + return true; + } + } + genericPart = null; + return false; + } + + public bool IsTypeSpecGeneric(string typeSpecName) + { + string genericPart; + if (IsTypeSpecGenericMetatypeReference(typeSpecName, out genericPart)) + { + return IsTypeSpecGeneric(genericPart); + } + else + { + foreach (GenericDeclaration gendecl in Generics) + { + if (typeSpecName == gendecl.Name) + return true; + } + if (Parent != null) + { + return Parent.IsTypeSpecGeneric(typeSpecName); + } + else + { + return false; + } + } + } + + public int GetTotalDepth() + { + int depth = 0; + BaseDeclaration bd = this; + while (bd.Parent != null) + { + if (Parent.ContainsGenericParameters) + depth++; + bd = bd.Parent; + } + return depth; + } + + public Tuple GetGenericDepthAndIndex(string name) + { + return GetGenericDepthAndIndex(name, GetTotalDepth()); + } + + public Tuple GetGenericDepthAndIndex(TypeSpec spec) + { + var ns = spec as NamedTypeSpec; + if (ns == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 5, $"Can't get generic depth from a {spec.GetType().Name}."); + return GetGenericDepthAndIndex(ns.Name); + } + + Tuple GetGenericDepthAndIndex(string name, int depth) + { + string genericPart; + if (IsTypeSpecGenericMetatypeReference(name, out genericPart)) + { + return GetGenericDepthAndIndex(genericPart, depth); + } + else + { + for (int i = 0; i < Generics.Count; i++) + { + if (Generics[i].Name == name) + return new Tuple(depth, i); + } + if (Parent != null) + { + return Parent.GetGenericDepthAndIndex(name, depth - 1); + } + return new Tuple(-1, -1); + } + } + + public GenericDeclaration GetGeneric(int depth, int index) + { + var parentsToWalk = GetMaxDepth() - depth; + BaseDeclaration decl = this; + do + { + // skip runs of no generics + while (!decl.ContainsGenericParameters) + { + decl = decl.Parent; + } + if (parentsToWalk > 0) + { + parentsToWalk--; + decl = decl.Parent; + } + } while (parentsToWalk > 0); + return decl.Generics[index]; + } + + + int GetMaxDepth(int depth) + { + depth += (ContainsGenericParameters ? 1 : 0); + if (Parent == null) + return depth; + return Parent.GetMaxDepth(depth); + } + + public int GetMaxDepth() + { + return GetMaxDepth(-1); + } + + public bool IsPublicOrOpen + { + get + { + return Access == Accessibility.Public || Access == Accessibility.Open; + } + } + + + public static BaseDeclaration FromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + var generics = GenericDeclaration.FromXElement(folder, elem.Element("genericparameters")); + BaseDeclaration decl = null; + switch (elem.Name.ToString()) + { + case "func": + decl = FunctionDeclaration.FuncFromXElement(folder, elem, module, parent); + break; + case "typedeclaration": + decl = TypeDeclaration.TypeFromXElement(folder, elem, module, parent); + break; + case "property": + decl = PropertyDeclaration.PropFromXElement(folder, elem, module, parent); + break; + default: + decl = new BaseDeclaration + { + Name = (string)elem.Attribute("name"), + Access = TypeDeclaration.AccessibilityFromString((string)elem.Attribute("accessibility")) + }; + break; + } + decl.Generics.AddRange(generics); + decl.Attributes.AddRange(AttributesFromXElement(elem.Element("attributes"))); + return decl; + } + + internal static IEnumerable AttributesFromXElement(XElement elem) + { + if (elem == null) + return Enumerable.Empty(); + return elem.Elements("attribute").Select(attr => AttributeDeclaration.FromXElement(attr)); + } + + public virtual string ToFullyQualifiedName(bool includeModule = true) + { + var sb = new StringBuilder(); + BaseDeclaration decl = this; + // recursion? We don't need to stinking recursion! + while (decl != null) + { + TypeDeclaration typeDecl = decl as TypeDeclaration; + // unrooted types have no parent, but do have a fully qualified name + if (typeDecl != null && typeDecl.IsUnrooted) + { + sb.Insert(0, typeDecl.ToFullyQualifiedName(false)); + break; + } + else + { + sb.Insert(0, decl.Name); + decl = decl.Parent; + if (decl != null) + sb.Insert(0, '.'); + } + } + if (includeModule) + { + sb.Insert(0, '.').Insert(0, Module.Name); + } + return sb.ToString(); + } + + public virtual string ToFullyQualifiedNameWithGenerics() + { + var sb = new StringBuilder(ToFullyQualifiedName()); + if (ContainsGenericParameters) + { + sb.Append("<"); + for (int i = 0; i < Generics.Count; i++) + { + if (i > 0) + sb.Append(", "); + sb.Append(Generics[i].Name); + } + sb.Append(">"); + } + return sb.ToString(); + } + + public override string ToString() + { + return ToFullyQualifiedNameWithGenerics(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs index 93e3d167183e..95153a4c0ff3 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs @@ -4,27 +4,29 @@ using System.Collections.Generic; using SyntaxDynamo.CSLang; -namespace SwiftReflector.SwiftXmlReflection { - public class ClassDeclaration : TypeDeclaration { - public ClassDeclaration () - : base () - { - Kind = TypeKind.Class; - CSharpMethods = new List (); - CSharpProperties = new List (); - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class ClassDeclaration : TypeDeclaration + { + public ClassDeclaration() + : base() + { + Kind = TypeKind.Class; + CSharpMethods = new List(); + CSharpProperties = new List(); + } - protected override TypeDeclaration UnrootedFactory () - { - return new ClassDeclaration (); - } + protected override TypeDeclaration UnrootedFactory() + { + return new ClassDeclaration(); + } - // These are strictly for imported members from C# dll's. - // These members should not get serialized. - public bool IsImportedBinding { get; set; } - public List CSharpMethods { get; } - public List CSharpProperties { get; } - } + // These are strictly for imported members from C# dll's. + // These members should not get serialized. + public bool IsImportedBinding { get; set; } + public List CSharpMethods { get; } + public List CSharpProperties { get; } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs index a61fc5d2d856..ebbfafd1b0b7 100644 --- a/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs @@ -7,119 +7,143 @@ using SwiftReflector.ExceptionTools; using System.Xml.Linq; -namespace SwiftReflector.SwiftXmlReflection { - public class EnumDeclaration : TypeDeclaration { - public EnumDeclaration () - : base () - { - Kind = TypeKind.Enum; - Elements = new List (); - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class EnumDeclaration : TypeDeclaration + { + public EnumDeclaration() + : base() + { + Kind = TypeKind.Enum; + Elements = new List(); + } - protected override TypeDeclaration UnrootedFactory () - { - return new EnumDeclaration (); - } + protected override TypeDeclaration UnrootedFactory() + { + return new EnumDeclaration(); + } - protected override void CompleteUnrooting (TypeDeclaration unrooted) - { - base.CompleteUnrooting (unrooted); - EnumDeclaration enumDecl = unrooted as EnumDeclaration; - if (enumDecl == null) - throw new ArgumentException ("unrooted type was not constructed by EnumDeclaration"); - enumDecl.Elements.AddRange (Elements); - } + protected override void CompleteUnrooting(TypeDeclaration unrooted) + { + base.CompleteUnrooting(unrooted); + EnumDeclaration enumDecl = unrooted as EnumDeclaration; + if (enumDecl == null) + throw new ArgumentException("unrooted type was not constructed by EnumDeclaration"); + enumDecl.Elements.AddRange(Elements); + } - public List Elements { get; private set; } - public bool ElementIsGeneric (EnumElement element) - { - return IsTypeSpecGeneric (element.TypeSpec); - } + public List Elements { get; private set; } + public bool ElementIsGeneric(EnumElement element) + { + return IsTypeSpecGeneric(element.TypeSpec); + } - public bool HasRawType { get { return rawTypeName != null && RawTypeSpec != null; } } + public bool HasRawType { get { return rawTypeName != null && RawTypeSpec != null; } } - string rawTypeName; - public string RawTypeName { - get { - return rawTypeName; - } - set { - rawTypeName = value; - if (value == null) - RawTypeSpec = null; - else { - try { - RawTypeSpec = TypeSpecParser.Parse (rawTypeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 8, $"Unable to parse type name '{rawTypeName}': {ex.Message}"); - } - } - } - } - public TypeSpec RawTypeSpec { get; private set; } + string rawTypeName; + public string RawTypeName + { + get + { + return rawTypeName; + } + set + { + rawTypeName = value; + if (value == null) + RawTypeSpec = null; + else + { + try + { + RawTypeSpec = TypeSpecParser.Parse(rawTypeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 8, $"Unable to parse type name '{rawTypeName}': {ex.Message}"); + } + } + } + } + public TypeSpec RawTypeSpec { get; private set; } - public bool IsTrivial { - get { - if (HasRawType) - return false; - if (Inheritance.Count > 0) - return false; - foreach (EnumElement elem in Elements) { - if (elem.HasType) - return false; - } - return true; - } - } + public bool IsTrivial + { + get + { + if (HasRawType) + return false; + if (Inheritance.Count > 0) + return false; + foreach (EnumElement elem in Elements) + { + if (elem.HasType) + return false; + } + return true; + } + } - public bool IsIntegral { - get { - if (HasRawType) { - return TypeSpec.IsIntegral (RawTypeSpec); - } - foreach (EnumElement elem in Elements) { - if (elem.HasType && !TypeSpec.IsIntegral (elem.TypeSpec)) - return false; - } - return true; - } - } + public bool IsIntegral + { + get + { + if (HasRawType) + { + return TypeSpec.IsIntegral(RawTypeSpec); + } + foreach (EnumElement elem in Elements) + { + if (elem.HasType && !TypeSpec.IsIntegral(elem.TypeSpec)) + return false; + } + return true; + } + } - public bool IsHomogenous { - get { - if (Elements.Count == 0) - return true; - TypeSpec firstSpec = Elements [0].TypeSpec; - for (int i = 1; i < Elements.Count; i++) { - TypeSpec nextSpec = Elements [i].TypeSpec; - if (firstSpec == null) { - if (firstSpec != nextSpec) - return false; - } else { - if (!firstSpec.Equals (nextSpec)) - return false; - } - } - return true; - } - } + public bool IsHomogenous + { + get + { + if (Elements.Count == 0) + return true; + TypeSpec firstSpec = Elements[0].TypeSpec; + for (int i = 1; i < Elements.Count; i++) + { + TypeSpec nextSpec = Elements[i].TypeSpec; + if (firstSpec == null) + { + if (firstSpec != nextSpec) + return false; + } + else + { + if (!firstSpec.Equals(nextSpec)) + return false; + } + } + return true; + } + } - public EnumElement this [string s] { - get { - return Elements.FirstOrDefault (elem => elem.Name == s); - } - } + public EnumElement this[string s] + { + get + { + return Elements.FirstOrDefault(elem => elem.Name == s); + } + } - protected override void GatherXObjects (List xobjects) - { - base.GatherXObjects (xobjects); - if (HasRawType) - xobjects.Add (new XAttribute ("rawType", RawTypeName)); - IEnumerable elems = Elements.Select (e => e.ToXElement ()); - xobjects.Add (new XElement ("elements", elems.ToArray ())); - } + protected override void GatherXObjects(List xobjects) + { + base.GatherXObjects(xobjects); + if (HasRawType) + xobjects.Add(new XAttribute("rawType", RawTypeName)); + IEnumerable elems = Elements.Select(e => e.ToXElement()); + xobjects.Add(new XElement("elements", elems.ToArray())); + } - } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs index e8177e344b79..995e2d9e1e46 100644 --- a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs +++ b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs @@ -7,50 +7,59 @@ using System.Xml.Linq; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class EnumElement : IXElementConvertible { - public EnumElement (string name, string typeName, long? value) - { - Name = Exceptions.ThrowOnNull (name, nameof(name)); - TypeName = typeName; - Value = value; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class EnumElement : IXElementConvertible + { + public EnumElement(string name, string typeName, long? value) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + TypeName = typeName; + Value = value; + } - public string Name { get; set; } - public bool HasType { get { return typeName != null && TypeSpec != null; } } - string typeName; - public string TypeName { - get { - return typeName; - } - set { - typeName = value; - if (value == null) - TypeSpec = null; - else { - try { - TypeSpec = TypeSpecParser.Parse (typeName); - } catch (RuntimeException ex) { - ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 9, $"Unable to parse type name '{typeName}': {ex.Message}"); - } - } - } - } - public TypeSpec TypeSpec { get; private set; } - public long? Value { get; private set; } + public string Name { get; set; } + public bool HasType { get { return typeName != null && TypeSpec != null; } } + string typeName; + public string TypeName + { + get + { + return typeName; + } + set + { + typeName = value; + if (value == null) + TypeSpec = null; + else + { + try + { + TypeSpec = TypeSpecParser.Parse(typeName); + } + catch (RuntimeException ex) + { + ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 9, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + } + public TypeSpec TypeSpec { get; private set; } + public long? Value { get; private set; } - #region IXElementConvertible implementation - public XElement ToXElement () - { - XElement elem = new XElement ("element", - new XAttribute ("name", Name)); - if (HasType) - elem.Add (new XAttribute ("type", TypeName)); - if (Value.HasValue) - elem.Add ("intValue", Value.Value); - return elem; - } - #endregion - } + #region IXElementConvertible implementation + public XElement ToXElement() + { + XElement elem = new XElement("element", + new XAttribute("name", Name)); + if (HasType) + elem.Add(new XAttribute("type", TypeName)); + if (Value.HasValue) + elem.Add("intValue", Value.Value); + return elem; + } + #endregion + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/Enums.cs b/src/SwiftReflector/SwiftXmlReflection/Enums.cs index 19a2909b9b8e..c9cfd7b884fe 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Enums.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Enums.cs @@ -1,82 +1,91 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SwiftReflector.SwiftXmlReflection { - public enum TypeKind { - Unknown = 0, - Class, - Struct, - Enum, - Protocol - } +namespace SwiftReflector.SwiftXmlReflection +{ + public enum TypeKind + { + Unknown = 0, + Class, + Struct, + Enum, + Protocol + } - public enum Accessibility { - Unknown = 0, - Public, - Private, - Internal, - Open, - } + public enum Accessibility + { + Unknown = 0, + Public, + Private, + Internal, + Open, + } - public enum StorageKind { - Unknown = 0, - Addressed, - AddressedWithObservers, - AddressedWithTrivialAccessors, - Computed, - ComputedWithMutableAddress, - Inherited, - InheritedWithObservers, - Stored, - StoredWithObservers, - StoredWithTrivialAccessors, - Coroutine, - MutableAddressor, - } + public enum StorageKind + { + Unknown = 0, + Addressed, + AddressedWithObservers, + AddressedWithTrivialAccessors, + Computed, + ComputedWithMutableAddress, + Inherited, + InheritedWithObservers, + Stored, + StoredWithObservers, + StoredWithTrivialAccessors, + Coroutine, + MutableAddressor, + } - public enum TypeSpecKind { - Named = 0, - Tuple, - Closure, - ProtocolList, - } + public enum TypeSpecKind + { + Named = 0, + Tuple, + Closure, + ProtocolList, + } - public enum TypeTokenKind { - TypeName, - Comma, - LeftParenthesis, - RightParenthesis, - LeftAngle, - RightAngle, - LeftBracket, - RightBracket, - Arrow, - At, - QuestionMark, - TypeLabel, - Colon, - ExclamationPoint, - Period, - Ampersand, - Done, - } + public enum TypeTokenKind + { + TypeName, + Comma, + LeftParenthesis, + RightParenthesis, + LeftAngle, + RightAngle, + LeftBracket, + RightBracket, + Arrow, + At, + QuestionMark, + TypeLabel, + Colon, + ExclamationPoint, + Period, + Ampersand, + Done, + } - public enum InheritanceKind { - Class, - Protocol - } + public enum InheritanceKind + { + Class, + Protocol + } - public enum ConstraintKind { - Inherits, - Equal - } + public enum ConstraintKind + { + Inherits, + Equal + } - public enum AttributeParameterKind { - None, - Label, - Literal, - Sublist, - Unknown, - } + public enum AttributeParameterKind + { + None, + Label, + Literal, + Sublist, + Unknown, + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs index 3cbd7e61368c..7145f8ae963e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs @@ -9,81 +9,92 @@ using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class ExtensionDeclaration : IXElementConvertible { +namespace SwiftReflector.SwiftXmlReflection +{ + public class ExtensionDeclaration : IXElementConvertible + { - public ExtensionDeclaration () - { - Inheritance = new List (); - Members = new List (); - } + public ExtensionDeclaration() + { + Inheritance = new List(); + Members = new List(); + } - public ExtensionDeclaration (ExtensionDeclaration other) - : this () - { - Inheritance.AddRange (other.Inheritance); - Members.AddRange (other.Members); - ExtensionOnTypeName = other.ExtensionOnTypeName; - Module = other.Module; - } + public ExtensionDeclaration(ExtensionDeclaration other) + : this() + { + Inheritance.AddRange(other.Inheritance); + Members.AddRange(other.Members); + ExtensionOnTypeName = other.ExtensionOnTypeName; + Module = other.Module; + } - public ModuleDeclaration Module { get; set; } - public List Inheritance { get; set; } - string extensionOnTypeName; - public string ExtensionOnTypeName { - get { - return extensionOnTypeName; - } - set { - extensionOnTypeName = Exceptions.ThrowOnNull (value, "value"); - try { - ExtensionOnType = TypeSpecParser.Parse (extensionOnTypeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase, $"Unable to parse type name '{extensionOnTypeName}': {ex.Message}"); - } + public ModuleDeclaration Module { get; set; } + public List Inheritance { get; set; } + string extensionOnTypeName; + public string ExtensionOnTypeName + { + get + { + return extensionOnTypeName; + } + set + { + extensionOnTypeName = Exceptions.ThrowOnNull(value, "value"); + try + { + ExtensionOnType = TypeSpecParser.Parse(extensionOnTypeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase, $"Unable to parse type name '{extensionOnTypeName}': {ex.Message}"); + } - } - } - public TypeSpec ExtensionOnType { get; private set; } - public List Members { get; set; } + } + } + public TypeSpec ExtensionOnType { get; private set; } + public List Members { get; set; } - public XElement ToXElement () - { - var xobjects = new List (); - GatherXObjects (xobjects); - XElement typeDecl = new XElement ("extension", xobjects.ToArray ()); - return typeDecl; - } + public XElement ToXElement() + { + var xobjects = new List(); + GatherXObjects(xobjects); + XElement typeDecl = new XElement("extension", xobjects.ToArray()); + return typeDecl; + } - void GatherXObjects (List xobjects) - { - xobjects.Add (new XAttribute ("onType", ExtensionOnTypeName)); - List memcontents = new List (Members.Select (m => m.ToXElement ())); - xobjects.Add (new XElement ("members", memcontents.ToArray ())); - List inherits = new List (Inheritance.Select (i => i.ToXElement ())); - xobjects.Add (new XElement ("inherits", inherits.ToArray ())); - } + void GatherXObjects(List xobjects) + { + xobjects.Add(new XAttribute("onType", ExtensionOnTypeName)); + List memcontents = new List(Members.Select(m => m.ToXElement())); + xobjects.Add(new XElement("members", memcontents.ToArray())); + List inherits = new List(Inheritance.Select(i => i.ToXElement())); + xobjects.Add(new XElement("inherits", inherits.ToArray())); + } - public static ExtensionDeclaration FromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module) - { - var decl = new ExtensionDeclaration (); - decl.Module = module; - decl.ExtensionOnTypeName = (string)elem.Attribute ("onType"); - decl.ExtensionOnType = folder.FoldAlias (null, decl.ExtensionOnType); - if (elem.Element ("members") != null) { - var members = from mem in elem.Element ("members").Elements () - select Member.FromXElement (folder, mem, module, null) as Member; - decl.Members.AddRange (members); - foreach (var member in decl.Members) { - member.ParentExtension = decl; - } - } - if (elem.Element ("inherits") != null) { - var inherits = from inherit in elem.Element ("inherits").Elements () - select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement (folder, inherit) as Inheritance; - decl.Inheritance.AddRange (inherits); - } - return decl; - } - } + public static ExtensionDeclaration FromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module) + { + var decl = new ExtensionDeclaration(); + decl.Module = module; + decl.ExtensionOnTypeName = (string)elem.Attribute("onType"); + decl.ExtensionOnType = folder.FoldAlias(null, decl.ExtensionOnType); + if (elem.Element("members") != null) + { + var members = from mem in elem.Element("members").Elements() + select Member.FromXElement(folder, mem, module, null) as Member; + decl.Members.AddRange(members); + foreach (var member in decl.Members) + { + member.ParentExtension = decl; + } + } + if (elem.Element("inherits") != null) + { + var inherits = from inherit in elem.Element("inherits").Elements() + select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement(folder, inherit) as Inheritance; + decl.Inheritance.AddRange(inherits); + } + return decl; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs index 926e2319cd20..7d976c86cf88 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs @@ -6,41 +6,43 @@ using System.Collections.Generic; using System.Xml.Linq; -namespace SwiftReflector.SwiftXmlReflection { - - public static class ExtensionMethods { - // surprise! You'd think that you could write this code: - // public static T DefaultedAttribute(this XElement elem, XName name, T defaultValue = default(T)) - // { - // XAttribute attr = elem.Attribute (name); - // if (attr == null) - // return defaultValue; - // return (T)attr; - // } - // but the last cast won't work because generics aren't templates. - - // So instead, we get to repeat ourselves a lot. - - public static bool BoolAttribute (this XElement elem, XName name, bool defaultValue = default (bool)) - { - XAttribute attr = elem.Attribute (name); - if (attr == null) - return defaultValue; - return (bool)attr; - } - - public static double DoubleAttribute (this XElement elem, XName name, double defaultValue = default (double)) - { - XAttribute attr = elem.Attribute (name); - if (attr == null) - return defaultValue; - return (double)attr; - } - - public static bool IsPrivateOrInternal (this Accessibility a) - { - return a == Accessibility.Private || a == Accessibility.Internal; - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + + public static class ExtensionMethods + { + // surprise! You'd think that you could write this code: + // public static T DefaultedAttribute(this XElement elem, XName name, T defaultValue = default(T)) + // { + // XAttribute attr = elem.Attribute (name); + // if (attr == null) + // return defaultValue; + // return (T)attr; + // } + // but the last cast won't work because generics aren't templates. + + // So instead, we get to repeat ourselves a lot. + + public static bool BoolAttribute(this XElement elem, XName name, bool defaultValue = default(bool)) + { + XAttribute attr = elem.Attribute(name); + if (attr == null) + return defaultValue; + return (bool)attr; + } + + public static double DoubleAttribute(this XElement elem, XName name, double defaultValue = default(double)) + { + XAttribute attr = elem.Attribute(name); + if (attr == null) + return defaultValue; + return (double)attr; + } + + public static bool IsPrivateOrInternal(this Accessibility a) + { + return a == Accessibility.Private || a == Accessibility.Internal; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs index 4bbbdbac5f3a..dc42d775b82e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs @@ -9,463 +9,531 @@ using SwiftReflector.ExceptionTools; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class FunctionDeclaration : Member { - public const string kConstructorName = ".ctor"; - public const string kDestructorName = ".dtor"; - public const string kPropertyGetterPrefix = "get_"; - public const string kPropertySetterPrefix = "set_"; - public const string kPropertyMaterializerPrefix = "materializeforset_"; - public const string kPropertySubscriptGetterName = "get_subscript"; - public const string kPropertySubscriptSetterName = "set_subscript"; - public const string kPropertySubscriptMaterializerName = "materializeforset_subscript"; - - static string [] subscriptNames = new string [] { - kPropertySubscriptGetterName, - kPropertySubscriptSetterName, - kPropertySubscriptMaterializerName, - }; - static bool IsSubscriptName (string s) - { - return Array.IndexOf (subscriptNames, s) >= 0; - } - - public FunctionDeclaration () - : base () - { - ParameterLists = new List> (); - } - - public FunctionDeclaration (FunctionDeclaration other) - : base (other) - { - ParameterLists = CopyOf (other.ParameterLists); - ReturnTypeName = other.ReturnTypeName; - IsProperty = other.IsProperty; - IsStatic = other.IsStatic; - IsFinal = other.IsFinal; - HasThrows = other.HasThrows; - IsDeprecated = other.IsDeprecated; - IsUnavailable = other.IsUnavailable; - OperatorType = other.OperatorType; - IsOptional = other.IsOptional; - ObjCSelector = other.ObjCSelector; - IsRequired = other.IsRequired; - IsConvenienceInit = other.IsConvenienceInit; - IsAsync = other.IsAsync; - foreach (var genDecl in other.Generics) { - Generics.Add (new GenericDeclaration (genDecl)); - } - } - - string returnTypeName; - public string ReturnTypeName { - get { return returnTypeName; } - set { - returnTypeName = Exceptions.ThrowOnNull (value, "value"); - try { - ReturnTypeSpec = TypeSpecParser.Parse (returnTypeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 1, $"Unable to parse type name '{returnTypeName}': {ex.Message}"); - } - } - } - - - // When writing an override, we need to keep around the function in the override - // this member should never get serialized. Ever. - public FunctionDeclaration OverrideSurrogateFunction { get; set; } - - - public TypeSpec ReturnTypeSpec { get; private set; } - - public bool IsRequired { get; set; } - public string ObjCSelector { get; set; } - public bool IsOptional { get; set; } - public bool HasThrows { get; set; } - public bool IsAsync { get; set; } - public bool IsProperty { get; set; } - public string PropertyName { get { return Name.Substring (kPropertyGetterPrefix.Length); } } - public bool IsStatic { get; set; } - public bool IsFinal { get; set; } - public bool IsOperator { get { return OperatorType != OperatorType.None; } } - public bool IsDeprecated { get; set; } - public bool IsUnavailable { get; set; } - public bool IsConvenienceInit { get; set; } - public bool IsVirtualClassMethod { get { return IsStatic && Access == Accessibility.Open; } } - public bool IsSubscript { - get { - return IsProperty && IsSubscriptName (Name); - } - } - public OperatorType OperatorType { get; set; } - public bool IsSubscriptGetter { - get { - return IsProperty && Name == kPropertySubscriptGetterName; - } - } - public bool IsSubscriptSetter { - get { - return IsProperty && Name == kPropertySubscriptSetterName; - } - } - // in practice, this is useless since it is near impossible to disambiguate it - // and it has no actual use from our point of view. Materializers are code used - // internally by the compiler and we don't really have access to this. - public bool IsSubscriptMaterializer { - get { - return IsProperty && Name == kPropertySubscriptMaterializerName; - } - } - - public TypeSpec PropertyType { - get { - if (!IsProperty) - throw ErrorHelper.CreateError (ReflectorError.kInventoryBase + 17, $"Attempt to get property type for a function named {this.Name}"); - // newValue should be the first argument in the last argument list. - return ParameterLists.Last () [0].TypeSpec; - } - } - - public List> ParameterLists { get; private set; } - - public bool IsTypeSpecGeneric (ParameterItem item) - { - return IsTypeSpecGeneric (item.TypeSpec); - } - - public int GenericParameterCount { - get { - return ParameterLists.Last ().Sum (pi => IsTypeSpecGeneric (pi) ? 1 : 0); - } - } - - public bool MatchesSignature (FunctionDeclaration other, bool ignoreFirstParameterListIfPresent) - { - if (!TypeSpec.BothNullOrEqual (this.ReturnTypeSpec, other.ReturnTypeSpec)) - return false; - if (this.ParameterLists.Count != other.ParameterLists.Count) - return false; - int startIndex = ignoreFirstParameterListIfPresent && this.ParameterLists.Count > 1 ? 1 : 0; - - for (int i = startIndex; i < this.ParameterLists.Count; i++) { - if (!ParameterItem.AreEqualIgnoreNamesReferencesInvariant (this, this.ParameterLists [i], other, other.ParameterLists [i], true)) - return false; - } - return true; - } - - public bool IsConstructor { get { return Name == kConstructorName; } } - public bool IsDestructor { get { return Name == kDestructorName; } } - public bool IsConstructorOrDestructor { get { return IsConstructor || IsDestructor; } } - public bool IsGetter { get { return IsProperty && Name.StartsWith (kPropertyGetterPrefix); } } - public bool IsSetter { get { return IsProperty && Name.StartsWith (kPropertySetterPrefix); } } - public bool IsMaterializer { get { return IsProperty && Name.StartsWith (kPropertyMaterializerPrefix); } } - - public bool IsOptionalConstructor { - get { - if (Name != kConstructorName) - return false; - var namedSpec = ReturnTypeSpec as NamedTypeSpec; - if (namedSpec == null) - return false; - if (namedSpec.Name != "Swift.Optional") - return false; - if (namedSpec.GenericParameters.Count != 1) - return false; - // previously we did a name check on the parent but in the case of - // a virtual class, the name could be the proxy class that we make - // and won't necessarily match. - return true; - } - } - - public bool IsVariadic { - get { - return ParameterLists.Last ().Any (pi => pi.IsVariadic); - } - } - - public FunctionDeclaration MatchingSetter (IEnumerable decls) - { - if (!IsProperty) - return null; - if (IsSubscript) { - return decls.Where (f => f.IsSubscriptSetter && SubscriptParametersMatch (this, f)).FirstOrDefault (); - } else { - return decls.Where (f => f.IsSetter && f.PropertyName == PropertyName).FirstOrDefault (); - } - } - - static bool SubscriptParametersMatch (FunctionDeclaration getter, FunctionDeclaration setter) - { - if (getter.ParameterLists.Count != 2 || setter.ParameterLists.Count != 2) - return false; - TypeSpec returnType = getter.ReturnTypeSpec; - if (getter.ParameterLists [1].Count != setter.ParameterLists [1].Count - 1) - return false; - if (!returnType.Equals (setter.ParameterLists [1] [0].TypeSpec)) - return false; - - return ParameterItem.AreEqualIgnoreNamesReferencesInvariant (getter, getter.ParameterLists [1], - setter, setter.ParameterLists [1].Skip (1).ToList (), true); - } - - - public bool ContainsBoundGenericClosure () - { - foreach (var arg in ParameterLists.Last ()) { - if (arg.TypeSpec.ContainsBoundGenericClosure ()) - return true; - } - return ReturnTypeSpec.ContainsBoundGenericClosure (); - } - - - public static FunctionDeclaration FuncFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) - { - FunctionDeclaration decl = new FunctionDeclaration { - Name = (string)elem.Attribute ("name"), - Module = module, - Parent = parent, - Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")), - ReturnTypeName = Exceptions.ThrowOnNull ((string)elem.Attribute ("returnType"), "returnType"), - IsAsync = elem.BoolAttribute ("isAsync"), - IsProperty = elem.BoolAttribute ("isProperty"), - IsStatic = elem.BoolAttribute ("isStatic"), - IsFinal = elem.BoolAttribute ("isFinal"), - OperatorType = OperatorTypeFromElement ((string)elem.Attribute ("operatorKind")), - HasThrows = elem.BoolAttribute ("hasThrows"), - IsDeprecated = elem.BoolAttribute ("isDeprecated"), - IsUnavailable = elem.BoolAttribute ("isUnavailable"), - IsOptional = elem.BoolAttribute ("isOptional"), - ObjCSelector = (string)elem.Attribute ("objcSelector"), - IsRequired = elem.BoolAttribute ("isRequired"), - IsConvenienceInit = elem.BoolAttribute ("isConvenienceInit") - }; - decl.ReturnTypeSpec = folder.FoldAlias (parent, decl.ReturnTypeSpec); - decl.ParameterLists.AddRange (ParameterItem.ParameterListListFromXElement (folder, elem.Element ("parameterlists"))); - if (decl.IsProperty && (decl.IsSetter || decl.IsSubscriptSetter)) { - decl.ParameterLists [decl.ParameterLists.Count - 1] = - MassageLastPropertySetterParameterList (decl.ParameterLists.Last ()); - } - return decl; - } - - static List MassageLastPropertySetterParameterList (List list) - { - if (list.Count == 0) - return list; // should never happen, but... - - if (list.Any (pi => pi.PublicName == "newValue")) - return list; // also should never happen, but... - - var firstParam = list [0]; - var firstParamName = firstParam.NameIsRequired ? firstParam.PublicName : firstParam.PrivateName; - // why the check on both value and newValue? Because we want both the public and private names to be newValue - if (firstParamName == "value" || firstParamName == "newValue") // because swift reflects this incorrectly - { - firstParam.PublicName = firstParam.PrivateName = "newValue"; - } - - return list; - } - - - protected override XElement MakeXElement () - { - XElement theFunc = new XElement ("func", - new XAttribute ("name", Name), - new XAttribute ("accessibility", TypeDeclaration.ToString (Access)), - new XAttribute ("returnType", ReturnTypeName), - new XAttribute ("isAsync", BoolString (IsAsync)), - new XAttribute ("isProperty", BoolString (IsProperty)), - new XAttribute ("isStatic", BoolString (IsStatic)), - new XAttribute ("isFinal", BoolString (IsFinal)), - new XAttribute ("isDeprecated", BoolString (IsDeprecated)), - new XAttribute ("isUnavailable", BoolString (IsUnavailable)), - new XAttribute ("isOptional", BoolString (IsOptional)), - new XAttribute ("operatorKind", OperatorType.ToString()), - new XAttribute ("hasThrows", BoolString (HasThrows)), - new XAttribute ("isRequired", BoolString (IsRequired)), - new XAttribute ("isConvenienceInit", BoolString (IsConvenienceInit)), - new XElement ("parameterlists", MakeParamListXElement ())); - if (!String.IsNullOrEmpty (ObjCSelector)) - theFunc.Add (new XAttribute ("objcSelector", ObjCSelector)); - return theFunc; - } - - XElement [] MakeParamListXElement () - { - List plists = new List (); - int index = 0; - foreach (List list in ParameterLists) { - XElement thisList = new XElement ("parameterlist", - new XAttribute ("index", index), - list.Select ((pi, i) => { - XElement elem = pi.ToXElement (); - elem.Add (new XAttribute ("index", i)); - return elem; - }).ToArray ()); - plists.Add (thisList); - index++; - } - return plists.ToArray (); - } - - static List> CopyOf (List> src) - { - List> dst = new List> (); - dst.AddRange (src.Select (l => CopyOf (l))); - return dst; - } - - static List CopyOf (List src) - { - List dst = new List (); - dst.AddRange (src.Select (pi => new ParameterItem (pi))); - return dst; - } - - public static OperatorType OperatorTypeFromElement (string type) - { - var enumType = OperatorType.None; - if (Enum.TryParse (type, out enumType)) - return enumType; - return OperatorType.None; - } - - static string BoolString (bool b) - { - return b ? "true" : "false"; - } - - string PropertyKindString { - get { - if (IsSubscriptGetter || IsGetter) { - return "get"; - } else if (IsSubscriptSetter || IsSetter) { - return "set"; - } else if (IsSubscriptMaterializer || IsMaterializer) { - return "materialize"; - } - return ""; - } - } - - public override bool HasDynamicSelf { - get { - var types = ParameterLists.Last ().Select (p => p.TypeSpec).ToList (); - if (!TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec)) - types.Add (ReturnTypeSpec); - return TypeSpec.AnyHasDynamicSelf (types); - } - } - - public override bool HasDynamicSelfInReturnOnly { - get { - if (IsProperty && !IsSubscript) - return false; - if (TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec) || !ReturnTypeSpec.HasDynamicSelf) - return false; - var types = ParameterLists.Last ().Select (p => p.TypeSpec).ToList (); - return !TypeSpec.AnyHasDynamicSelf (types); - } - } - - public override bool HasDynamicSelfInArguments { - get { - return TypeSpec.AnyHasDynamicSelf (ParameterLists.Last ().Select (p => p.TypeSpec).ToList ()); - } - } - - public FunctionDeclaration MacroReplaceType (string toFind, string replaceWith, bool skipThisArgument) - { - var newFunc = new FunctionDeclaration (this); - if (!TypeSpec.IsNullOrEmptyTuple (newFunc.ReturnTypeSpec)) { - newFunc.ReturnTypeName = newFunc.ReturnTypeSpec.ReplaceName (toFind, replaceWith).ToString (); - } - for (int i = 0; i < newFunc.ParameterLists.Last ().Count; i++) { - var arg = newFunc.ParameterLists.Last () [i]; - if (skipThisArgument && arg.PublicName == "this") - continue; - arg.TypeSpec = arg.TypeSpec.ReplaceName (toFind, replaceWith); - } - return newFunc; - } - - internal string ParametersToString () - { - var builder = new StringBuilder (); - var first = true; - foreach (var parm in ParameterLists.Last ()) { - if (!first) { - builder.Append (", "); - } else { - first = false; - } - // forms - // public_name private_name: [inout] Type - // public_name: [inout] Type - // _ private_name: [inout] Type - if (parm.PublicName == parm.PrivateName) { - builder.Append (parm.PublicName); - } else if (parm.NameIsRequired) { - builder.Append (parm.PublicName).Append (" ").Append (parm.PrivateName); - } else { - builder.Append ("_ ").Append (parm.PrivateName); - } - builder.Append (": "); - if (parm.IsInOut || parm.TypeSpec.IsInOut) - builder.Append ("inout "); - builder.Append (parm.TypeSpec); - } - return builder.ToString (); - } - - public override string ToString () - { - // Forms: - // access [modfiers] var Name: Type { [get | set] } [throws] - // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] - // access [modifiers] Name(args) -> Type [throws] - - var builder = new StringBuilder (); - builder.Append (Access).Append (" "); - if (IsFinal) - builder.Append ("final "); - if (IsStatic) - builder.Append ("static "); - - - if (IsProperty) { - if (IsSubscript) { - builder.Append (Parent.ToString ()).Append (".subscript"); - builder.Append (" [").Append (ParametersToString ()).Append ("] -> "); - } else { - builder.Append ("var ").Append (Parent.ToString ()).Append (".").Append (PropertyName); - builder.Append (": "); - } - builder.Append (ReturnTypeName).Append (" { ").Append (PropertyKindString).Append (" }"); - if (HasThrows) { - builder.Append (" throws"); - } - } else { - builder.Append (base.ToString ()); - builder.Append (" (").Append (ParametersToString ()).Append (")"); - if (HasThrows) { - builder.Append (" throws"); - } - - builder.Append (" -> "); - if (TypeSpec.IsNullOrEmptyTuple (ReturnTypeSpec)) { - builder.Append ("()"); - } else { - builder.Append (ReturnTypeSpec); - } - } - return builder.ToString (); - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class FunctionDeclaration : Member + { + public const string kConstructorName = ".ctor"; + public const string kDestructorName = ".dtor"; + public const string kPropertyGetterPrefix = "get_"; + public const string kPropertySetterPrefix = "set_"; + public const string kPropertyMaterializerPrefix = "materializeforset_"; + public const string kPropertySubscriptGetterName = "get_subscript"; + public const string kPropertySubscriptSetterName = "set_subscript"; + public const string kPropertySubscriptMaterializerName = "materializeforset_subscript"; + + static string[] subscriptNames = new string[] { + kPropertySubscriptGetterName, + kPropertySubscriptSetterName, + kPropertySubscriptMaterializerName, + }; + static bool IsSubscriptName(string s) + { + return Array.IndexOf(subscriptNames, s) >= 0; + } + + public FunctionDeclaration() + : base() + { + ParameterLists = new List>(); + } + + public FunctionDeclaration(FunctionDeclaration other) + : base(other) + { + ParameterLists = CopyOf(other.ParameterLists); + ReturnTypeName = other.ReturnTypeName; + IsProperty = other.IsProperty; + IsStatic = other.IsStatic; + IsFinal = other.IsFinal; + HasThrows = other.HasThrows; + IsDeprecated = other.IsDeprecated; + IsUnavailable = other.IsUnavailable; + OperatorType = other.OperatorType; + IsOptional = other.IsOptional; + ObjCSelector = other.ObjCSelector; + IsRequired = other.IsRequired; + IsConvenienceInit = other.IsConvenienceInit; + IsAsync = other.IsAsync; + foreach (var genDecl in other.Generics) + { + Generics.Add(new GenericDeclaration(genDecl)); + } + } + + string returnTypeName; + public string ReturnTypeName + { + get { return returnTypeName; } + set + { + returnTypeName = Exceptions.ThrowOnNull(value, "value"); + try + { + ReturnTypeSpec = TypeSpecParser.Parse(returnTypeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 1, $"Unable to parse type name '{returnTypeName}': {ex.Message}"); + } + } + } + + + // When writing an override, we need to keep around the function in the override + // this member should never get serialized. Ever. + public FunctionDeclaration OverrideSurrogateFunction { get; set; } + + + public TypeSpec ReturnTypeSpec { get; private set; } + + public bool IsRequired { get; set; } + public string ObjCSelector { get; set; } + public bool IsOptional { get; set; } + public bool HasThrows { get; set; } + public bool IsAsync { get; set; } + public bool IsProperty { get; set; } + public string PropertyName { get { return Name.Substring(kPropertyGetterPrefix.Length); } } + public bool IsStatic { get; set; } + public bool IsFinal { get; set; } + public bool IsOperator { get { return OperatorType != OperatorType.None; } } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsConvenienceInit { get; set; } + public bool IsVirtualClassMethod { get { return IsStatic && Access == Accessibility.Open; } } + public bool IsSubscript + { + get + { + return IsProperty && IsSubscriptName(Name); + } + } + public OperatorType OperatorType { get; set; } + public bool IsSubscriptGetter + { + get + { + return IsProperty && Name == kPropertySubscriptGetterName; + } + } + public bool IsSubscriptSetter + { + get + { + return IsProperty && Name == kPropertySubscriptSetterName; + } + } + // in practice, this is useless since it is near impossible to disambiguate it + // and it has no actual use from our point of view. Materializers are code used + // internally by the compiler and we don't really have access to this. + public bool IsSubscriptMaterializer + { + get + { + return IsProperty && Name == kPropertySubscriptMaterializerName; + } + } + + public TypeSpec PropertyType + { + get + { + if (!IsProperty) + throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 17, $"Attempt to get property type for a function named {this.Name}"); + // newValue should be the first argument in the last argument list. + return ParameterLists.Last()[0].TypeSpec; + } + } + + public List> ParameterLists { get; private set; } + + public bool IsTypeSpecGeneric(ParameterItem item) + { + return IsTypeSpecGeneric(item.TypeSpec); + } + + public int GenericParameterCount + { + get + { + return ParameterLists.Last().Sum(pi => IsTypeSpecGeneric(pi) ? 1 : 0); + } + } + + public bool MatchesSignature(FunctionDeclaration other, bool ignoreFirstParameterListIfPresent) + { + if (!TypeSpec.BothNullOrEqual(this.ReturnTypeSpec, other.ReturnTypeSpec)) + return false; + if (this.ParameterLists.Count != other.ParameterLists.Count) + return false; + int startIndex = ignoreFirstParameterListIfPresent && this.ParameterLists.Count > 1 ? 1 : 0; + + for (int i = startIndex; i < this.ParameterLists.Count; i++) + { + if (!ParameterItem.AreEqualIgnoreNamesReferencesInvariant(this, this.ParameterLists[i], other, other.ParameterLists[i], true)) + return false; + } + return true; + } + + public bool IsConstructor { get { return Name == kConstructorName; } } + public bool IsDestructor { get { return Name == kDestructorName; } } + public bool IsConstructorOrDestructor { get { return IsConstructor || IsDestructor; } } + public bool IsGetter { get { return IsProperty && Name.StartsWith(kPropertyGetterPrefix); } } + public bool IsSetter { get { return IsProperty && Name.StartsWith(kPropertySetterPrefix); } } + public bool IsMaterializer { get { return IsProperty && Name.StartsWith(kPropertyMaterializerPrefix); } } + + public bool IsOptionalConstructor + { + get + { + if (Name != kConstructorName) + return false; + var namedSpec = ReturnTypeSpec as NamedTypeSpec; + if (namedSpec == null) + return false; + if (namedSpec.Name != "Swift.Optional") + return false; + if (namedSpec.GenericParameters.Count != 1) + return false; + // previously we did a name check on the parent but in the case of + // a virtual class, the name could be the proxy class that we make + // and won't necessarily match. + return true; + } + } + + public bool IsVariadic + { + get + { + return ParameterLists.Last().Any(pi => pi.IsVariadic); + } + } + + public FunctionDeclaration MatchingSetter(IEnumerable decls) + { + if (!IsProperty) + return null; + if (IsSubscript) + { + return decls.Where(f => f.IsSubscriptSetter && SubscriptParametersMatch(this, f)).FirstOrDefault(); + } + else + { + return decls.Where(f => f.IsSetter && f.PropertyName == PropertyName).FirstOrDefault(); + } + } + + static bool SubscriptParametersMatch(FunctionDeclaration getter, FunctionDeclaration setter) + { + if (getter.ParameterLists.Count != 2 || setter.ParameterLists.Count != 2) + return false; + TypeSpec returnType = getter.ReturnTypeSpec; + if (getter.ParameterLists[1].Count != setter.ParameterLists[1].Count - 1) + return false; + if (!returnType.Equals(setter.ParameterLists[1][0].TypeSpec)) + return false; + + return ParameterItem.AreEqualIgnoreNamesReferencesInvariant(getter, getter.ParameterLists[1], + setter, setter.ParameterLists[1].Skip(1).ToList(), true); + } + + + public bool ContainsBoundGenericClosure() + { + foreach (var arg in ParameterLists.Last()) + { + if (arg.TypeSpec.ContainsBoundGenericClosure()) + return true; + } + return ReturnTypeSpec.ContainsBoundGenericClosure(); + } + + + public static FunctionDeclaration FuncFromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + FunctionDeclaration decl = new FunctionDeclaration + { + Name = (string)elem.Attribute("name"), + Module = module, + Parent = parent, + Access = TypeDeclaration.AccessibilityFromString((string)elem.Attribute("accessibility")), + ReturnTypeName = Exceptions.ThrowOnNull((string)elem.Attribute("returnType"), "returnType"), + IsAsync = elem.BoolAttribute("isAsync"), + IsProperty = elem.BoolAttribute("isProperty"), + IsStatic = elem.BoolAttribute("isStatic"), + IsFinal = elem.BoolAttribute("isFinal"), + OperatorType = OperatorTypeFromElement((string)elem.Attribute("operatorKind")), + HasThrows = elem.BoolAttribute("hasThrows"), + IsDeprecated = elem.BoolAttribute("isDeprecated"), + IsUnavailable = elem.BoolAttribute("isUnavailable"), + IsOptional = elem.BoolAttribute("isOptional"), + ObjCSelector = (string)elem.Attribute("objcSelector"), + IsRequired = elem.BoolAttribute("isRequired"), + IsConvenienceInit = elem.BoolAttribute("isConvenienceInit") + }; + decl.ReturnTypeSpec = folder.FoldAlias(parent, decl.ReturnTypeSpec); + decl.ParameterLists.AddRange(ParameterItem.ParameterListListFromXElement(folder, elem.Element("parameterlists"))); + if (decl.IsProperty && (decl.IsSetter || decl.IsSubscriptSetter)) + { + decl.ParameterLists[decl.ParameterLists.Count - 1] = + MassageLastPropertySetterParameterList(decl.ParameterLists.Last()); + } + return decl; + } + + static List MassageLastPropertySetterParameterList(List list) + { + if (list.Count == 0) + return list; // should never happen, but... + + if (list.Any(pi => pi.PublicName == "newValue")) + return list; // also should never happen, but... + + var firstParam = list[0]; + var firstParamName = firstParam.NameIsRequired ? firstParam.PublicName : firstParam.PrivateName; + // why the check on both value and newValue? Because we want both the public and private names to be newValue + if (firstParamName == "value" || firstParamName == "newValue") // because swift reflects this incorrectly + { + firstParam.PublicName = firstParam.PrivateName = "newValue"; + } + + return list; + } + + + protected override XElement MakeXElement() + { + XElement theFunc = new XElement("func", + new XAttribute("name", Name), + new XAttribute("accessibility", TypeDeclaration.ToString(Access)), + new XAttribute("returnType", ReturnTypeName), + new XAttribute("isAsync", BoolString(IsAsync)), + new XAttribute("isProperty", BoolString(IsProperty)), + new XAttribute("isStatic", BoolString(IsStatic)), + new XAttribute("isFinal", BoolString(IsFinal)), + new XAttribute("isDeprecated", BoolString(IsDeprecated)), + new XAttribute("isUnavailable", BoolString(IsUnavailable)), + new XAttribute("isOptional", BoolString(IsOptional)), + new XAttribute("operatorKind", OperatorType.ToString()), + new XAttribute("hasThrows", BoolString(HasThrows)), + new XAttribute("isRequired", BoolString(IsRequired)), + new XAttribute("isConvenienceInit", BoolString(IsConvenienceInit)), + new XElement("parameterlists", MakeParamListXElement())); + if (!String.IsNullOrEmpty(ObjCSelector)) + theFunc.Add(new XAttribute("objcSelector", ObjCSelector)); + return theFunc; + } + + XElement[] MakeParamListXElement() + { + List plists = new List(); + int index = 0; + foreach (List list in ParameterLists) + { + XElement thisList = new XElement("parameterlist", + new XAttribute("index", index), + list.Select((pi, i) => + { + XElement elem = pi.ToXElement(); + elem.Add(new XAttribute("index", i)); + return elem; + }).ToArray()); + plists.Add(thisList); + index++; + } + return plists.ToArray(); + } + + static List> CopyOf(List> src) + { + List> dst = new List>(); + dst.AddRange(src.Select(l => CopyOf(l))); + return dst; + } + + static List CopyOf(List src) + { + List dst = new List(); + dst.AddRange(src.Select(pi => new ParameterItem(pi))); + return dst; + } + + public static OperatorType OperatorTypeFromElement(string type) + { + var enumType = OperatorType.None; + if (Enum.TryParse(type, out enumType)) + return enumType; + return OperatorType.None; + } + + static string BoolString(bool b) + { + return b ? "true" : "false"; + } + + string PropertyKindString + { + get + { + if (IsSubscriptGetter || IsGetter) + { + return "get"; + } + else if (IsSubscriptSetter || IsSetter) + { + return "set"; + } + else if (IsSubscriptMaterializer || IsMaterializer) + { + return "materialize"; + } + return ""; + } + } + + public override bool HasDynamicSelf + { + get + { + var types = ParameterLists.Last().Select(p => p.TypeSpec).ToList(); + if (!TypeSpec.IsNullOrEmptyTuple(ReturnTypeSpec)) + types.Add(ReturnTypeSpec); + return TypeSpec.AnyHasDynamicSelf(types); + } + } + + public override bool HasDynamicSelfInReturnOnly + { + get + { + if (IsProperty && !IsSubscript) + return false; + if (TypeSpec.IsNullOrEmptyTuple(ReturnTypeSpec) || !ReturnTypeSpec.HasDynamicSelf) + return false; + var types = ParameterLists.Last().Select(p => p.TypeSpec).ToList(); + return !TypeSpec.AnyHasDynamicSelf(types); + } + } + + public override bool HasDynamicSelfInArguments + { + get + { + return TypeSpec.AnyHasDynamicSelf(ParameterLists.Last().Select(p => p.TypeSpec).ToList()); + } + } + + public FunctionDeclaration MacroReplaceType(string toFind, string replaceWith, bool skipThisArgument) + { + var newFunc = new FunctionDeclaration(this); + if (!TypeSpec.IsNullOrEmptyTuple(newFunc.ReturnTypeSpec)) + { + newFunc.ReturnTypeName = newFunc.ReturnTypeSpec.ReplaceName(toFind, replaceWith).ToString(); + } + for (int i = 0; i < newFunc.ParameterLists.Last().Count; i++) + { + var arg = newFunc.ParameterLists.Last()[i]; + if (skipThisArgument && arg.PublicName == "this") + continue; + arg.TypeSpec = arg.TypeSpec.ReplaceName(toFind, replaceWith); + } + return newFunc; + } + + internal string ParametersToString() + { + var builder = new StringBuilder(); + var first = true; + foreach (var parm in ParameterLists.Last()) + { + if (!first) + { + builder.Append(", "); + } + else + { + first = false; + } + // forms + // public_name private_name: [inout] Type + // public_name: [inout] Type + // _ private_name: [inout] Type + if (parm.PublicName == parm.PrivateName) + { + builder.Append(parm.PublicName); + } + else if (parm.NameIsRequired) + { + builder.Append(parm.PublicName).Append(" ").Append(parm.PrivateName); + } + else + { + builder.Append("_ ").Append(parm.PrivateName); + } + builder.Append(": "); + if (parm.IsInOut || parm.TypeSpec.IsInOut) + builder.Append("inout "); + builder.Append(parm.TypeSpec); + } + return builder.ToString(); + } + + public override string ToString() + { + // Forms: + // access [modfiers] var Name: Type { [get | set] } [throws] + // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] + // access [modifiers] Name(args) -> Type [throws] + + var builder = new StringBuilder(); + builder.Append(Access).Append(" "); + if (IsFinal) + builder.Append("final "); + if (IsStatic) + builder.Append("static "); + + + if (IsProperty) + { + if (IsSubscript) + { + builder.Append(Parent.ToString()).Append(".subscript"); + builder.Append(" [").Append(ParametersToString()).Append("] -> "); + } + else + { + builder.Append("var ").Append(Parent.ToString()).Append(".").Append(PropertyName); + builder.Append(": "); + } + builder.Append(ReturnTypeName).Append(" { ").Append(PropertyKindString).Append(" }"); + if (HasThrows) + { + builder.Append(" throws"); + } + } + else + { + builder.Append(base.ToString()); + builder.Append(" (").Append(ParametersToString()).Append(")"); + if (HasThrows) + { + builder.Append(" throws"); + } + + builder.Append(" -> "); + if (TypeSpec.IsNullOrEmptyTuple(ReturnTypeSpec)) + { + builder.Append("()"); + } + else + { + builder.Append(ReturnTypeSpec); + } + } + return builder.ToString(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs index 818b79522f3a..0e2a8cf3a15e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs @@ -7,121 +7,137 @@ using System.Xml.Linq; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftXmlReflection { - public class GenericDeclaration { - public GenericDeclaration () - { - Constraints = new List (); - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class GenericDeclaration + { + public GenericDeclaration() + { + Constraints = new List(); + } - public GenericDeclaration (string name) - : this () - { - Name = name; - } + public GenericDeclaration(string name) + : this() + { + Name = name; + } - public GenericDeclaration (GenericDeclaration other) - : this () - { - Name = other.Name; - foreach (var constraint in other.Constraints) { - Constraints.Add (BaseConstraint.CopyOf (constraint)); - } - } + public GenericDeclaration(GenericDeclaration other) + : this() + { + Name = other.Name; + foreach (var constraint in other.Constraints) + { + Constraints.Add(BaseConstraint.CopyOf(constraint)); + } + } - public string Name { get; set; } - public List Constraints { get; private set; } + public string Name { get; set; } + public List Constraints { get; private set; } - public bool IsProtocolConstrained (TypeMapper mapper) - { - if (Constraints.Count == 0) - return false; - foreach (BaseConstraint bc in Constraints) { - Entity ent = null; - InheritanceConstraint inh = bc as InheritanceConstraint; - if (inh != null) { - ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); - } else { - EqualityConstraint eq = (EqualityConstraint)bc; - ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); - } - if (ent == null) - continue; // shouldn't happen - if (ent.EntityType != EntityType.Protocol) - return false; - } - return true; - } + public bool IsProtocolConstrained(TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) + { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) + { + ent = mapper.GetEntityForTypeSpec(inh.InheritsTypeSpec); + } + else + { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec(eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType != EntityType.Protocol) + return false; + } + return true; + } - public bool IsAssociatedTypeProtocolConstrained (TypeMapper mapper) - { - if (Constraints.Count == 0) - return false; - foreach (BaseConstraint bc in Constraints) { - Entity ent = null; - InheritanceConstraint inh = bc as InheritanceConstraint; - if (inh != null) { - ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); - } else { - EqualityConstraint eq = (EqualityConstraint)bc; - ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); - } - if (ent == null) - continue; // shouldn't happen - if (ent.EntityType != EntityType.Protocol) - return false; - if (ent.Type is ProtocolDeclaration proto && !proto.IsExistential) - return true; - } - return false; - } + public bool IsAssociatedTypeProtocolConstrained(TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) + { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) + { + ent = mapper.GetEntityForTypeSpec(inh.InheritsTypeSpec); + } + else + { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec(eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType != EntityType.Protocol) + return false; + if (ent.Type is ProtocolDeclaration proto && !proto.IsExistential) + return true; + } + return false; + } - public bool IsClassConstrained (TypeMapper mapper) - { - if (Constraints.Count == 0) - return false; - foreach (BaseConstraint bc in Constraints) { - Entity ent = null; - InheritanceConstraint inh = bc as InheritanceConstraint; - if (inh != null) { - ent = mapper.GetEntityForTypeSpec (inh.InheritsTypeSpec); - } else { - EqualityConstraint eq = (EqualityConstraint)bc; - ent = mapper.GetEntityForTypeSpec (eq.Type2Spec); - } - if (ent == null) - continue; // shouldn't happen - if (ent.EntityType == EntityType.Class) - return true; - } - return false; + public bool IsClassConstrained(TypeMapper mapper) + { + if (Constraints.Count == 0) + return false; + foreach (BaseConstraint bc in Constraints) + { + Entity ent = null; + InheritanceConstraint inh = bc as InheritanceConstraint; + if (inh != null) + { + ent = mapper.GetEntityForTypeSpec(inh.InheritsTypeSpec); + } + else + { + EqualityConstraint eq = (EqualityConstraint)bc; + ent = mapper.GetEntityForTypeSpec(eq.Type2Spec); + } + if (ent == null) + continue; // shouldn't happen + if (ent.EntityType == EntityType.Class) + return true; + } + return false; - } + } - public static List FromXElement (TypeAliasFolder folder, XElement generic) - { - List decls = new List (); - if (generic == null) - return decls; - decls.AddRange (from decl in generic.Descendants ("param") select new GenericDeclaration ((string)decl.Attribute ("name"))); + public static List FromXElement(TypeAliasFolder folder, XElement generic) + { + List decls = new List(); + if (generic == null) + return decls; + decls.AddRange(from decl in generic.Descendants("param") select new GenericDeclaration((string)decl.Attribute("name"))); - var constraints = from constr in generic.Descendants ("where") select BaseConstraint.FromXElement (folder, constr); - foreach (BaseConstraint constr in constraints) { - GenericDeclaration decl = FindGenericDeclFor (constr, decls); - if (decl != null) - decl.Constraints.Add (constr); - } + var constraints = from constr in generic.Descendants("where") select BaseConstraint.FromXElement(folder, constr); + foreach (BaseConstraint constr in constraints) + { + GenericDeclaration decl = FindGenericDeclFor(constr, decls); + if (decl != null) + decl.Constraints.Add(constr); + } - return decls; - } + return decls; + } - static GenericDeclaration FindGenericDeclFor (BaseConstraint constraint, List decls) - { - string nameToMatch = constraint.EffectiveTypeName (); - if (nameToMatch == null) - return null; - return decls.FirstOrDefault (d => d.Name == nameToMatch); - } - } + static GenericDeclaration FindGenericDeclFor(BaseConstraint constraint, List decls) + { + string nameToMatch = constraint.EffectiveTypeName(); + if (nameToMatch == null) + return null; + return decls.FirstOrDefault(d => d.Name == nameToMatch); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs index 1c66b0737dfa..f0b53d84e973 100644 --- a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs +++ b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs @@ -7,38 +7,44 @@ using System.Xml.Linq; using SwiftReflector.IOUtils; -namespace SwiftReflector.SwiftXmlReflection { - public class GenericDeclarationCollection : List, IXElementConvertible { - public GenericDeclarationCollection () - : base () - { - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class GenericDeclarationCollection : List, IXElementConvertible + { + public GenericDeclarationCollection() + : base() + { + } - public GenericDeclarationCollection (int capacity) - : base (capacity) - { - } + public GenericDeclarationCollection(int capacity) + : base(capacity) + { + } - public XElement ToXElement () - { - if (Count == 0) - return null; - XElement genparms = new XElement ("genericparameters"); + public XElement ToXElement() + { + if (Count == 0) + return null; + XElement genparms = new XElement("genericparameters"); - foreach (GenericDeclaration decl in this) { - XElement param = new XElement ("param", new XAttribute ("name", decl.Name)); - genparms.Add (param); - } - foreach (GenericDeclaration decl in this) { - if (decl.Constraints.Count > 0) { - foreach (BaseConstraint bc in decl.Constraints) { - XElement bcel = bc.ToXElement (); - if (bcel != null) - genparms.Add (bcel); - } - } - } - return genparms; - } - } + foreach (GenericDeclaration decl in this) + { + XElement param = new XElement("param", new XAttribute("name", decl.Name)); + genparms.Add(param); + } + foreach (GenericDeclaration decl in this) + { + if (decl.Constraints.Count > 0) + { + foreach (BaseConstraint bc in decl.Constraints) + { + XElement bcel = bc.ToXElement(); + if (bcel != null) + genparms.Add(bcel); + } + } + } + return genparms; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs b/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs index 2924d1300303..d1f063536ad8 100644 --- a/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs +++ b/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SwiftReflector.SwiftXmlReflection { - public class GenericReferenceAssociatedTypeProtocol { - public NamedTypeSpec GenericPart { get; set; } - public ProtocolDeclaration Protocol { get; set; } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class GenericReferenceAssociatedTypeProtocol + { + public NamedTypeSpec GenericPart { get; set; } + public ProtocolDeclaration Protocol { get; set; } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs index 32adc91891ef..1377e7f92de9 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs @@ -9,71 +9,80 @@ using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class Inheritance : IXElementConvertible { - public Inheritance (string inheritedTypeName, InheritanceKind inheritanceKind) - { - this.InheritanceKind = inheritanceKind; - InheritedTypeName = inheritedTypeName; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class Inheritance : IXElementConvertible + { + public Inheritance(string inheritedTypeName, InheritanceKind inheritanceKind) + { + this.InheritanceKind = inheritanceKind; + InheritedTypeName = inheritedTypeName; + } - public InheritanceKind InheritanceKind { get; private set; } + public InheritanceKind InheritanceKind { get; private set; } - string inheritedTypeName; - public string InheritedTypeName { - get { return inheritedTypeName; } - set { - inheritedTypeName = Exceptions.ThrowOnNull (value, nameof(value)); - try { - InheritedTypeSpec = TypeSpecParser.Parse (inheritedTypeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 7, $"Unable to parse type name '{inheritedTypeName}': {ex.Message}"); - } - } - } - public TypeSpec InheritedTypeSpec { get; private set; } + string inheritedTypeName; + public string InheritedTypeName + { + get { return inheritedTypeName; } + set + { + inheritedTypeName = Exceptions.ThrowOnNull(value, nameof(value)); + try + { + InheritedTypeSpec = TypeSpecParser.Parse(inheritedTypeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 7, $"Unable to parse type name '{inheritedTypeName}': {ex.Message}"); + } + } + } + public TypeSpec InheritedTypeSpec { get; private set; } - public static Inheritance FromXElement (TypeAliasFolder folder, XElement elem) - { - string typeName = (string)elem.Attribute ("type"); - string inheritanceKindStr = (string)elem.Attribute ("inheritanceKind"); - InheritanceKind kind = ToInheritanceKind (inheritanceKindStr); - var inheritance = new Inheritance (typeName, kind); - inheritance.InheritedTypeSpec = folder.FoldAlias (null, inheritance.InheritedTypeSpec); - return inheritance; - } + public static Inheritance FromXElement(TypeAliasFolder folder, XElement elem) + { + string typeName = (string)elem.Attribute("type"); + string inheritanceKindStr = (string)elem.Attribute("inheritanceKind"); + InheritanceKind kind = ToInheritanceKind(inheritanceKindStr); + var inheritance = new Inheritance(typeName, kind); + inheritance.InheritedTypeSpec = folder.FoldAlias(null, inheritance.InheritedTypeSpec); + return inheritance; + } - public XElement ToXElement () - { - return new XElement ("inherit", new XAttribute ("type", InheritedTypeName), - new XAttribute ("inheritanceKind", ToString (InheritanceKind))); - } + public XElement ToXElement() + { + return new XElement("inherit", new XAttribute("type", InheritedTypeName), + new XAttribute("inheritanceKind", ToString(InheritanceKind))); + } - static string ToString (InheritanceKind kind) - { - switch (kind) { - case InheritanceKind.Class: - return "class"; - case InheritanceKind.Protocol: - return "protocol"; - default: - throw new ArgumentOutOfRangeException (nameof(kind)); - } - } + static string ToString(InheritanceKind kind) + { + switch (kind) + { + case InheritanceKind.Class: + return "class"; + case InheritanceKind.Protocol: + return "protocol"; + default: + throw new ArgumentOutOfRangeException(nameof(kind)); + } + } - static InheritanceKind ToInheritanceKind (string kindStr) - { - Exceptions.ThrowOnNull (kindStr, nameof(kindStr)); - switch (kindStr) { - case "protocol": - return InheritanceKind.Protocol; - case "class": - return InheritanceKind.Class; - default: - throw new ArgumentOutOfRangeException (nameof (kindStr), String.Format ("Expected either protocol or class, but got {0}.", - kindStr)); - } - } - } + static InheritanceKind ToInheritanceKind(string kindStr) + { + Exceptions.ThrowOnNull(kindStr, nameof(kindStr)); + switch (kindStr) + { + case "protocol": + return InheritanceKind.Protocol; + case "class": + return InheritanceKind.Class; + default: + throw new ArgumentOutOfRangeException(nameof(kindStr), String.Format("Expected either protocol or class, but got {0}.", + kindStr)); + } + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/Member.cs b/src/SwiftReflector/SwiftXmlReflection/Member.cs index a32859f3d383..6a3a4ddf1233 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Member.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Member.cs @@ -6,44 +6,49 @@ using System.Xml.Linq; using SwiftReflector.IOUtils; -namespace SwiftReflector.SwiftXmlReflection { - public abstract class Member : BaseDeclaration, IXElementConvertible { - protected Member () - : base () - { - } - - protected Member (Member other) - : base (other) - { - } - - public bool IsProtocolMember { get { return Parent != null && Parent is ProtocolDeclaration; } } - - #region IXElementConvertible implementation - - public XElement ToXElement () - { - return MakeXElement (); - } - - protected virtual XElement MakeXElement () - { - throw new NotImplementedException (); - } - #endregion - - public abstract bool HasDynamicSelf { - get; - } - - public abstract bool HasDynamicSelfInReturnOnly { - get; - } - - public abstract bool HasDynamicSelfInArguments { - get; - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public abstract class Member : BaseDeclaration, IXElementConvertible + { + protected Member() + : base() + { + } + + protected Member(Member other) + : base(other) + { + } + + public bool IsProtocolMember { get { return Parent != null && Parent is ProtocolDeclaration; } } + + #region IXElementConvertible implementation + + public XElement ToXElement() + { + return MakeXElement(); + } + + protected virtual XElement MakeXElement() + { + throw new NotImplementedException(); + } + #endregion + + public abstract bool HasDynamicSelf + { + get; + } + + public abstract bool HasDynamicSelfInReturnOnly + { + get; + } + + public abstract bool HasDynamicSelfInArguments + { + get; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs index 8d8ed94c94c1..5a24894f5f4f 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs @@ -7,183 +7,209 @@ using System.Xml.Linq; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftXmlReflection { - public class ModuleDeclaration { - public ModuleDeclaration () - { - Declarations = new List (); - Extensions = new List (); - Operators = new List (); - TypeAliases = new List (); - } - - public ModuleDeclaration (string name) - : this () - { - Name = name; - } - - public string Name { get; set; } - public bool IsUnrooted { get; private set; } - - public ModuleDeclaration MakeUnrooted () - { - if (IsUnrooted) - return this; - ModuleDeclaration unrooted = new ModuleDeclaration (); - unrooted.IsUnrooted = true; - unrooted.Name = Name; - return unrooted; - } - - public List Declarations { get; private set; } - public List TypeAliases { get; private set; } - - public static ModuleDeclaration FromXElement (XElement elem, TypeDatabase typeDatabase) - { - ModuleDeclaration decl = new ModuleDeclaration { - Name = (string)elem.Attribute ("name"), - SwiftCompilerVersion = new Version((string)elem.Attribute("swiftVersion") ?? "3.1") - }; - - decl.TypeAliases.AddRange (elem.Descendants ("typealias").Select (al => TypeAliasDeclaration.FromXElement (decl.Name, al))); - var folder = new TypeAliasFolder (decl.TypeAliases); - folder.AddDatabaseAliases (typeDatabase); - - // non extensions - foreach (var child in elem.Elements()) { - if (child.Name == "extension") { - decl.Extensions.Add (ExtensionDeclaration.FromXElement (folder, child, decl)); - } else if (child.Name == "operator") { - decl.Operators.Add (OperatorDeclaration.FromXElement (child, child.Attribute ("moduleName")?.Value)); - } else { - decl.Declarations.Add (BaseDeclaration.FromXElement (folder, child, decl, null)); - } - } - return decl; - } - - public Version SwiftCompilerVersion { get; set; } - public bool IsEmpty () - { - return Declarations.Count == 0 && Extensions.Count == 0; - } - - public IEnumerable Classes { get { return Declarations.OfType ().Where (cd => !(cd is ProtocolDeclaration)); } } - public IEnumerable Structs { get { return Declarations.OfType (); } } - public IEnumerable Enums { get { return Declarations.OfType (); } } - public IEnumerable Protocols { get { return Declarations.OfType (); } } - public IEnumerable Functions { get { return Declarations.OfType (); } } - public IEnumerable Properties { get { return Declarations.OfType (); } } - public IEnumerable TopLevelFunctions { get { return Functions.Where (f => f.Parent == null && f.Access == Accessibility.Public || f.Access == Accessibility.Open); } } - public IEnumerable TopLevelProperties { get { return Properties.Where (p => p.Parent == null && p.Access == Accessibility.Public || p.Access == Accessibility.Open); } } - public List Extensions { get; private set; } - public List Operators { get; private set; } - - - public bool IsCompilerCompatibleWith(Version targetCompilerVersion) - { - // yes, this could be an equality comparison, but I expect some - // level of backwards compatability at some point, so flesh it out now. - switch (SwiftCompilerVersion.Major) { - case 2: - return false; // No. Just no. - case 3: - return targetCompilerVersion.Major == 3; - case 4: - return targetCompilerVersion.Major == 4; - case 5: - return targetCompilerVersion.Major == 5; - default: - return false; // not yet, thanks. - } - } - - public List AllClasses { - get { - return AllFooHelper (); - } - } - - public List AllStructs { - get { - return AllFooHelper (); - } - } - - public List AllEnums { - get { - return AllFooHelper (); - } - } - - public List AllProtocols { - get { - // no chicanery here - all protocol definitions are top-level - return Protocols.ToList (); - } - } - - List AllFooHelper () where T : TypeDeclaration - { - List ts = new List (); - AddAllInto (Classes, ts); - AddAllInto (Structs, ts); - AddAllInto (Enums, ts); - return ts; - } - - - void AddAllInto (IEnumerable someTypes, List repository) where T : TypeDeclaration - { - foreach (TypeDeclaration t in someTypes) { - if (t is T) - repository.Add ((T)t); - AddAllInto (t.InnerClasses, repository); - AddAllInto (t.InnerStructs, repository); - AddAllInto (t.InnerEnums, repository); - } - } - - - public List AllTypesAndTopLevelDeclarations { - get { - List decls = new List (); - AddAllDeclsInto (Declarations, decls); - return decls; - } - } - - void AddAllDeclsInto (IEnumerable someDecls, List allDecls) - { - foreach (BaseDeclaration d in someDecls) { - allDecls.Add (d); - TypeDeclaration t = d as TypeDeclaration; - if (t != null) { - AddAllDeclsInto (t.InnerClasses, allDecls); - AddAllDeclsInto (t.InnerStructs, allDecls); - AddAllDeclsInto (t.InnerEnums, allDecls); - } - } - } - - public List AllTypes { - get { - List types = new List (); - AddAllTypesInto (Declarations.OfType (), types); - return types; - } - } - - void AddAllTypesInto (IEnumerable someTypes, List allTypes) - { - foreach (TypeDeclaration t in someTypes) { - allTypes.Add (t); - AddAllTypesInto (t.InnerClasses, allTypes); - AddAllTypesInto (t.InnerStructs, allTypes); - AddAllTypesInto (t.InnerEnums, allTypes); - } - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class ModuleDeclaration + { + public ModuleDeclaration() + { + Declarations = new List(); + Extensions = new List(); + Operators = new List(); + TypeAliases = new List(); + } + + public ModuleDeclaration(string name) + : this() + { + Name = name; + } + + public string Name { get; set; } + public bool IsUnrooted { get; private set; } + + public ModuleDeclaration MakeUnrooted() + { + if (IsUnrooted) + return this; + ModuleDeclaration unrooted = new ModuleDeclaration(); + unrooted.IsUnrooted = true; + unrooted.Name = Name; + return unrooted; + } + + public List Declarations { get; private set; } + public List TypeAliases { get; private set; } + + public static ModuleDeclaration FromXElement(XElement elem, TypeDatabase typeDatabase) + { + ModuleDeclaration decl = new ModuleDeclaration + { + Name = (string)elem.Attribute("name"), + SwiftCompilerVersion = new Version((string)elem.Attribute("swiftVersion") ?? "3.1") + }; + + decl.TypeAliases.AddRange(elem.Descendants("typealias").Select(al => TypeAliasDeclaration.FromXElement(decl.Name, al))); + var folder = new TypeAliasFolder(decl.TypeAliases); + folder.AddDatabaseAliases(typeDatabase); + + // non extensions + foreach (var child in elem.Elements()) + { + if (child.Name == "extension") + { + decl.Extensions.Add(ExtensionDeclaration.FromXElement(folder, child, decl)); + } + else if (child.Name == "operator") + { + decl.Operators.Add(OperatorDeclaration.FromXElement(child, child.Attribute("moduleName")?.Value)); + } + else + { + decl.Declarations.Add(BaseDeclaration.FromXElement(folder, child, decl, null)); + } + } + return decl; + } + + public Version SwiftCompilerVersion { get; set; } + public bool IsEmpty() + { + return Declarations.Count == 0 && Extensions.Count == 0; + } + + public IEnumerable Classes { get { return Declarations.OfType().Where(cd => !(cd is ProtocolDeclaration)); } } + public IEnumerable Structs { get { return Declarations.OfType(); } } + public IEnumerable Enums { get { return Declarations.OfType(); } } + public IEnumerable Protocols { get { return Declarations.OfType(); } } + public IEnumerable Functions { get { return Declarations.OfType(); } } + public IEnumerable Properties { get { return Declarations.OfType(); } } + public IEnumerable TopLevelFunctions { get { return Functions.Where(f => f.Parent == null && f.Access == Accessibility.Public || f.Access == Accessibility.Open); } } + public IEnumerable TopLevelProperties { get { return Properties.Where(p => p.Parent == null && p.Access == Accessibility.Public || p.Access == Accessibility.Open); } } + public List Extensions { get; private set; } + public List Operators { get; private set; } + + + public bool IsCompilerCompatibleWith(Version targetCompilerVersion) + { + // yes, this could be an equality comparison, but I expect some + // level of backwards compatability at some point, so flesh it out now. + switch (SwiftCompilerVersion.Major) + { + case 2: + return false; // No. Just no. + case 3: + return targetCompilerVersion.Major == 3; + case 4: + return targetCompilerVersion.Major == 4; + case 5: + return targetCompilerVersion.Major == 5; + default: + return false; // not yet, thanks. + } + } + + public List AllClasses + { + get + { + return AllFooHelper(); + } + } + + public List AllStructs + { + get + { + return AllFooHelper(); + } + } + + public List AllEnums + { + get + { + return AllFooHelper(); + } + } + + public List AllProtocols + { + get + { + // no chicanery here - all protocol definitions are top-level + return Protocols.ToList(); + } + } + + List AllFooHelper() where T : TypeDeclaration + { + List ts = new List(); + AddAllInto(Classes, ts); + AddAllInto(Structs, ts); + AddAllInto(Enums, ts); + return ts; + } + + + void AddAllInto(IEnumerable someTypes, List repository) where T : TypeDeclaration + { + foreach (TypeDeclaration t in someTypes) + { + if (t is T) + repository.Add((T)t); + AddAllInto(t.InnerClasses, repository); + AddAllInto(t.InnerStructs, repository); + AddAllInto(t.InnerEnums, repository); + } + } + + + public List AllTypesAndTopLevelDeclarations + { + get + { + List decls = new List(); + AddAllDeclsInto(Declarations, decls); + return decls; + } + } + + void AddAllDeclsInto(IEnumerable someDecls, List allDecls) + { + foreach (BaseDeclaration d in someDecls) + { + allDecls.Add(d); + TypeDeclaration t = d as TypeDeclaration; + if (t != null) + { + AddAllDeclsInto(t.InnerClasses, allDecls); + AddAllDeclsInto(t.InnerStructs, allDecls); + AddAllDeclsInto(t.InnerEnums, allDecls); + } + } + } + + public List AllTypes + { + get + { + List types = new List(); + AddAllTypesInto(Declarations.OfType(), types); + return types; + } + } + + void AddAllTypesInto(IEnumerable someTypes, List allTypes) + { + foreach (TypeDeclaration t in someTypes) + { + allTypes.Add(t); + AddAllTypesInto(t.InnerClasses, allTypes); + AddAllTypesInto(t.InnerStructs, allTypes); + AddAllTypesInto(t.InnerEnums, allTypes); + } + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs index c45f5e86d699..07b8bb2ea0b4 100644 --- a/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs @@ -5,46 +5,49 @@ using System.Collections.Generic; using System.Xml.Linq; -namespace SwiftReflector.SwiftXmlReflection { - public class OperatorDeclaration { - public OperatorDeclaration () - { - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class OperatorDeclaration + { + public OperatorDeclaration() + { + } - public string ModuleName { get; private set; } - public string Name { get; private set; } - public OperatorType OperatorType { get; private set; } - public string PrecedenceGroup { get; private set; } + public string ModuleName { get; private set; } + public string Name { get; private set; } + public OperatorType OperatorType { get; private set; } + public string PrecedenceGroup { get; private set; } - public XElement ToXElement () - { - var xobjects = new List (); - GatherXObjects (xobjects); - XElement typeDecl = new XElement ("operator", xobjects.ToArray ()); - return typeDecl; - } + public XElement ToXElement() + { + var xobjects = new List(); + GatherXObjects(xobjects); + XElement typeDecl = new XElement("operator", xobjects.ToArray()); + return typeDecl; + } - void GatherXObjects (List xobjects) - { - xobjects.Add (new XAttribute ("name", Name)); - if (PrecedenceGroup != null) - xobjects.Add (new XAttribute ("precedenceGroup", PrecedenceGroup)); - xobjects.Add (new XAttribute ("operatorKind", OperatorType.ToString ())); - } + void GatherXObjects(List xobjects) + { + xobjects.Add(new XAttribute("name", Name)); + if (PrecedenceGroup != null) + xobjects.Add(new XAttribute("precedenceGroup", PrecedenceGroup)); + xobjects.Add(new XAttribute("operatorKind", OperatorType.ToString())); + } - public static OperatorDeclaration FromXElement (XElement elem, string module) - { - return new OperatorDeclaration () { - ModuleName = module ?? elem.Attribute ("moduleName")?.Value ?? "", - Name = elem.Attribute ("name").Value, - PrecedenceGroup = NullOnNullOrEmpty (elem.Attribute ("precedenceGroup")?.Value), - OperatorType = FunctionDeclaration.OperatorTypeFromElement ((string)elem.Attribute ("operatorKind")) - }; - } + public static OperatorDeclaration FromXElement(XElement elem, string module) + { + return new OperatorDeclaration() + { + ModuleName = module ?? elem.Attribute("moduleName")?.Value ?? "", + Name = elem.Attribute("name").Value, + PrecedenceGroup = NullOnNullOrEmpty(elem.Attribute("precedenceGroup")?.Value), + OperatorType = FunctionDeclaration.OperatorTypeFromElement((string)elem.Attribute("operatorKind")) + }; + } - static string NullOnNullOrEmpty (string s) - { - return String.IsNullOrEmpty (s) ? null : s; - } - } + static string NullOnNullOrEmpty(string s) + { + return String.IsNullOrEmpty(s) ? null : s; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs index b319cae0085b..3ef94e0bd034 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs @@ -10,206 +10,228 @@ using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class ParameterItem : IXElementConvertible { - public static string kInOutMarker = "inout "; - public ParameterItem () - { - } - - public ParameterItem (ParameterItem pi) - { - PublicName = pi.PublicName; - PrivateName = pi.PrivateName; - TypeName = pi.TypeName; - IsInOut = pi.IsInOut; - IsVariadic = pi.IsVariadic; - } - - public string PublicName { get; set; } - public string PrivateName { get; set; } - public bool NameIsRequired { get { return !String.IsNullOrEmpty (PublicName); } } - public bool IsVariadic { get; set; } - - string typeName; - public string TypeName { - get { return typeName; } - set { - typeName = Exceptions.ThrowOnNull (value, nameof(value)); - try { - typeSpec = TypeSpecParser.Parse (typeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 2, $"Unable to parse type name '{typeName}': {ex.Message}"); - } - } - } - TypeSpec typeSpec; - public TypeSpec TypeSpec { - get { return typeSpec; } - set { - Exceptions.ThrowOnNull (value, "value"); - typeSpec = value; - typeName = value.ToString (); - } - } - public bool IsInOut { get; set; } - - #region IXElementConvertible implementation - - public XElement ToXElement () - { - return new XElement ("parameter", - new XAttribute ("publicName", PublicName), - new XAttribute ("privateName", PrivateName), - new XAttribute ("type", TypeName), - new XAttribute ("isVariadic", IsVariadic) - ); - } - - #endregion - - public static List> ParameterListListFromXElement (TypeAliasFolder folder, XElement elem) - { - var plists = from plelem in elem.Elements ("parameterlist") - orderby (int)plelem.Attribute ("index") - select ParameterListFromXElement (folder, plelem); - return plists.ToList (); - } - - public static List ParameterListFromXElement (TypeAliasFolder folder, XElement elem) - { - var indexed = from pelem in elem.Elements ("parameter") - orderby (int)pelem.Attribute ("index") - select ParameterItem.FromXElement (folder, pelem); - - return indexed.ToList (); - } - - public static ParameterItem FromXElement (TypeAliasFolder folder, XElement elem) - { - ParameterItem pi = new ParameterItem { - PublicName = (string)elem.Attribute ("publicName"), - PrivateName = (string)elem.Attribute ("privateName"), - TypeName = (string)elem.Attribute ("type"), - IsVariadic = elem.BoolAttribute ("isVariadic"), - }; - pi.IsInOut = pi.TypeSpec.IsInOut; - pi.TypeSpec = folder.FoldAlias (null, pi.TypeSpec); - return pi; - } - - public bool EqualsIgnoreName (ParameterItem other) - { - if (other == null) - return false; - return IsVariadic == other.IsVariadic && this.TypeSpec.Equals (other.TypeSpec); - } - - public bool EqualsIgnoreNamesPartialMatch (ParameterItem other) - { - if (other == null) - return false; - return this.TypeSpec.EqualsPartialMatch (other.TypeSpec); - } - - public static bool AreEqualIgnoreNames (IList pl1, IList pl2) - { - if (pl1.Count != pl2.Count) - return false; - for (int i = 0; i < pl1.Count; i++) { - if (!pl1 [i].EqualsIgnoreName (pl2 [i])) - return false; - } - return true; - } - - public static bool AreEqualIgnoreNamesReferencesInvariant (FunctionDeclaration fn1, IList pl1, - FunctionDeclaration fn2, IList pl2, bool matchPartialNames) - { - if (pl1.Count != pl2.Count) { - return false; - } - - for (int i = 0; i < pl1.Count; i++) { - var p1 = SubstituteSelfFromParent (fn1, pl1 [i]); - var p2 = SubstituteSelfFromParent (fn2, pl2 [i]); - p1 = RecastAsReference (p1); - p2 = RecastAsReference (p2); - - - // Names invariant means TYPE names not parameter names - if (!ParameterNamesMatch (p1, p2)) { - // we give a pass on matching "self". - // this is done because "self" is a keyword in swift - // and when matching a wrapper function, we can't call - // a parameter "self" but have to call it "thisN" where - // N is either an empty string or a number. - // This is because there might be a real parameter named "this" - // and we had to rename it. - // The end result is that we can't use a "this" test, but we - // can use a "self" test. - var parmName1 = p1.NameIsRequired ? p1.PublicName : p1.PrivateName; - var parmName2 = p2.NameIsRequired ? p2.PublicName : p2.PrivateName; - if (parmName1 != "self" && parmName2 != "self") - return false; - } - if (fn1.IsTypeSpecGeneric (p1)) { - if (!fn2.IsTypeSpecGeneric (p2)) - return false; - continue; - } - if (!p1.EqualsIgnoreName (p2)) { - if (matchPartialNames) { - if (!p1.EqualsIgnoreNamesPartialMatch (p2)) - return false; - } else { - return false; - } - } - } - return true; - } - - static ParameterItem SubstituteSelfFromParent (FunctionDeclaration func, ParameterItem p) - { - if (func.Parent == null || !p.TypeSpec.HasDynamicSelf) - return p; - p = new ParameterItem (p); - p.TypeSpec = p.TypeSpec.ReplaceName ("Self", func.Parent.ToFullyQualifiedNameWithGenerics ()); - return p; - } - - static ParameterItem RecastAsReference (ParameterItem p) - { - if (p.IsInOut) { - if (!p.TypeSpec.IsInOut) - p.TypeSpec.IsInOut = true; - return p; - } - if (p.TypeSpec is NamedTypeSpec && p.TypeSpec.ContainsGenericParameters) { - NamedTypeSpec named = (NamedTypeSpec)p.TypeSpec; - // special case - turn UnsafePointer into inout T for matching purposes - if (named.Name == "Swift.UnsafePointer" || named.Name == "Swift.UnsafeMutablePointer") { - p = new ParameterItem (p); - p.TypeSpec = p.TypeSpec.GenericParameters [0]; - p.IsInOut = true; - p.TypeSpec.IsInOut = true; - } - } - return p; - } - - static bool ParameterNamesMatch (ParameterItem p1, ParameterItem p2) - { - // parameters are considered matching if and only if their public names match. - // The following are all DISTINCT - // public func foo (a b: Int) { } - // public func foo (c b: Int) { } - // public func foo (b: Int) { } - the public name is b - // public func foo (_ b: Int) { } - the public name is null or empty - - return p1.PublicName == p2.PublicName; - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class ParameterItem : IXElementConvertible + { + public static string kInOutMarker = "inout "; + public ParameterItem() + { + } + + public ParameterItem(ParameterItem pi) + { + PublicName = pi.PublicName; + PrivateName = pi.PrivateName; + TypeName = pi.TypeName; + IsInOut = pi.IsInOut; + IsVariadic = pi.IsVariadic; + } + + public string PublicName { get; set; } + public string PrivateName { get; set; } + public bool NameIsRequired { get { return !String.IsNullOrEmpty(PublicName); } } + public bool IsVariadic { get; set; } + + string typeName; + public string TypeName + { + get { return typeName; } + set + { + typeName = Exceptions.ThrowOnNull(value, nameof(value)); + try + { + typeSpec = TypeSpecParser.Parse(typeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 2, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + TypeSpec typeSpec; + public TypeSpec TypeSpec + { + get { return typeSpec; } + set + { + Exceptions.ThrowOnNull(value, "value"); + typeSpec = value; + typeName = value.ToString(); + } + } + public bool IsInOut { get; set; } + + #region IXElementConvertible implementation + + public XElement ToXElement() + { + return new XElement("parameter", + new XAttribute("publicName", PublicName), + new XAttribute("privateName", PrivateName), + new XAttribute("type", TypeName), + new XAttribute("isVariadic", IsVariadic) + ); + } + + #endregion + + public static List> ParameterListListFromXElement(TypeAliasFolder folder, XElement elem) + { + var plists = from plelem in elem.Elements("parameterlist") + orderby (int)plelem.Attribute("index") + select ParameterListFromXElement(folder, plelem); + return plists.ToList(); + } + + public static List ParameterListFromXElement(TypeAliasFolder folder, XElement elem) + { + var indexed = from pelem in elem.Elements("parameter") + orderby (int)pelem.Attribute("index") + select ParameterItem.FromXElement(folder, pelem); + + return indexed.ToList(); + } + + public static ParameterItem FromXElement(TypeAliasFolder folder, XElement elem) + { + ParameterItem pi = new ParameterItem + { + PublicName = (string)elem.Attribute("publicName"), + PrivateName = (string)elem.Attribute("privateName"), + TypeName = (string)elem.Attribute("type"), + IsVariadic = elem.BoolAttribute("isVariadic"), + }; + pi.IsInOut = pi.TypeSpec.IsInOut; + pi.TypeSpec = folder.FoldAlias(null, pi.TypeSpec); + return pi; + } + + public bool EqualsIgnoreName(ParameterItem other) + { + if (other == null) + return false; + return IsVariadic == other.IsVariadic && this.TypeSpec.Equals(other.TypeSpec); + } + + public bool EqualsIgnoreNamesPartialMatch(ParameterItem other) + { + if (other == null) + return false; + return this.TypeSpec.EqualsPartialMatch(other.TypeSpec); + } + + public static bool AreEqualIgnoreNames(IList pl1, IList pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) + { + if (!pl1[i].EqualsIgnoreName(pl2[i])) + return false; + } + return true; + } + + public static bool AreEqualIgnoreNamesReferencesInvariant(FunctionDeclaration fn1, IList pl1, + FunctionDeclaration fn2, IList pl2, bool matchPartialNames) + { + if (pl1.Count != pl2.Count) + { + return false; + } + + for (int i = 0; i < pl1.Count; i++) + { + var p1 = SubstituteSelfFromParent(fn1, pl1[i]); + var p2 = SubstituteSelfFromParent(fn2, pl2[i]); + p1 = RecastAsReference(p1); + p2 = RecastAsReference(p2); + + + // Names invariant means TYPE names not parameter names + if (!ParameterNamesMatch(p1, p2)) + { + // we give a pass on matching "self". + // this is done because "self" is a keyword in swift + // and when matching a wrapper function, we can't call + // a parameter "self" but have to call it "thisN" where + // N is either an empty string or a number. + // This is because there might be a real parameter named "this" + // and we had to rename it. + // The end result is that we can't use a "this" test, but we + // can use a "self" test. + var parmName1 = p1.NameIsRequired ? p1.PublicName : p1.PrivateName; + var parmName2 = p2.NameIsRequired ? p2.PublicName : p2.PrivateName; + if (parmName1 != "self" && parmName2 != "self") + return false; + } + if (fn1.IsTypeSpecGeneric(p1)) + { + if (!fn2.IsTypeSpecGeneric(p2)) + return false; + continue; + } + if (!p1.EqualsIgnoreName(p2)) + { + if (matchPartialNames) + { + if (!p1.EqualsIgnoreNamesPartialMatch(p2)) + return false; + } + else + { + return false; + } + } + } + return true; + } + + static ParameterItem SubstituteSelfFromParent(FunctionDeclaration func, ParameterItem p) + { + if (func.Parent == null || !p.TypeSpec.HasDynamicSelf) + return p; + p = new ParameterItem(p); + p.TypeSpec = p.TypeSpec.ReplaceName("Self", func.Parent.ToFullyQualifiedNameWithGenerics()); + return p; + } + + static ParameterItem RecastAsReference(ParameterItem p) + { + if (p.IsInOut) + { + if (!p.TypeSpec.IsInOut) + p.TypeSpec.IsInOut = true; + return p; + } + if (p.TypeSpec is NamedTypeSpec && p.TypeSpec.ContainsGenericParameters) + { + NamedTypeSpec named = (NamedTypeSpec)p.TypeSpec; + // special case - turn UnsafePointer into inout T for matching purposes + if (named.Name == "Swift.UnsafePointer" || named.Name == "Swift.UnsafeMutablePointer") + { + p = new ParameterItem(p); + p.TypeSpec = p.TypeSpec.GenericParameters[0]; + p.IsInOut = true; + p.TypeSpec.IsInOut = true; + } + } + return p; + } + + static bool ParameterNamesMatch(ParameterItem p1, ParameterItem p2) + { + // parameters are considered matching if and only if their public names match. + // The following are all DISTINCT + // public func foo (a b: Int) { } + // public func foo (c b: Int) { } + // public func foo (b: Int) { } - the public name is b + // public func foo (_ b: Int) { } - the public name is null or empty + + return p1.PublicName == p2.PublicName; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs index 0c0224659dd8..b67b300c265f 100644 --- a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs @@ -9,167 +9,189 @@ using System.Text; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class PropertyDeclaration : Member { - public PropertyDeclaration () - { - } - - public PropertyDeclaration (PropertyDeclaration other) - : base (other) - { - TypeName = other.TypeName; - Storage = other.Storage; - IsStatic = other.IsStatic; - IsLet = other.IsLet; - IsDeprecated = other.IsDeprecated; - IsUnavailable = other.IsUnavailable; - IsOptional = other.IsOptional; - } - - string typeName; - public string TypeName { - get { - return typeName; - } - set { - typeName = Exceptions.ThrowOnNull (value, nameof(value)); - try { - TypeSpec = TypeSpecParser.Parse (typeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 3, $"Unable to parse type name '{typeName}': {ex.Message}"); - } - } - } - public TypeSpec TypeSpec { get; private set; } - public StorageKind Storage { get; set; } - public bool IsStatic { get; set; } - public bool IsLet { get; set; } - public bool IsDeprecated { get; set; } - public bool IsUnavailable { get; set; } - public bool IsOptional { get; set; } - public bool IsAsync { - get { - var getter = GetGetter (); - return getter == null ? false : getter.IsAsync; - } - } - - public FunctionDeclaration GetGetter () - { - return SearchForPropertyAccessor (FunctionDeclaration.kPropertyGetterPrefix); - } - - public FunctionDeclaration GetSetter () - { - return SearchForPropertyAccessor (FunctionDeclaration.kPropertySetterPrefix); - } - - - FunctionDeclaration SearchForPropertyAccessor (string prefix) - { - var funcs = GetFunctionsToSearch (); - return funcs.FirstOrDefault (f => f.IsProperty && - f.IsStatic == IsStatic && - f.Name.StartsWith (prefix, StringComparison.Ordinal) && - (f.Name.Length == prefix.Length + Name.Length) && - string.CompareOrdinal (f.Name, prefix.Length, Name, 0, Name.Length) == 0); - } - - IEnumerable GetFunctionsToSearch () - { - if (Parent == null) { - return Module.Functions; - } else { - TypeDeclaration parent = Parent as TypeDeclaration; - if (parent == null) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 4, $"Expected property parent to be a TypeDeclaration, but was a {Parent.GetType ().Name}"); - } - return parent.Members.OfType (); - } - } - - public static PropertyDeclaration PropFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) - { - var property = new PropertyDeclaration { - Name = (string)elem.Attribute ("name"), - Module = module, - Parent = parent, - Access = TypeDeclaration.AccessibilityFromString ((string)elem.Attribute ("accessibility")), - TypeName = (string)elem.Attribute ("type"), - Storage = StorageKindFromString ((string)elem.Attribute ("storage")), - IsStatic = elem.BoolAttribute ("isStatic"), - IsLet = elem.BoolAttribute ("isLet"), - IsDeprecated = elem.BoolAttribute("isDeprecated"), - IsUnavailable = elem.BoolAttribute("isUnavailable"), - IsOptional = elem.BoolAttribute("isOptional") - - }; - - property.TypeSpec = folder.FoldAlias (parent, property.TypeSpec); - - return property; - } - - protected override XElement MakeXElement () - { - return new XElement ("property", - new XAttribute ("name", Name), - new XAttribute ("accessibility", Access), - new XAttribute ("type", TypeName), - new XAttribute ("storage", Storage), - new XAttribute ("isStatic", IsStatic), - new XAttribute ("isLet", IsLet), - new XAttribute ("isDeprecated", IsDeprecated), - new XAttribute ("isUnavailable", IsUnavailable), - new XAttribute ("isOptional", IsOptional) - ); - } - - public static StorageKind StorageKindFromString (string value) - { - if (value == null) - return StorageKind.Unknown; - StorageKind storage; - Enum.TryParse (value, out storage); - return storage; - } - - public override string ToString () - { - // Forms: - // access [modfiers] var Name: Type { [get | set] } [throws] - // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] - // access [modifiers] Name(args) -> Type [throws] - - var getter = GetGetter (); - var builder = new StringBuilder (); - builder.Append (Access).Append (" "); - if (IsStatic) - builder.Append ("static "); - if (getter.IsSubscript) { - builder.Append ("subscript ").Append (base.ToString ()); - builder.Append (" [").Append (getter.ParametersToString ()).Append ("]:"); - } else { - builder.Append ("var ").Append (Parent.ToString ()).Append (".").Append (getter.PropertyName); - builder.Append (": "); - } - - builder.Append (getter.ReturnTypeName); - if (GetSetter () != null) { - builder.Append (" { get set }"); - } else { - builder.Append (" { get }"); - } - if (getter.HasThrows) { - builder.Append (" throws"); - } - return builder.ToString (); - } - - public override bool HasDynamicSelf => this.TypeSpec.HasDynamicSelf; - public override bool HasDynamicSelfInReturnOnly => false; - public override bool HasDynamicSelfInArguments => HasDynamicSelf; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class PropertyDeclaration : Member + { + public PropertyDeclaration() + { + } + + public PropertyDeclaration(PropertyDeclaration other) + : base(other) + { + TypeName = other.TypeName; + Storage = other.Storage; + IsStatic = other.IsStatic; + IsLet = other.IsLet; + IsDeprecated = other.IsDeprecated; + IsUnavailable = other.IsUnavailable; + IsOptional = other.IsOptional; + } + + string typeName; + public string TypeName + { + get + { + return typeName; + } + set + { + typeName = Exceptions.ThrowOnNull(value, nameof(value)); + try + { + TypeSpec = TypeSpecParser.Parse(typeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 3, $"Unable to parse type name '{typeName}': {ex.Message}"); + } + } + } + public TypeSpec TypeSpec { get; private set; } + public StorageKind Storage { get; set; } + public bool IsStatic { get; set; } + public bool IsLet { get; set; } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsOptional { get; set; } + public bool IsAsync + { + get + { + var getter = GetGetter(); + return getter == null ? false : getter.IsAsync; + } + } + + public FunctionDeclaration GetGetter() + { + return SearchForPropertyAccessor(FunctionDeclaration.kPropertyGetterPrefix); + } + + public FunctionDeclaration GetSetter() + { + return SearchForPropertyAccessor(FunctionDeclaration.kPropertySetterPrefix); + } + + + FunctionDeclaration SearchForPropertyAccessor(string prefix) + { + var funcs = GetFunctionsToSearch(); + return funcs.FirstOrDefault(f => f.IsProperty && + f.IsStatic == IsStatic && + f.Name.StartsWith(prefix, StringComparison.Ordinal) && + (f.Name.Length == prefix.Length + Name.Length) && + string.CompareOrdinal(f.Name, prefix.Length, Name, 0, Name.Length) == 0); + } + + IEnumerable GetFunctionsToSearch() + { + if (Parent == null) + { + return Module.Functions; + } + else + { + TypeDeclaration parent = Parent as TypeDeclaration; + if (parent == null) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 4, $"Expected property parent to be a TypeDeclaration, but was a {Parent.GetType().Name}"); + } + return parent.Members.OfType(); + } + } + + public static PropertyDeclaration PropFromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) + { + var property = new PropertyDeclaration + { + Name = (string)elem.Attribute("name"), + Module = module, + Parent = parent, + Access = TypeDeclaration.AccessibilityFromString((string)elem.Attribute("accessibility")), + TypeName = (string)elem.Attribute("type"), + Storage = StorageKindFromString((string)elem.Attribute("storage")), + IsStatic = elem.BoolAttribute("isStatic"), + IsLet = elem.BoolAttribute("isLet"), + IsDeprecated = elem.BoolAttribute("isDeprecated"), + IsUnavailable = elem.BoolAttribute("isUnavailable"), + IsOptional = elem.BoolAttribute("isOptional") + + }; + + property.TypeSpec = folder.FoldAlias(parent, property.TypeSpec); + + return property; + } + + protected override XElement MakeXElement() + { + return new XElement("property", + new XAttribute("name", Name), + new XAttribute("accessibility", Access), + new XAttribute("type", TypeName), + new XAttribute("storage", Storage), + new XAttribute("isStatic", IsStatic), + new XAttribute("isLet", IsLet), + new XAttribute("isDeprecated", IsDeprecated), + new XAttribute("isUnavailable", IsUnavailable), + new XAttribute("isOptional", IsOptional) + ); + } + + public static StorageKind StorageKindFromString(string value) + { + if (value == null) + return StorageKind.Unknown; + StorageKind storage; + Enum.TryParse(value, out storage); + return storage; + } + + public override string ToString() + { + // Forms: + // access [modfiers] var Name: Type { [get | set] } [throws] + // access [modifiers] subscript Name [ args ]: Type { get [set] } [throws] + // access [modifiers] Name(args) -> Type [throws] + + var getter = GetGetter(); + var builder = new StringBuilder(); + builder.Append(Access).Append(" "); + if (IsStatic) + builder.Append("static "); + if (getter.IsSubscript) + { + builder.Append("subscript ").Append(base.ToString()); + builder.Append(" [").Append(getter.ParametersToString()).Append("]:"); + } + else + { + builder.Append("var ").Append(Parent.ToString()).Append(".").Append(getter.PropertyName); + builder.Append(": "); + } + + builder.Append(getter.ReturnTypeName); + if (GetSetter() != null) + { + builder.Append(" { get set }"); + } + else + { + builder.Append(" { get }"); + } + if (getter.HasThrows) + { + builder.Append(" throws"); + } + return builder.ToString(); + } + + public override bool HasDynamicSelf => this.TypeSpec.HasDynamicSelf; + public override bool HasDynamicSelfInReturnOnly => false; + public override bool HasDynamicSelfInArguments => HasDynamicSelf; + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs index da245914af25..219f1c61fd27 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs @@ -6,66 +6,74 @@ using System.Linq; using System.Xml.Linq; -namespace SwiftReflector.SwiftXmlReflection { - public class ProtocolDeclaration : ClassDeclaration { - public ProtocolDeclaration () - { - Kind = TypeKind.Protocol; - AssociatedTypes = new List (); - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class ProtocolDeclaration : ClassDeclaration + { + public ProtocolDeclaration() + { + Kind = TypeKind.Protocol; + AssociatedTypes = new List(); + } - protected override TypeDeclaration UnrootedFactory () - { - return new ProtocolDeclaration (); - } + protected override TypeDeclaration UnrootedFactory() + { + return new ProtocolDeclaration(); + } - protected override void GatherXObjects (List xobjects) - { - base.GatherXObjects (xobjects); - if (AssociatedTypes.Count <= 0) - return; - var assocTypes = new List (); - foreach (var assoc in AssociatedTypes) { - var contents = new List (); - assoc.GatherXObjects (contents); - assocTypes.Add (new XElement ("associatedtype", contents.ToArray ())); - } - xobjects.Add (new XElement ("associatedtypes", assocTypes.ToArray ())); - } + protected override void GatherXObjects(List xobjects) + { + base.GatherXObjects(xobjects); + if (AssociatedTypes.Count <= 0) + return; + var assocTypes = new List(); + foreach (var assoc in AssociatedTypes) + { + var contents = new List(); + assoc.GatherXObjects(contents); + assocTypes.Add(new XElement("associatedtype", contents.ToArray())); + } + xobjects.Add(new XElement("associatedtypes", assocTypes.ToArray())); + } - protected override void CompleteUnrooting (TypeDeclaration unrooted) - { - base.CompleteUnrooting (unrooted); - if (unrooted is ProtocolDeclaration pd) { - pd.AssociatedTypes.AddRange (AssociatedTypes); - } - } + protected override void CompleteUnrooting(TypeDeclaration unrooted) + { + base.CompleteUnrooting(unrooted); + if (unrooted is ProtocolDeclaration pd) + { + pd.AssociatedTypes.AddRange(AssociatedTypes); + } + } - public List AssociatedTypes { get; private set; } + public List AssociatedTypes { get; private set; } - public bool HasAssociatedTypes => AssociatedTypes.Count > 0; + public bool HasAssociatedTypes => AssociatedTypes.Count > 0; - public AssociatedTypeDeclaration AssociatedTypeNamed (string name) - { - return AssociatedTypes.FirstOrDefault (at => at.Name == name); - } + public AssociatedTypeDeclaration AssociatedTypeNamed(string name) + { + return AssociatedTypes.FirstOrDefault(at => at.Name == name); + } - public bool HasDynamicSelf { - // you shouldn't cache this. This type is mutable, so that would be bad - get => Members.Any (m => m.HasDynamicSelf); - } + public bool HasDynamicSelf + { + // you shouldn't cache this. This type is mutable, so that would be bad + get => Members.Any(m => m.HasDynamicSelf); + } - public bool HasDynamicSelfInReturnOnly { - get => Members.Any (m => m.HasDynamicSelfInReturnOnly) && !HasDynamicSelfInArguments; - } + public bool HasDynamicSelfInReturnOnly + { + get => Members.Any(m => m.HasDynamicSelfInReturnOnly) && !HasDynamicSelfInArguments; + } - public bool HasDynamicSelfInArguments { - get => Members.Any (m => m.HasDynamicSelfInArguments); - } + public bool HasDynamicSelfInArguments + { + get => Members.Any(m => m.HasDynamicSelfInArguments); + } - public bool IsExistential { - get => !(HasAssociatedTypes || HasDynamicSelfInArguments); - } - } + public bool IsExistential + { + get => !(HasAssociatedTypes || HasDynamicSelfInArguments); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/Reflector.cs b/src/SwiftReflector/SwiftXmlReflection/Reflector.cs index c1ee002a214b..7ee62ad61bec 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Reflector.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Reflector.cs @@ -12,107 +12,123 @@ using System.Text; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftXmlReflection { - public class Reflector { - public const double kCurrentVersion = 1.0; - const double kNextMajorVersion = 2.0; - - public static List FromXml (XDocument doc, TypeDatabase typeDatabase) - { - var xamreflect = doc.Element ("xamreflect"); - var version = xamreflect.DoubleAttribute ("version"); - - if (version < kCurrentVersion || version >= kNextMajorVersion) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 5, $"Unsupported xamreflect version {version}. Current is {kCurrentVersion}"); - } - - try { - List modules = (from module in xamreflect.Descendants ("module") - select ModuleDeclaration.FromXElement (module, typeDatabase)).ToList (); - return modules; - } catch (Exception e) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 6, $"Error while reading XML reflection information: {e.Message}"); - } - } - - public static List FromXml (Stream stm, TypeDatabase typeDatabase) - { - var doc = XDocument.Load (stm); - return FromXml (doc, typeDatabase); - } - - public static List FromXmlFile (string path, TypeDatabase typeDatabase) - { - try { - using (FileStream stm = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)) { - return FromXml (stm, typeDatabase); - } - } catch (Exception e) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 10, e, $"Failed to load xml file '{path}': {e.Message}"); - } - } - - public static List FromXml (string xmlText, TypeDatabase typeDatabase) - { - using (StringReader reader = new StringReader (xmlText)) { - var doc = XDocument.Load (reader); - return FromXml (doc, typeDatabase); - } - } - - public static List FromModules (string executablePath, List searchDirectories, List modules, - IFileProvider provider, string outfileName, out string fullOutputPath) - { - fullOutputPath = PathToXmlFromModules (executablePath, searchDirectories, modules, provider, outfileName); - return FromXmlFile (fullOutputPath, null); - } - - public static string PathToXmlFromModules (string executablePath, List searchDirectories, List modules, - IFileProvider provider, string outfileName) - { - string fullOutputPath = provider.ProvideFileFor (outfileName); - try { - return PathToXmlFromModules (executablePath, searchDirectories, modules, fullOutputPath); - } finally { - provider.NotifyFileDone (outfileName, fullOutputPath); - } - } - - // returns the path to the output XML file - public static string PathToXmlFromModules (string executablePath, List searchDirectories, List modules, - string outfilePath) - { - var args = BuildArgs (searchDirectories, modules, outfilePath); - ExecAndCollect.Run (executablePath, args); - return outfilePath; - } - - static string BuildArgs (List searchDirectories, List modules, string outfilePath) - { - StringBuilder sb = new StringBuilder (); - - // -xamreflect [-I dir]* -o outfilePath module1 [module2 ...] - - sb.Append ("-xamreflect "); - - foreach (string s in searchDirectories) { - sb.Append ("-I "); - sb.Append (QuoteIfNeeded (s)); - } - if (sb.Length > 0) - sb.Append (" "); - sb.Append ("-o ").Append (QuoteIfNeeded (outfilePath)); - sb.Append (" "); - foreach (string s in modules) { - sb.Append (QuoteIfNeeded (s)); - } - return sb.ToString (); - } - - static string QuoteIfNeeded (string s) - { - throw new NotImplementedException (); - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class Reflector + { + public const double kCurrentVersion = 1.0; + const double kNextMajorVersion = 2.0; + + public static List FromXml(XDocument doc, TypeDatabase typeDatabase) + { + var xamreflect = doc.Element("xamreflect"); + var version = xamreflect.DoubleAttribute("version"); + + if (version < kCurrentVersion || version >= kNextMajorVersion) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 5, $"Unsupported xamreflect version {version}. Current is {kCurrentVersion}"); + } + + try + { + List modules = (from module in xamreflect.Descendants("module") + select ModuleDeclaration.FromXElement(module, typeDatabase)).ToList(); + return modules; + } + catch (Exception e) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 6, $"Error while reading XML reflection information: {e.Message}"); + } + } + + public static List FromXml(Stream stm, TypeDatabase typeDatabase) + { + var doc = XDocument.Load(stm); + return FromXml(doc, typeDatabase); + } + + public static List FromXmlFile(string path, TypeDatabase typeDatabase) + { + try + { + using (FileStream stm = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + return FromXml(stm, typeDatabase); + } + } + catch (Exception e) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 10, e, $"Failed to load xml file '{path}': {e.Message}"); + } + } + + public static List FromXml(string xmlText, TypeDatabase typeDatabase) + { + using (StringReader reader = new StringReader(xmlText)) + { + var doc = XDocument.Load(reader); + return FromXml(doc, typeDatabase); + } + } + + public static List FromModules(string executablePath, List searchDirectories, List modules, + IFileProvider provider, string outfileName, out string fullOutputPath) + { + fullOutputPath = PathToXmlFromModules(executablePath, searchDirectories, modules, provider, outfileName); + return FromXmlFile(fullOutputPath, null); + } + + public static string PathToXmlFromModules(string executablePath, List searchDirectories, List modules, + IFileProvider provider, string outfileName) + { + string fullOutputPath = provider.ProvideFileFor(outfileName); + try + { + return PathToXmlFromModules(executablePath, searchDirectories, modules, fullOutputPath); + } + finally + { + provider.NotifyFileDone(outfileName, fullOutputPath); + } + } + + // returns the path to the output XML file + public static string PathToXmlFromModules(string executablePath, List searchDirectories, List modules, + string outfilePath) + { + var args = BuildArgs(searchDirectories, modules, outfilePath); + ExecAndCollect.Run(executablePath, args); + return outfilePath; + } + + static string BuildArgs(List searchDirectories, List modules, string outfilePath) + { + StringBuilder sb = new StringBuilder(); + + // -xamreflect [-I dir]* -o outfilePath module1 [module2 ...] + + sb.Append("-xamreflect "); + + foreach (string s in searchDirectories) + { + sb.Append("-I "); + sb.Append(QuoteIfNeeded(s)); + } + if (sb.Length > 0) + sb.Append(" "); + sb.Append("-o ").Append(QuoteIfNeeded(outfilePath)); + sb.Append(" "); + foreach (string s in modules) + { + sb.Append(QuoteIfNeeded(s)); + } + return sb.ToString(); + } + + static string QuoteIfNeeded(string s) + { + throw new NotImplementedException(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs index e3f880e012f6..5297c2a5f887 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs @@ -4,41 +4,44 @@ using System; using SwiftReflector.ExceptionTools; -namespace SwiftReflector.SwiftXmlReflection { - public class ShamDeclaration : TypeDeclaration { - public ShamDeclaration (string fullName, EntityType type) - { - fullUnrootedName = fullName; - Tuple modName = fullName.SplitModuleFromName (); - unrootedName = modName.Item2; - IsUnrooted = true; - TypeKind kind = TypeKind.Unknown; - switch (type) { - case EntityType.Scalar: - kind = TypeKind.Struct; - break; - case EntityType.Class: - kind = TypeKind.Class; - break; - case EntityType.Struct: - kind = TypeKind.Struct; - break; - case EntityType.Enum: - case EntityType.TrivialEnum: - kind = TypeKind.Enum; - break; - default: - break; - } - Kind = kind; - Module = new ModuleDeclaration (); - Module.Name = modName.Item1; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class ShamDeclaration : TypeDeclaration + { + public ShamDeclaration(string fullName, EntityType type) + { + fullUnrootedName = fullName; + Tuple modName = fullName.SplitModuleFromName(); + unrootedName = modName.Item2; + IsUnrooted = true; + TypeKind kind = TypeKind.Unknown; + switch (type) + { + case EntityType.Scalar: + kind = TypeKind.Struct; + break; + case EntityType.Class: + kind = TypeKind.Class; + break; + case EntityType.Struct: + kind = TypeKind.Struct; + break; + case EntityType.Enum: + case EntityType.TrivialEnum: + kind = TypeKind.Enum; + break; + default: + break; + } + Kind = kind; + Module = new ModuleDeclaration(); + Module.Name = modName.Item1; + } - protected override void GatherXObjects (System.Collections.Generic.List xobjects) - { - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 1, $"Attempt to serialize a sham type for {this.ToFullyQualifiedName (true)}. Likely this type was never fully realized."); - } - } + protected override void GatherXObjects(System.Collections.Generic.List xobjects) + { + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 1, $"Attempt to serialize a sham type for {this.ToFullyQualifiedName(true)}. Likely this type was never fully realized."); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs index 3dcd1173b061..56d3709a434a 100644 --- a/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs @@ -1,17 +1,19 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SwiftReflector.SwiftXmlReflection { - public class StructDeclaration : TypeDeclaration { - public StructDeclaration () - { - Kind = TypeKind.Struct; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class StructDeclaration : TypeDeclaration + { + public StructDeclaration() + { + Kind = TypeKind.Struct; + } - protected override TypeDeclaration UnrootedFactory () - { - return new StructDeclaration (); - } - } + protected override TypeDeclaration UnrootedFactory() + { + return new StructDeclaration(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs index bd5a73b3c68f..be6c97f838ba 100644 --- a/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs @@ -1,20 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SwiftReflector.SwiftXmlReflection { - // this is a pseudo class. - public class SubscriptDeclaration { - public SubscriptDeclaration (FunctionDeclaration getter, FunctionDeclaration setter, FunctionDeclaration materializer) - { - Getter = getter; - Setter = setter; - Materializer = materializer; - } +namespace SwiftReflector.SwiftXmlReflection +{ + // this is a pseudo class. + public class SubscriptDeclaration + { + public SubscriptDeclaration(FunctionDeclaration getter, FunctionDeclaration setter, FunctionDeclaration materializer) + { + Getter = getter; + Setter = setter; + Materializer = materializer; + } - public FunctionDeclaration Getter { get; set; } - public FunctionDeclaration Setter { get; set; } - public FunctionDeclaration Materializer { get; set; } - public bool IsAsync => Getter.IsAsync; - } + public FunctionDeclaration Getter { get; set; } + public FunctionDeclaration Setter { get; set; } + public FunctionDeclaration Materializer { get; set; } + public bool IsAsync => Getter.IsAsync; + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs index 521afacadfe5..dc117eee8ab2 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs @@ -6,87 +6,107 @@ using SyntaxDynamo; using SwiftReflector.ExceptionTools; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeAliasDeclaration { - public TypeAliasDeclaration () - { - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeAliasDeclaration + { + public TypeAliasDeclaration() + { + } - public Accessibility Access { get; private set; } + public Accessibility Access { get; private set; } - string typeName; - public string TypeName { - get { return typeName; } - set { - typeName = Exceptions.ThrowOnNull (value, nameof (value)); - if (typeName.IndexOf (':') >= 0) - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 12, $"typealias {value} has a generic constraint which is not supported"); - try { - typeSpec = TypeSpecParser.Parse (typeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias name '{value}': {ex.Message}"); - } - } - } + string typeName; + public string TypeName + { + get { return typeName; } + set + { + typeName = Exceptions.ThrowOnNull(value, nameof(value)); + if (typeName.IndexOf(':') >= 0) + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 12, $"typealias {value} has a generic constraint which is not supported"); + try + { + typeSpec = TypeSpecParser.Parse(typeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias name '{value}': {ex.Message}"); + } + } + } - TypeSpec typeSpec; - public TypeSpec TypeSpec { - get { return typeSpec; } - set { - Exceptions.ThrowOnNull (value, nameof (value)); - typeSpec = value; - typeName = value.ToString (); - } - } + TypeSpec typeSpec; + public TypeSpec TypeSpec + { + get { return typeSpec; } + set + { + Exceptions.ThrowOnNull(value, nameof(value)); + typeSpec = value; + typeName = value.ToString(); + } + } - string targetTypeName; - public string TargetTypeName { - get { return targetTypeName; } - set { - targetTypeName = Exceptions.ThrowOnNull (value, nameof (value)); - try { - targetTypeSpec = TypeSpecParser.Parse (targetTypeName); - } catch (RuntimeException ex) { - throw ErrorHelper.CreateError (ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias target name '{value}': {ex.Message}"); - } - } - } + string targetTypeName; + public string TargetTypeName + { + get { return targetTypeName; } + set + { + targetTypeName = Exceptions.ThrowOnNull(value, nameof(value)); + try + { + targetTypeSpec = TypeSpecParser.Parse(targetTypeName); + } + catch (RuntimeException ex) + { + throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 11, $"Unable to parse typealias target name '{value}': {ex.Message}"); + } + } + } - TypeSpec targetTypeSpec; - public TypeSpec TargetTypeSpec { - get { return targetTypeSpec; } - set { - Exceptions.ThrowOnNull (value, nameof (value)); - targetTypeSpec = value; - targetTypeName = value.ToString (); - } - } + TypeSpec targetTypeSpec; + public TypeSpec TargetTypeSpec + { + get { return targetTypeSpec; } + set + { + Exceptions.ThrowOnNull(value, nameof(value)); + targetTypeSpec = value; + targetTypeName = value.ToString(); + } + } - public String ModuleName { - get { - var spec = TypeSpec as NamedTypeSpec; - return spec?.Module; - } - } + public String ModuleName + { + get + { + var spec = TypeSpec as NamedTypeSpec; + return spec?.Module; + } + } - public XElement ToXElement () - { - return new XElement ("typealias", new XAttribute ("name", TypeName), - new XAttribute ("type", TargetTypeName)); - } + public XElement ToXElement() + { + return new XElement("typealias", new XAttribute("name", TypeName), + new XAttribute("type", TargetTypeName)); + } - public static TypeAliasDeclaration FromXElement (string moduleName, XElement element) - { - var aliasName = element.Attribute ("name").Value; - if (!aliasName.Contains (".")) { - Exceptions.ThrowOnNull (moduleName, nameof (moduleName)); - aliasName = $"{moduleName}.{aliasName}"; - } - return new TypeAliasDeclaration () { - Access = TypeDeclaration.AccessibilityFromString ((string)element.Attribute ("accessibility")), - TypeName = aliasName, - TargetTypeName = element.Attribute ("type").Value - }; - } - } + public static TypeAliasDeclaration FromXElement(string moduleName, XElement element) + { + var aliasName = element.Attribute("name").Value; + if (!aliasName.Contains(".")) + { + Exceptions.ThrowOnNull(moduleName, nameof(moduleName)); + aliasName = $"{moduleName}.{aliasName}"; + } + return new TypeAliasDeclaration() + { + Access = TypeDeclaration.AccessibilityFromString((string)element.Attribute("accessibility")), + TypeName = aliasName, + TargetTypeName = element.Attribute("type").Value + }; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs b/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs index 8985e7b5fe31..79391dac91bc 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs @@ -6,254 +6,283 @@ using System.Linq; using SwiftReflector.TypeMapping; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeAliasFolder { - Dictionary aliases; +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeAliasFolder + { + Dictionary aliases; - public TypeAliasFolder (IList aliases) - { - this.aliases = new Dictionary (); - foreach (var alias in aliases) { - this.aliases.Add (AliasKey (alias.TypeSpec), alias); - } - } + public TypeAliasFolder(IList aliases) + { + this.aliases = new Dictionary(); + foreach (var alias in aliases) + { + this.aliases.Add(AliasKey(alias.TypeSpec), alias); + } + } - public void AddDatabaseAliases (TypeDatabase typeDatabase) - { - if (typeDatabase == null) - return; - foreach (var moduleName in typeDatabase.ModuleNames) { - var moduleDB = typeDatabase.ModuleDatabaseForModuleName (moduleName); - foreach (var alias in moduleDB.TypeAliases) { - this.aliases.Add (AliasKey (alias.TypeSpec), alias); - } - } - } + public void AddDatabaseAliases(TypeDatabase typeDatabase) + { + if (typeDatabase == null) + return; + foreach (var moduleName in typeDatabase.ModuleNames) + { + var moduleDB = typeDatabase.ModuleDatabaseForModuleName(moduleName); + foreach (var alias in moduleDB.TypeAliases) + { + this.aliases.Add(AliasKey(alias.TypeSpec), alias); + } + } + } - public TypeSpec FoldAlias (BaseDeclaration context, TypeSpec original) - { - if (aliases.Count == 0) - return original; + public TypeSpec FoldAlias(BaseDeclaration context, TypeSpec original) + { + if (aliases.Count == 0) + return original; - var changed = false; - while (true) { - original = FoldAlias (context, original, out changed); - if (!changed) - return original; - } - } + var changed = false; + while (true) + { + original = FoldAlias(context, original, out changed); + if (!changed) + return original; + } + } - TypeSpec FoldAlias (BaseDeclaration context, TypeSpec spec, out bool changed) - { - switch (spec.Kind) { - case TypeSpecKind.Named: - return FoldAlias (context, spec as NamedTypeSpec, out changed); - case TypeSpecKind.Closure: - return FoldAlias (context, spec as ClosureTypeSpec, out changed); - case TypeSpecKind.ProtocolList: - return FoldAlias (context, spec as ProtocolListTypeSpec, out changed); - case TypeSpecKind.Tuple: - return FoldAlias (context, spec as TupleTypeSpec, out changed); - default: - throw new ArgumentOutOfRangeException (nameof (spec)); - } + TypeSpec FoldAlias(BaseDeclaration context, TypeSpec spec, out bool changed) + { + switch (spec.Kind) + { + case TypeSpecKind.Named: + return FoldAlias(context, spec as NamedTypeSpec, out changed); + case TypeSpecKind.Closure: + return FoldAlias(context, spec as ClosureTypeSpec, out changed); + case TypeSpecKind.ProtocolList: + return FoldAlias(context, spec as ProtocolListTypeSpec, out changed); + case TypeSpecKind.Tuple: + return FoldAlias(context, spec as TupleTypeSpec, out changed); + default: + throw new ArgumentOutOfRangeException(nameof(spec)); + } - } + } - TypeSpec FoldAlias (BaseDeclaration context, TupleTypeSpec spec, out bool changed) - { - changed = false; - TypeSpec [] newContents = spec.Elements.ToArray (); - for (int i = 0; i < newContents.Length; i++) { - var elemChanged = false; - newContents [i] = FoldAlias (context, newContents [i], out elemChanged); - changed = changed || elemChanged; - } - if (changed) { - var newTuple = new TupleTypeSpec (newContents); - newTuple.Attributes.AddRange (spec.Attributes); - return newTuple; - } - return spec; - } + TypeSpec FoldAlias(BaseDeclaration context, TupleTypeSpec spec, out bool changed) + { + changed = false; + TypeSpec[] newContents = spec.Elements.ToArray(); + for (int i = 0; i < newContents.Length; i++) + { + var elemChanged = false; + newContents[i] = FoldAlias(context, newContents[i], out elemChanged); + changed = changed || elemChanged; + } + if (changed) + { + var newTuple = new TupleTypeSpec(newContents); + newTuple.Attributes.AddRange(spec.Attributes); + return newTuple; + } + return spec; + } - TypeSpec FoldAlias (BaseDeclaration context, ClosureTypeSpec spec, out bool changed) - { - var returnChanged = false; - var returnSpec = FoldAlias (context, spec.ReturnType, out returnChanged); + TypeSpec FoldAlias(BaseDeclaration context, ClosureTypeSpec spec, out bool changed) + { + var returnChanged = false; + var returnSpec = FoldAlias(context, spec.ReturnType, out returnChanged); - var argsChanged = false; - var args = FoldAlias (context, spec.Arguments, out argsChanged); + var argsChanged = false; + var args = FoldAlias(context, spec.Arguments, out argsChanged); - changed = returnChanged || argsChanged; - if (changed) { - var newSpec = new ClosureTypeSpec (args, returnSpec); - newSpec.Attributes.AddRange (spec.Attributes); - return newSpec; - } - return spec; - } + changed = returnChanged || argsChanged; + if (changed) + { + var newSpec = new ClosureTypeSpec(args, returnSpec); + newSpec.Attributes.AddRange(spec.Attributes); + return newSpec; + } + return spec; + } - TypeSpec FoldAlias (BaseDeclaration context, ProtocolListTypeSpec spec, out bool changed) - { - changed = false; - var protos = new NamedTypeSpec [spec.Protocols.Count]; + TypeSpec FoldAlias(BaseDeclaration context, ProtocolListTypeSpec spec, out bool changed) + { + changed = false; + var protos = new NamedTypeSpec[spec.Protocols.Count]; - var protoChanged = false; - var i = 0; - foreach (var proto in spec.Protocols.Keys) { - protos [i] = FoldAlias (context, proto, out protoChanged) as NamedTypeSpec; - changed = changed || protoChanged; - } - if (changed) { - var newProtoList = new ProtocolListTypeSpec (protos); - newProtoList.Attributes.AddRange (spec.Attributes); - return newProtoList; - } - return spec; - } + var protoChanged = false; + var i = 0; + foreach (var proto in spec.Protocols.Keys) + { + protos[i] = FoldAlias(context, proto, out protoChanged) as NamedTypeSpec; + changed = changed || protoChanged; + } + if (changed) + { + var newProtoList = new ProtocolListTypeSpec(protos); + newProtoList.Attributes.AddRange(spec.Attributes); + return newProtoList; + } + return spec; + } - TypeSpec FoldAlias (BaseDeclaration context, NamedTypeSpec spec, out bool changed) - { - if (context == null || !context.IsTypeSpecGenericReference (spec)) { - TypeAliasDeclaration decl = null; - if (aliases.TryGetValue (spec.Name, out decl)) { - changed = true; - var newNamedSpec = RemapAliasedTypeSpec (spec, decl); - newNamedSpec.Attributes.AddRange (spec.Attributes); - return newNamedSpec; - } else { - return FoldGenerics (context, spec, out changed); - } - } else { - return FoldGenerics (context, spec, out changed); - } - } + TypeSpec FoldAlias(BaseDeclaration context, NamedTypeSpec spec, out bool changed) + { + if (context == null || !context.IsTypeSpecGenericReference(spec)) + { + TypeAliasDeclaration decl = null; + if (aliases.TryGetValue(spec.Name, out decl)) + { + changed = true; + var newNamedSpec = RemapAliasedTypeSpec(spec, decl); + newNamedSpec.Attributes.AddRange(spec.Attributes); + return newNamedSpec; + } + else + { + return FoldGenerics(context, spec, out changed); + } + } + else + { + return FoldGenerics(context, spec, out changed); + } + } - TypeSpec FoldGenerics (BaseDeclaration context, NamedTypeSpec spec, out bool changed) - { - changed = false; - if (!spec.ContainsGenericParameters) - return spec; - var genericsChanged = false; - var newGenerics = spec.GenericParameters.ToArray (); - for (int i = 0; i < newGenerics.Length; i++) { - var genericChanged = false; - newGenerics [i] = FoldAlias (context, newGenerics [i], out genericChanged); - genericsChanged = genericsChanged || genericChanged; - } - if (genericsChanged) { - changed = true; - var newNamedSpec = new NamedTypeSpec (spec.Name, newGenerics); - newNamedSpec.Attributes.AddRange (spec.Attributes); - return newNamedSpec; - } - return spec; - } + TypeSpec FoldGenerics(BaseDeclaration context, NamedTypeSpec spec, out bool changed) + { + changed = false; + if (!spec.ContainsGenericParameters) + return spec; + var genericsChanged = false; + var newGenerics = spec.GenericParameters.ToArray(); + for (int i = 0; i < newGenerics.Length; i++) + { + var genericChanged = false; + newGenerics[i] = FoldAlias(context, newGenerics[i], out genericChanged); + genericsChanged = genericsChanged || genericChanged; + } + if (genericsChanged) + { + changed = true; + var newNamedSpec = new NamedTypeSpec(spec.Name, newGenerics); + newNamedSpec.Attributes.AddRange(spec.Attributes); + return newNamedSpec; + } + return spec; + } - TypeSpec RemapAliasedTypeSpec (NamedTypeSpec source, TypeAliasDeclaration decl) - { - // OK - in the Decl, we're going to have something like: - // Name = SomeOtherType - // or we'll have - // Name = SomeOtherType - // The first case is easy. In the second case we need to look - // at the t1 and find out where it comes from in Name<...> - // and remap it using what was provided in the source. - // But of course this get complicated. - // You could have something like this: - // typealias Foo = UnsafeMutablePointer<(Int, T)> - // So we need a map from each generic argument in Foo to - // each generic argument in source. - // Then we need to build a new TypeSpec using the declaration's target - // type substituting in elements from the map. - // and it gets more complicated because the thing we're looking at may - // be an associated type. - // - // Here's an example: - //public protocol KVPish - //{ - // associatedtype Key : Hashable - // associatedtype Value - // func contains(a: Key) -> Bool - // func get(a: Key) -> Value - //} - // - //public typealias KPHolder = Dictionary - var genericMap = new Dictionary (); - if (decl.TypeSpec.ContainsGenericParameters) { - for (int i = 0; i < decl.TypeSpec.GenericParameters.Count; i++) { - // the "parts" here are part of a formal generic declaration - // and they HAVE to be named type specs and they themselves - // won't ever be generic. They're going to just be a name. - // Future Steve: trust me. - var part = decl.TypeSpec.GenericParameters [i] as NamedTypeSpec; - genericMap.Add (part.Name, source.GenericParameters [i]); - } - } - return RemapTypeSpec (decl.TargetTypeSpec, genericMap); - } + TypeSpec RemapAliasedTypeSpec(NamedTypeSpec source, TypeAliasDeclaration decl) + { + // OK - in the Decl, we're going to have something like: + // Name = SomeOtherType + // or we'll have + // Name = SomeOtherType + // The first case is easy. In the second case we need to look + // at the t1 and find out where it comes from in Name<...> + // and remap it using what was provided in the source. + // But of course this get complicated. + // You could have something like this: + // typealias Foo = UnsafeMutablePointer<(Int, T)> + // So we need a map from each generic argument in Foo to + // each generic argument in source. + // Then we need to build a new TypeSpec using the declaration's target + // type substituting in elements from the map. + // and it gets more complicated because the thing we're looking at may + // be an associated type. + // + // Here's an example: + //public protocol KVPish + //{ + // associatedtype Key : Hashable + // associatedtype Value + // func contains(a: Key) -> Bool + // func get(a: Key) -> Value + //} + // + //public typealias KPHolder = Dictionary + var genericMap = new Dictionary(); + if (decl.TypeSpec.ContainsGenericParameters) + { + for (int i = 0; i < decl.TypeSpec.GenericParameters.Count; i++) + { + // the "parts" here are part of a formal generic declaration + // and they HAVE to be named type specs and they themselves + // won't ever be generic. They're going to just be a name. + // Future Steve: trust me. + var part = decl.TypeSpec.GenericParameters[i] as NamedTypeSpec; + genericMap.Add(part.Name, source.GenericParameters[i]); + } + } + return RemapTypeSpec(decl.TargetTypeSpec, genericMap); + } - TypeSpec RemapTypeSpec (TypeSpec spec, Dictionary nameMap) - { - switch (spec.Kind) { - case TypeSpecKind.Closure: - return RemapTypeSpec (spec as ClosureTypeSpec, nameMap); - case TypeSpecKind.Named: - return RemapTypeSpec (spec as NamedTypeSpec, nameMap); - case TypeSpecKind.ProtocolList: - return RemapTypeSpec (spec as ProtocolListTypeSpec, nameMap); - case TypeSpecKind.Tuple: - return RemapTypeSpec (spec as TupleTypeSpec, nameMap); - default: - throw new NotImplementedException ($"Unknown type spec kind {spec.Kind}"); - } - } + TypeSpec RemapTypeSpec(TypeSpec spec, Dictionary nameMap) + { + switch (spec.Kind) + { + case TypeSpecKind.Closure: + return RemapTypeSpec(spec as ClosureTypeSpec, nameMap); + case TypeSpecKind.Named: + return RemapTypeSpec(spec as NamedTypeSpec, nameMap); + case TypeSpecKind.ProtocolList: + return RemapTypeSpec(spec as ProtocolListTypeSpec, nameMap); + case TypeSpecKind.Tuple: + return RemapTypeSpec(spec as TupleTypeSpec, nameMap); + default: + throw new NotImplementedException($"Unknown type spec kind {spec.Kind}"); + } + } - TypeSpec RemapTypeSpec (TupleTypeSpec tuple, Dictionary nameMap) - { - var tupleElems = tuple.Elements.ToArray (); - for (int i = 0; i < tupleElems.Length; i++) { - tupleElems [i] = RemapTypeSpec (tupleElems [i], nameMap); - } - return new TupleTypeSpec (tupleElems); - } + TypeSpec RemapTypeSpec(TupleTypeSpec tuple, Dictionary nameMap) + { + var tupleElems = tuple.Elements.ToArray(); + for (int i = 0; i < tupleElems.Length; i++) + { + tupleElems[i] = RemapTypeSpec(tupleElems[i], nameMap); + } + return new TupleTypeSpec(tupleElems); + } - TypeSpec RemapTypeSpec (ClosureTypeSpec clos, Dictionary nameMap) - { - var returnType = RemapTypeSpec (clos.ReturnType, nameMap); - var args = RemapTypeSpec (clos.Arguments, nameMap); - return new ClosureTypeSpec (args, returnType); - } + TypeSpec RemapTypeSpec(ClosureTypeSpec clos, Dictionary nameMap) + { + var returnType = RemapTypeSpec(clos.ReturnType, nameMap); + var args = RemapTypeSpec(clos.Arguments, nameMap); + return new ClosureTypeSpec(args, returnType); + } - TypeSpec RemapTypeSpec (ProtocolListTypeSpec proto, Dictionary nameMap) - { - return new ProtocolListTypeSpec (proto.Protocols.Keys.Select (k => RemapTypeSpec (k, nameMap) as NamedTypeSpec)); - } + TypeSpec RemapTypeSpec(ProtocolListTypeSpec proto, Dictionary nameMap) + { + return new ProtocolListTypeSpec(proto.Protocols.Keys.Select(k => RemapTypeSpec(k, nameMap) as NamedTypeSpec)); + } - TypeSpec RemapTypeSpec (NamedTypeSpec named, Dictionary nameMap) - { - var parts = named.Name.Split ('.'); - for (int i = 0; i < parts.Length; i++) { - TypeSpec replacement; - if (nameMap.TryGetValue (parts [i], out replacement)) { - parts [i] = replacement.ToString (); - } - } - var newName = parts.InterleaveStrings ("."); - if (named.ContainsGenericParameters) { - var newParams = named.GenericParameters.Select (p => RemapTypeSpec (p, nameMap)).ToArray (); - return new NamedTypeSpec (newName, newParams); - } else { - return new NamedTypeSpec (newName); - } - } + TypeSpec RemapTypeSpec(NamedTypeSpec named, Dictionary nameMap) + { + var parts = named.Name.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + TypeSpec replacement; + if (nameMap.TryGetValue(parts[i], out replacement)) + { + parts[i] = replacement.ToString(); + } + } + var newName = parts.InterleaveStrings("."); + if (named.ContainsGenericParameters) + { + var newParams = named.GenericParameters.Select(p => RemapTypeSpec(p, nameMap)).ToArray(); + return new NamedTypeSpec(newName, newParams); + } + else + { + return new NamedTypeSpec(newName); + } + } - static string AliasKey (TypeSpec spec) - { - if (spec is NamedTypeSpec named) - return named.Name; - return spec.ToString (); - } - } + static string AliasKey(TypeSpec spec) + { + if (spec is NamedTypeSpec named) + return named.Name; + return spec.ToString(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs index 092da842bf24..a72bcb2313ea 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs @@ -11,528 +11,573 @@ using SwiftReflector.TypeMapping; using System.Text; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeDeclaration : BaseDeclaration, IXElementConvertible { - public TypeDeclaration () - : base () - { - Kind = TypeKind.Unknown; - InnerClasses = new List (); - InnerStructs = new List (); - InnerEnums = new List (); - Members = new List (); - Inheritance = new List (); - TypeAliases = new List (); - } - - public TypeKind Kind { get; set; } - public List Inheritance { get; set; } - public List Members { get; set; } - public List InnerClasses { get; set; } - public List InnerStructs { get; set; } - public List InnerEnums { get; set; } - public List TypeAliases { get; set; } - public bool IsObjC { get; set; } - public bool IsFinal { get; set; } - public bool IsDeprecated { get; set; } - public bool IsUnavailable { get; set; } - public bool IsUnrooted { get; protected set; } - - public TypeDeclaration MakeUnrooted () - { - if (IsUnrooted) - return this; - - TypeDeclaration unrooted = UnrootedFactory (); - unrooted.unrootedName = ToFullyQualifiedName (false); - unrooted.fullUnrootedName = ToFullyQualifiedName (true); - unrooted.Kind = Kind; - unrooted.Inheritance.AddRange (Inheritance); - unrooted.Members.AddRange (Members); - unrooted.IsObjC = IsObjC; - unrooted.IsFinal = IsFinal; - unrooted.IsUnrooted = true; - unrooted.Name = Name; - unrooted.Access = Access; - unrooted.Module = Module.MakeUnrooted (); - unrooted.Generics.AddRange (Generics); - CompleteUnrooting (unrooted); - return unrooted; - } - - protected virtual TypeDeclaration UnrootedFactory () - { - throw new NotImplementedException (); - } - - public bool IsObjCOrInheritsObjC (TypeMapper typeMapper) - { - if (IsObjC) - return true; - if (Inheritance == null || Inheritance.Count == 0) - return false; - foreach (var inheritance in Inheritance) { - if (inheritance.InheritanceKind != InheritanceKind.Class) - continue; - var entity = typeMapper.GetEntityForTypeSpec (inheritance.InheritedTypeSpec); - if (entity == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 4, $"Unable to find entity for class inheritance type {inheritance.InheritedTypeName}"); - return entity.Type.IsObjC || entity.Type.IsObjCOrInheritsObjC (typeMapper); - } - return false; - } - - public bool IsSwiftBaseClass () - { - // this predicate determines if a TypeDeclaration is: - // * a ClassDeclaration - // * an all swift object - // * no inheritance or any inheritance is not class inheritance - if (!(this is ClassDeclaration)) - return false; - if (IsObjC) - return false; - return Inheritance == null || !Inheritance.Any (inh => inh.InheritanceKind == InheritanceKind.Class); - } - - public bool ProtectedObjCCtorIsInThis (TypeMapper typeMapper) - { - // this predicate determines if this type has a protected objc ctor in this. - // it's used to determine if, when writing the C# binding, if we need to call base () or this () - var classDecl = this as ClassDeclaration; - if (classDecl == null) - return false; - if (!IsObjC) - return false; - // no inheritance - // this : (nothing) -> IsImportedBinding - if (Inheritance == null || Inheritance.FirstOrDefault (inh => inh.InheritanceKind == InheritanceKind.Class) == null) { - // if there's no inheritance, then the protected ctor is in this if it wasn't imported - return !classDecl.IsImportedBinding; - } - // this : import -> true - // this : binding : binding : import -> false - var classInherit = Inheritance.First (inh => inh.InheritanceKind == InheritanceKind.Class); - var entity = typeMapper.GetEntityForTypeSpec (classInherit.InheritedTypeSpec); - if (entity == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 9, $"Unable to find entity for class inheritance on type {classInherit.InheritedTypeName}"); - var inheritedClass = entity.Type as ClassDeclaration; - if (inheritedClass == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 10, $"Expected a ClassDeclaration in inheritance chain but got {entity.Type.ToFullyQualifiedName (true)} of {entity.Type.GetType ().Name}"); - return inheritedClass.IsImportedBinding; - } - - protected virtual void CompleteUnrooting (TypeDeclaration unrooted) - { - } - - protected string unrootedName = null; - protected string fullUnrootedName = null; - public override string ToFullyQualifiedName (bool includeModule = true) - { - if (IsUnrooted) { - return includeModule ? fullUnrootedName : unrootedName; - } else { - return base.ToFullyQualifiedName (includeModule); - } - } - - #region IXElementConvertible implementation - - public XElement ToXElement () - { - if (!IsUnrooted) - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 0, "TypeDeclarations must be unrooted to create from XML."); - - var xobjects = new List (); - GatherXObjects (xobjects); - XElement typeDecl = new XElement ("typedeclaration", xobjects.ToArray ()); - return typeDecl; - } - - protected virtual void GatherXObjects (List xobjects) - { - XElement generics = Generics.ToXElement (); - if (generics != null) - xobjects.Add (generics); - xobjects.Add (new XAttribute ("kind", ToString (Kind))); - xobjects.Add (new XAttribute ("name", fullUnrootedName)); - xobjects.Add (new XAttribute ("module", Module.Name)); - xobjects.Add (new XAttribute ("accessibility", TypeDeclaration.ToString (Access))); - xobjects.Add (new XAttribute ("isObjC", IsObjC ? "true" : "false")); - xobjects.Add (new XAttribute ("isFinal", IsFinal ? "true" : "false")); - xobjects.Add (new XAttribute ("isDeprecated", IsDeprecated ? "true" : "false")); - xobjects.Add (new XAttribute ("isUnavailable", IsUnavailable ? "true" : "false")); - // DO NOT INCLUDE Inner[Classes,Structs,Enums] - List memcontents = new List (Members.Select (m => m.ToXElement ())); - xobjects.Add (new XElement ("members", memcontents.ToArray ())); - List inherits = new List (Inheritance.Select (i => i.ToXElement ())); - xobjects.Add (new XElement ("inherits", inherits.ToArray ())); - if (TypeAliases.Count > 0) { - var aliases = new List (TypeAliases.Select (a => a.ToXElement ())); - xobjects.Add (new XElement ("typealiases", aliases.ToArray ())); - } - } - - #endregion - - public static TypeDeclaration TypeFromXElement (TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent /* can be null */) - { - var decl = FromKind ((string)elem.Attribute ("kind")); - bool isUnrooted = elem.Attribute ("module") != null; - decl.Module = module; - decl.Parent = parent; - if (isUnrooted) { - decl.IsUnrooted = true; - decl.fullUnrootedName = (string)elem.Attribute ("name"); - decl.unrootedName = decl.fullUnrootedName.NameWithoutModule (); - decl.Name = decl.fullUnrootedName.Contains ('.') ? decl.fullUnrootedName.Substring (decl.fullUnrootedName.LastIndexOf ('.') + 1) - : decl.fullUnrootedName; - } else { - decl.Name = (string)elem.Attribute ("name"); - } - decl.Access = AccessibilityFromString ((string)elem.Attribute ("accessibility")); - decl.IsObjC = elem.BoolAttribute ("isObjC"); - decl.IsFinal = elem.BoolAttribute ("isFinal"); - decl.IsDeprecated = elem.BoolAttribute ("isDeprecated"); - decl.IsUnavailable = elem.BoolAttribute ("isUnavailable"); - - decl.InnerClasses.AddRange (InnerFoo (folder, elem, "innerclasses", module, decl)); - decl.InnerStructs.AddRange (InnerFoo (folder, elem, "innerstructs", module, decl)); - decl.InnerEnums.AddRange (InnerFoo (folder, elem, "innerenums", module, decl)); - if (elem.Element ("members") != null) { - var members = from mem in elem.Element ("members").Elements () - select Member.FromXElement (folder, mem, module, decl) as Member; - decl.Members.AddRange (members); - } - if (elem.Element ("inherits") != null) { - var inherits = from inherit in elem.Element ("inherits").Elements () - select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement (folder, inherit) as Inheritance; - decl.Inheritance.AddRange (inherits); - } - var typealiases = elem.Element ("typealiases"); - if (typealiases != null) { - var aliases = from alias in typealiases.Elements () - select TypeAliasDeclaration.FromXElement (module.Name, alias); - decl.TypeAliases.AddRange (aliases); - } - EnumDeclaration edecl = decl as EnumDeclaration; - if (edecl != null) { - var enumElements = (from enumElement in elem.Element ("elements").Elements () - select new EnumElement ((string)enumElement.Attribute ("name"), (string)enumElement.Attribute ("type"), - (long?)enumElement.Attribute ("intValue"))).ToList (); ; - edecl.Elements.AddRange (enumElements); - if (elem.Attribute ("rawType") != null) { - var rawType = TypeSpecParser.Parse ((string)elem.Attribute ("rawType")); - edecl.RawTypeName = folder.FoldAlias (parent, rawType).ToString (); - } - } - - var protoDecl = decl as ProtocolDeclaration; - if (protoDecl != null) { - if (elem.Element ("associatedtypes") != null) { - var assocElements = from assocElem in elem.Element ("associatedtypes").Elements () - select AssociatedTypeDeclaration.FromXElement (folder, assocElem); - protoDecl.AssociatedTypes.AddRange (assocElements); - } - } - - return decl; - } - - static IEnumerable InnerFoo (TypeAliasFolder folder, XElement parent, string innerName, ModuleDeclaration module, BaseDeclaration parDecl) where T : TypeDeclaration - { - var inner = parent.Elements (innerName).SelectMany (el => el.Elements ("typedeclaration")); - var innerList = inner.Select (elem => FromXElement (folder, elem, module, parDecl)).ToList (); - var innerCast = innerList.Cast ().ToList (); - return innerCast; - } - - static TypeDeclaration FromKind (string kind) - { - switch (kind) { - case "class": - return new ClassDeclaration (); - case "struct": - return new StructDeclaration (); - case "enum": - return new EnumDeclaration (); - case "protocol": - return new ProtocolDeclaration (); - default: - return new TypeDeclaration (); - } - } - - internal static string ToString (TypeKind kind) - { - switch (kind) { - case TypeKind.Class: - return "class"; - case TypeKind.Struct: - return "struct"; - case TypeKind.Enum: - return "enum"; - case TypeKind.Protocol: - return "protocol:"; - default: - throw new ArgumentOutOfRangeException (nameof (kind)); - } - } - - public static Accessibility AccessibilityFromString (string value) - { - if (value == null) - return Accessibility.Unknown; - Accessibility access; - Enum.TryParse (value, out access); - return access; - } - - internal static string ToString (Accessibility access) - { - return access.ToString (); - } - - public List AllVirtualMethods () - { - if (this is ProtocolDeclaration) { - return Members.OfType ().Where (decl => - !decl.IsConstructorOrDestructor && - (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Public)).ToList (); - } else { - return Members.OfType ().Where (decl => - !decl.IsConstructorOrDestructor && - (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Open)).ToList (); - } - } - - public List AllProperties () - { - return Members.OfType ().ToList (); - } - - public List AllVirtualProperties () - { - Accessibility requiredAccessibility; - if (this is ProtocolDeclaration) { - requiredAccessibility = Accessibility.Public; - } else { - requiredAccessibility = Accessibility.Open; - } - return Members.OfType ().Where (decl => { - if (decl.IsStatic) - return false; - if (decl.Access != requiredAccessibility) - return false; - var getter = decl.GetGetter (); - if (getter == null) - return false; - if (getter.IsDeprecated || getter.IsUnavailable) - return false; - return true; - }).ToList (); - } - - public List AllFinalMethods () - { - return Members.OfType ().Where (decl => - !decl.IsConstructorOrDestructor && decl.IsFinal).ToList (); - } - - public List AllMethodsNoCDTor () - { - return Members.OfType ().Where (decl => !decl.IsConstructorOrDestructor).ToList (); - } - - public List AllConstructors () - { - return Members.OfType ().Where (decl => decl.IsConstructor).ToList (); - } - - public List AllDestructors () - { - return Members.OfType ().Where (decl => decl.IsDestructor).ToList (); - } - - public List AllSubscripts () - { - var allSubFuncs = Members.OfType ().Where (decl => decl.IsSubscript).ToList (); - var allSubs = new List (); - while (allSubFuncs.Count > 0) { - int i = allSubFuncs.Count - 1; - FunctionDeclaration decl = allSubFuncs [i]; - allSubFuncs.RemoveAt (i); - if (decl.IsSubscriptMaterializer) - continue; - if (decl.IsSubscriptGetter) { - FunctionDeclaration setter = GetAndRemoveSetter (allSubFuncs, decl); - FunctionDeclaration materializer = GetAndRemoveMaterializer (allSubFuncs, decl); - allSubs.Add (new SubscriptDeclaration (decl, setter, materializer)); - } else if (decl.IsSubscriptSetter) { - FunctionDeclaration getter = GetAndRemoveGetter (allSubFuncs, decl); - FunctionDeclaration materializer = GetAndRemoveMaterializer (allSubFuncs, decl); - allSubs.Add (new SubscriptDeclaration (getter, decl, materializer)); - } - } - return allSubs; - } - - public TypeSpec ToTypeSpec () - { - NamedTypeSpec ns = new NamedTypeSpec (ToFullyQualifiedName ()); - ns.GenericParameters.AddRange (Generics.Select (gen => new NamedTypeSpec (gen.Name))); - return ns; - } - - static FunctionDeclaration GetAndRemoveMaterializer (List decls, FunctionDeclaration other) - { - // FIXME - materializers don't have enough to match on with 100% confidence - // Materializers are (probably) not needed by tom-swifty, so no big - return null; - } - - static FunctionDeclaration GetAndRemoveGetter (List decls, FunctionDeclaration other) - { - var plToMatch = new List (); - TypeSpec returnToMatch = null; - var selfToMatch = other.Parent; - - if (other.IsSetter) { - // setter - - // The arguments to a setter are - // value, arg1, arg2 ... argn - // We want to match the type of the return of the getter to the value of the setter - // as well as the parameters - List pl = other.ParameterLists.Last (); - plToMatch.AddRange (pl.GetRange (1, pl.Count - 1)); - returnToMatch = pl [0].TypeSpec; - } else { - // materializer. - // The arguments to a materializer are - // buffer, callbackStoragebuffer, arg1, arg2 ... argn - // We have no return to match. Oops. - List pl = other.ParameterLists.Last (); - plToMatch.AddRange (pl.GetRange (2, pl.Count - 2)); - returnToMatch = null; - } - - - for (int i = 0; i < decls.Count; i++) { - FunctionDeclaration getter = decls [i]; - if (getter.Parent != selfToMatch) - return null; - if (!getter.IsSubscriptGetter) - continue; - if ((returnToMatch != null && returnToMatch.Equals (getter.ReturnTypeSpec)) || returnToMatch == null) { - List targetPl = getter.ParameterLists.Last (); - if (ParmsMatch (plToMatch, targetPl)) { - decls.RemoveAt (i); - return getter; - } - } - } - return null; - } - - static FunctionDeclaration GetAndRemoveSetter (List decls, FunctionDeclaration other) - { - var plToMatch = new List (); - var selfToMatch = other.Parent; - - if (other.IsGetter) { - // getter - - // The arguments to a getter are - // arg1, arg2 ... argn - // We want to match the type of the return of the getter to the value of the setter - // as well as the parameters - List pl = other.ParameterLists.Last (); - ParameterItem item = new ParameterItem (); - item.PublicName = ""; - item.PrivateName = "retval"; - item.TypeSpec = other.ReturnTypeSpec; - item.TypeName = other.ReturnTypeName; - plToMatch.Add (item); - plToMatch.AddRange (pl); - } else { - // we don't have enough information to match on setter - // and since we don't use the materializer, NBD. - - // materializer. - // The arguments to a materializer are - // buffer, callbackStoragebuffer, arg1, arg2 ... argn - // We have no return to match. Oops. - return null; - } - - for (int i = 0; i < decls.Count; i++) { - FunctionDeclaration setter = decls [i]; - if (!setter.IsSubscriptGetter) - continue; - List targetPl = setter.ParameterLists.Last (); - if (ParmsMatch (plToMatch, targetPl)) { - decls.RemoveAt (i); - return setter; - } - } - return null; - } - - public bool VirtualMethodExistsInInheritedBoundType (FunctionDeclaration func, TypeMapper typeMapper) - { - // virtual methods are only in classes - if (!(this is ClassDeclaration)) - return false; - var classInheritance = Inheritance.FirstOrDefault (inh => inh.InheritanceKind == InheritanceKind.Class); - if (classInheritance == null) - return false; - - var inheritedEntity = typeMapper.GetEntityForTypeSpec (classInheritance.InheritedTypeSpec); - if (inheritedEntity == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 18, $"Unable to find type database entry for class {classInheritance.InheritedTypeName} while searching inheritance."); - - // if we get here, the Type has to be a ClassDeclaration - var inheritedClass = inheritedEntity.Type as ClassDeclaration; - - var methods = inheritedClass.AllVirtualMethods ().FindAll (fn => fn.Name == func.Name - && fn.ParameterLists.Last ().Count == func.ParameterLists.Last ().Count).ToList (); - foreach (var method in methods) { - if (ParmsMatchWithNames (method.ParameterLists.Last (), func.ParameterLists.Last ()) - && method.ReturnTypeSpec.Equals (func.ReturnTypeSpec)) - return true; - } - return inheritedClass.VirtualMethodExistsInInheritedBoundType (func, typeMapper); - } - - static bool ParmsMatchWithNames (List pl1, List pl2) - { - if (pl1.Count != pl2.Count) - return false; - for (int i = 0; i < pl1.Count; i++) { - if (pl1 [i].PublicName != pl2 [i].PublicName) - return false; - if (pl1 [i].IsInOut != pl2 [i].IsInOut) - return false; - if (!pl1 [i].TypeSpec.Equals (pl2 [i].TypeSpec)) - return false; - } - return true; - } - - static bool ParmsMatch (List pl1, List pl2) - { - if (pl1.Count != pl2.Count) - return false; - for (int i = 0; i < pl1.Count; i++) { - if (pl1 [i].IsInOut != pl2 [i].IsInOut) - return false; - if (!pl1 [i].TypeSpec.Equals (pl2 [i].TypeSpec)) - return false; - } - return true; - } - - - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeDeclaration : BaseDeclaration, IXElementConvertible + { + public TypeDeclaration() + : base() + { + Kind = TypeKind.Unknown; + InnerClasses = new List(); + InnerStructs = new List(); + InnerEnums = new List(); + Members = new List(); + Inheritance = new List(); + TypeAliases = new List(); + } + + public TypeKind Kind { get; set; } + public List Inheritance { get; set; } + public List Members { get; set; } + public List InnerClasses { get; set; } + public List InnerStructs { get; set; } + public List InnerEnums { get; set; } + public List TypeAliases { get; set; } + public bool IsObjC { get; set; } + public bool IsFinal { get; set; } + public bool IsDeprecated { get; set; } + public bool IsUnavailable { get; set; } + public bool IsUnrooted { get; protected set; } + + public TypeDeclaration MakeUnrooted() + { + if (IsUnrooted) + return this; + + TypeDeclaration unrooted = UnrootedFactory(); + unrooted.unrootedName = ToFullyQualifiedName(false); + unrooted.fullUnrootedName = ToFullyQualifiedName(true); + unrooted.Kind = Kind; + unrooted.Inheritance.AddRange(Inheritance); + unrooted.Members.AddRange(Members); + unrooted.IsObjC = IsObjC; + unrooted.IsFinal = IsFinal; + unrooted.IsUnrooted = true; + unrooted.Name = Name; + unrooted.Access = Access; + unrooted.Module = Module.MakeUnrooted(); + unrooted.Generics.AddRange(Generics); + CompleteUnrooting(unrooted); + return unrooted; + } + + protected virtual TypeDeclaration UnrootedFactory() + { + throw new NotImplementedException(); + } + + public bool IsObjCOrInheritsObjC(TypeMapper typeMapper) + { + if (IsObjC) + return true; + if (Inheritance == null || Inheritance.Count == 0) + return false; + foreach (var inheritance in Inheritance) + { + if (inheritance.InheritanceKind != InheritanceKind.Class) + continue; + var entity = typeMapper.GetEntityForTypeSpec(inheritance.InheritedTypeSpec); + if (entity == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 4, $"Unable to find entity for class inheritance type {inheritance.InheritedTypeName}"); + return entity.Type.IsObjC || entity.Type.IsObjCOrInheritsObjC(typeMapper); + } + return false; + } + + public bool IsSwiftBaseClass() + { + // this predicate determines if a TypeDeclaration is: + // * a ClassDeclaration + // * an all swift object + // * no inheritance or any inheritance is not class inheritance + if (!(this is ClassDeclaration)) + return false; + if (IsObjC) + return false; + return Inheritance == null || !Inheritance.Any(inh => inh.InheritanceKind == InheritanceKind.Class); + } + + public bool ProtectedObjCCtorIsInThis(TypeMapper typeMapper) + { + // this predicate determines if this type has a protected objc ctor in this. + // it's used to determine if, when writing the C# binding, if we need to call base () or this () + var classDecl = this as ClassDeclaration; + if (classDecl == null) + return false; + if (!IsObjC) + return false; + // no inheritance + // this : (nothing) -> IsImportedBinding + if (Inheritance == null || Inheritance.FirstOrDefault(inh => inh.InheritanceKind == InheritanceKind.Class) == null) + { + // if there's no inheritance, then the protected ctor is in this if it wasn't imported + return !classDecl.IsImportedBinding; + } + // this : import -> true + // this : binding : binding : import -> false + var classInherit = Inheritance.First(inh => inh.InheritanceKind == InheritanceKind.Class); + var entity = typeMapper.GetEntityForTypeSpec(classInherit.InheritedTypeSpec); + if (entity == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 9, $"Unable to find entity for class inheritance on type {classInherit.InheritedTypeName}"); + var inheritedClass = entity.Type as ClassDeclaration; + if (inheritedClass == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 10, $"Expected a ClassDeclaration in inheritance chain but got {entity.Type.ToFullyQualifiedName(true)} of {entity.Type.GetType().Name}"); + return inheritedClass.IsImportedBinding; + } + + protected virtual void CompleteUnrooting(TypeDeclaration unrooted) + { + } + + protected string unrootedName = null; + protected string fullUnrootedName = null; + public override string ToFullyQualifiedName(bool includeModule = true) + { + if (IsUnrooted) + { + return includeModule ? fullUnrootedName : unrootedName; + } + else + { + return base.ToFullyQualifiedName(includeModule); + } + } + + #region IXElementConvertible implementation + + public XElement ToXElement() + { + if (!IsUnrooted) + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 0, "TypeDeclarations must be unrooted to create from XML."); + + var xobjects = new List(); + GatherXObjects(xobjects); + XElement typeDecl = new XElement("typedeclaration", xobjects.ToArray()); + return typeDecl; + } + + protected virtual void GatherXObjects(List xobjects) + { + XElement generics = Generics.ToXElement(); + if (generics != null) + xobjects.Add(generics); + xobjects.Add(new XAttribute("kind", ToString(Kind))); + xobjects.Add(new XAttribute("name", fullUnrootedName)); + xobjects.Add(new XAttribute("module", Module.Name)); + xobjects.Add(new XAttribute("accessibility", TypeDeclaration.ToString(Access))); + xobjects.Add(new XAttribute("isObjC", IsObjC ? "true" : "false")); + xobjects.Add(new XAttribute("isFinal", IsFinal ? "true" : "false")); + xobjects.Add(new XAttribute("isDeprecated", IsDeprecated ? "true" : "false")); + xobjects.Add(new XAttribute("isUnavailable", IsUnavailable ? "true" : "false")); + // DO NOT INCLUDE Inner[Classes,Structs,Enums] + List memcontents = new List(Members.Select(m => m.ToXElement())); + xobjects.Add(new XElement("members", memcontents.ToArray())); + List inherits = new List(Inheritance.Select(i => i.ToXElement())); + xobjects.Add(new XElement("inherits", inherits.ToArray())); + if (TypeAliases.Count > 0) + { + var aliases = new List(TypeAliases.Select(a => a.ToXElement())); + xobjects.Add(new XElement("typealiases", aliases.ToArray())); + } + } + + #endregion + + public static TypeDeclaration TypeFromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent /* can be null */) + { + var decl = FromKind((string)elem.Attribute("kind")); + bool isUnrooted = elem.Attribute("module") != null; + decl.Module = module; + decl.Parent = parent; + if (isUnrooted) + { + decl.IsUnrooted = true; + decl.fullUnrootedName = (string)elem.Attribute("name"); + decl.unrootedName = decl.fullUnrootedName.NameWithoutModule(); + decl.Name = decl.fullUnrootedName.Contains('.') ? decl.fullUnrootedName.Substring(decl.fullUnrootedName.LastIndexOf('.') + 1) + : decl.fullUnrootedName; + } + else + { + decl.Name = (string)elem.Attribute("name"); + } + decl.Access = AccessibilityFromString((string)elem.Attribute("accessibility")); + decl.IsObjC = elem.BoolAttribute("isObjC"); + decl.IsFinal = elem.BoolAttribute("isFinal"); + decl.IsDeprecated = elem.BoolAttribute("isDeprecated"); + decl.IsUnavailable = elem.BoolAttribute("isUnavailable"); + + decl.InnerClasses.AddRange(InnerFoo(folder, elem, "innerclasses", module, decl)); + decl.InnerStructs.AddRange(InnerFoo(folder, elem, "innerstructs", module, decl)); + decl.InnerEnums.AddRange(InnerFoo(folder, elem, "innerenums", module, decl)); + if (elem.Element("members") != null) + { + var members = from mem in elem.Element("members").Elements() + select Member.FromXElement(folder, mem, module, decl) as Member; + decl.Members.AddRange(members); + } + if (elem.Element("inherits") != null) + { + var inherits = from inherit in elem.Element("inherits").Elements() + select SwiftReflector.SwiftXmlReflection.Inheritance.FromXElement(folder, inherit) as Inheritance; + decl.Inheritance.AddRange(inherits); + } + var typealiases = elem.Element("typealiases"); + if (typealiases != null) + { + var aliases = from alias in typealiases.Elements() + select TypeAliasDeclaration.FromXElement(module.Name, alias); + decl.TypeAliases.AddRange(aliases); + } + EnumDeclaration edecl = decl as EnumDeclaration; + if (edecl != null) + { + var enumElements = (from enumElement in elem.Element("elements").Elements() + select new EnumElement((string)enumElement.Attribute("name"), (string)enumElement.Attribute("type"), + (long?)enumElement.Attribute("intValue"))).ToList(); ; + edecl.Elements.AddRange(enumElements); + if (elem.Attribute("rawType") != null) + { + var rawType = TypeSpecParser.Parse((string)elem.Attribute("rawType")); + edecl.RawTypeName = folder.FoldAlias(parent, rawType).ToString(); + } + } + + var protoDecl = decl as ProtocolDeclaration; + if (protoDecl != null) + { + if (elem.Element("associatedtypes") != null) + { + var assocElements = from assocElem in elem.Element("associatedtypes").Elements() + select AssociatedTypeDeclaration.FromXElement(folder, assocElem); + protoDecl.AssociatedTypes.AddRange(assocElements); + } + } + + return decl; + } + + static IEnumerable InnerFoo(TypeAliasFolder folder, XElement parent, string innerName, ModuleDeclaration module, BaseDeclaration parDecl) where T : TypeDeclaration + { + var inner = parent.Elements(innerName).SelectMany(el => el.Elements("typedeclaration")); + var innerList = inner.Select(elem => FromXElement(folder, elem, module, parDecl)).ToList(); + var innerCast = innerList.Cast().ToList(); + return innerCast; + } + + static TypeDeclaration FromKind(string kind) + { + switch (kind) + { + case "class": + return new ClassDeclaration(); + case "struct": + return new StructDeclaration(); + case "enum": + return new EnumDeclaration(); + case "protocol": + return new ProtocolDeclaration(); + default: + return new TypeDeclaration(); + } + } + + internal static string ToString(TypeKind kind) + { + switch (kind) + { + case TypeKind.Class: + return "class"; + case TypeKind.Struct: + return "struct"; + case TypeKind.Enum: + return "enum"; + case TypeKind.Protocol: + return "protocol:"; + default: + throw new ArgumentOutOfRangeException(nameof(kind)); + } + } + + public static Accessibility AccessibilityFromString(string value) + { + if (value == null) + return Accessibility.Unknown; + Accessibility access; + Enum.TryParse(value, out access); + return access; + } + + internal static string ToString(Accessibility access) + { + return access.ToString(); + } + + public List AllVirtualMethods() + { + if (this is ProtocolDeclaration) + { + return Members.OfType().Where(decl => + !decl.IsConstructorOrDestructor && + (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Public)).ToList(); + } + else + { + return Members.OfType().Where(decl => + !decl.IsConstructorOrDestructor && + (!decl.IsFinal && !decl.IsStatic && decl.Access == Accessibility.Open)).ToList(); + } + } + + public List AllProperties() + { + return Members.OfType().ToList(); + } + + public List AllVirtualProperties() + { + Accessibility requiredAccessibility; + if (this is ProtocolDeclaration) + { + requiredAccessibility = Accessibility.Public; + } + else + { + requiredAccessibility = Accessibility.Open; + } + return Members.OfType().Where(decl => + { + if (decl.IsStatic) + return false; + if (decl.Access != requiredAccessibility) + return false; + var getter = decl.GetGetter(); + if (getter == null) + return false; + if (getter.IsDeprecated || getter.IsUnavailable) + return false; + return true; + }).ToList(); + } + + public List AllFinalMethods() + { + return Members.OfType().Where(decl => + !decl.IsConstructorOrDestructor && decl.IsFinal).ToList(); + } + + public List AllMethodsNoCDTor() + { + return Members.OfType().Where(decl => !decl.IsConstructorOrDestructor).ToList(); + } + + public List AllConstructors() + { + return Members.OfType().Where(decl => decl.IsConstructor).ToList(); + } + + public List AllDestructors() + { + return Members.OfType().Where(decl => decl.IsDestructor).ToList(); + } + + public List AllSubscripts() + { + var allSubFuncs = Members.OfType().Where(decl => decl.IsSubscript).ToList(); + var allSubs = new List(); + while (allSubFuncs.Count > 0) + { + int i = allSubFuncs.Count - 1; + FunctionDeclaration decl = allSubFuncs[i]; + allSubFuncs.RemoveAt(i); + if (decl.IsSubscriptMaterializer) + continue; + if (decl.IsSubscriptGetter) + { + FunctionDeclaration setter = GetAndRemoveSetter(allSubFuncs, decl); + FunctionDeclaration materializer = GetAndRemoveMaterializer(allSubFuncs, decl); + allSubs.Add(new SubscriptDeclaration(decl, setter, materializer)); + } + else if (decl.IsSubscriptSetter) + { + FunctionDeclaration getter = GetAndRemoveGetter(allSubFuncs, decl); + FunctionDeclaration materializer = GetAndRemoveMaterializer(allSubFuncs, decl); + allSubs.Add(new SubscriptDeclaration(getter, decl, materializer)); + } + } + return allSubs; + } + + public TypeSpec ToTypeSpec() + { + NamedTypeSpec ns = new NamedTypeSpec(ToFullyQualifiedName()); + ns.GenericParameters.AddRange(Generics.Select(gen => new NamedTypeSpec(gen.Name))); + return ns; + } + + static FunctionDeclaration GetAndRemoveMaterializer(List decls, FunctionDeclaration other) + { + // FIXME - materializers don't have enough to match on with 100% confidence + // Materializers are (probably) not needed by tom-swifty, so no big + return null; + } + + static FunctionDeclaration GetAndRemoveGetter(List decls, FunctionDeclaration other) + { + var plToMatch = new List(); + TypeSpec returnToMatch = null; + var selfToMatch = other.Parent; + + if (other.IsSetter) + { + // setter - + // The arguments to a setter are + // value, arg1, arg2 ... argn + // We want to match the type of the return of the getter to the value of the setter + // as well as the parameters + List pl = other.ParameterLists.Last(); + plToMatch.AddRange(pl.GetRange(1, pl.Count - 1)); + returnToMatch = pl[0].TypeSpec; + } + else + { + // materializer. + // The arguments to a materializer are + // buffer, callbackStoragebuffer, arg1, arg2 ... argn + // We have no return to match. Oops. + List pl = other.ParameterLists.Last(); + plToMatch.AddRange(pl.GetRange(2, pl.Count - 2)); + returnToMatch = null; + } + + + for (int i = 0; i < decls.Count; i++) + { + FunctionDeclaration getter = decls[i]; + if (getter.Parent != selfToMatch) + return null; + if (!getter.IsSubscriptGetter) + continue; + if ((returnToMatch != null && returnToMatch.Equals(getter.ReturnTypeSpec)) || returnToMatch == null) + { + List targetPl = getter.ParameterLists.Last(); + if (ParmsMatch(plToMatch, targetPl)) + { + decls.RemoveAt(i); + return getter; + } + } + } + return null; + } + + static FunctionDeclaration GetAndRemoveSetter(List decls, FunctionDeclaration other) + { + var plToMatch = new List(); + var selfToMatch = other.Parent; + + if (other.IsGetter) + { + // getter - + // The arguments to a getter are + // arg1, arg2 ... argn + // We want to match the type of the return of the getter to the value of the setter + // as well as the parameters + List pl = other.ParameterLists.Last(); + ParameterItem item = new ParameterItem(); + item.PublicName = ""; + item.PrivateName = "retval"; + item.TypeSpec = other.ReturnTypeSpec; + item.TypeName = other.ReturnTypeName; + plToMatch.Add(item); + plToMatch.AddRange(pl); + } + else + { + // we don't have enough information to match on setter + // and since we don't use the materializer, NBD. + + // materializer. + // The arguments to a materializer are + // buffer, callbackStoragebuffer, arg1, arg2 ... argn + // We have no return to match. Oops. + return null; + } + + for (int i = 0; i < decls.Count; i++) + { + FunctionDeclaration setter = decls[i]; + if (!setter.IsSubscriptGetter) + continue; + List targetPl = setter.ParameterLists.Last(); + if (ParmsMatch(plToMatch, targetPl)) + { + decls.RemoveAt(i); + return setter; + } + } + return null; + } + + public bool VirtualMethodExistsInInheritedBoundType(FunctionDeclaration func, TypeMapper typeMapper) + { + // virtual methods are only in classes + if (!(this is ClassDeclaration)) + return false; + var classInheritance = Inheritance.FirstOrDefault(inh => inh.InheritanceKind == InheritanceKind.Class); + if (classInheritance == null) + return false; + + var inheritedEntity = typeMapper.GetEntityForTypeSpec(classInheritance.InheritedTypeSpec); + if (inheritedEntity == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 18, $"Unable to find type database entry for class {classInheritance.InheritedTypeName} while searching inheritance."); + + // if we get here, the Type has to be a ClassDeclaration + var inheritedClass = inheritedEntity.Type as ClassDeclaration; + + var methods = inheritedClass.AllVirtualMethods().FindAll(fn => fn.Name == func.Name + && fn.ParameterLists.Last().Count == func.ParameterLists.Last().Count).ToList(); + foreach (var method in methods) + { + if (ParmsMatchWithNames(method.ParameterLists.Last(), func.ParameterLists.Last()) + && method.ReturnTypeSpec.Equals(func.ReturnTypeSpec)) + return true; + } + return inheritedClass.VirtualMethodExistsInInheritedBoundType(func, typeMapper); + } + + static bool ParmsMatchWithNames(List pl1, List pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) + { + if (pl1[i].PublicName != pl2[i].PublicName) + return false; + if (pl1[i].IsInOut != pl2[i].IsInOut) + return false; + if (!pl1[i].TypeSpec.Equals(pl2[i].TypeSpec)) + return false; + } + return true; + } + + static bool ParmsMatch(List pl1, List pl2) + { + if (pl1.Count != pl2.Count) + return false; + for (int i = 0; i < pl1.Count; i++) + { + if (pl1[i].IsInOut != pl2[i].IsInOut) + return false; + if (!pl1[i].TypeSpec.Equals(pl2[i].TypeSpec)) + return false; + } + return true; + } + + + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs index 5ba78fc62604..682e7b551860 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs @@ -8,800 +8,882 @@ using System.Linq; using System.Collections; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeSpecAttribute { - public TypeSpecAttribute (string name) - { - Name = name; - Parameters = new List (); - } - public string Name { get; set; } - public List Parameters { get; private set; } - public override string ToString () - { - StringBuilder sb = new StringBuilder (); - sb.Append ('@'); - sb.Append (Name); - if (Parameters.Count > 0) { - sb.Append ('('); - for (int i = 0; i < Parameters.Count; i++) { - if (i > 0) - sb.Append (", "); - sb.Append (Parameters [i]); - } - sb.Append (')'); - } - return sb.ToString (); - } - } - - public abstract class TypeSpec { - protected TypeSpec (TypeSpecKind kind) - { - Kind = kind; - GenericParameters = new List (); - Attributes = new List (); - } - - public TypeSpecKind Kind { get; private set; } - public List GenericParameters { get; private set; } - public bool ContainsGenericParameters { get { return GenericParameters.Count != 0; } } - public List Attributes { get; private set; } - public bool HasAttributes { get { return Attributes.Count != 0; } } - public bool IsInOut { get; set; } - public bool IsAny { get; set; } - public virtual bool IsEmptyTuple { get { return false; } } - protected abstract string LLToString (bool useFullName); - protected virtual string LLFinalStringParts () { return ""; } - protected abstract bool LLEquals (TypeSpec other, bool partialNameMatch); - public string TypeLabel { get; set; } - public bool IsArray { - get { - NamedTypeSpec ns = this as NamedTypeSpec; - return ns != null && ns.Name == "Swift.Array"; - } - } - - public bool IsBoundGeneric (BaseDeclaration context, TypeMapper mapper) - { - switch (this.Kind) { - case TypeSpecKind.Named: - NamedTypeSpec ns = (NamedTypeSpec)this; - Entity en = mapper.TryGetEntityForSwiftClassName (ns.Name); - if (en == null) { - if (context.IsTypeSpecGeneric (ns)) - return false; // unbound - } - foreach (TypeSpec genParm in GenericParameters) { - if (genParm.IsUnboundGeneric (context, mapper)) - return false; // unbound - } - return true; - case TypeSpecKind.Closure: - ClosureTypeSpec cs = (ClosureTypeSpec)this; - return cs.Arguments.IsBoundGeneric (context, mapper) && cs.ReturnType.IsBoundGeneric (context, mapper); - case TypeSpecKind.Tuple: - TupleTypeSpec ts = (TupleTypeSpec)this; - foreach (TypeSpec elem in ts.Elements) { - if (elem.IsUnboundGeneric (context, mapper)) - return false; - } - return true; - default: - throw new NotSupportedException ("unknown TypeSpecKind " + this.Kind.ToString ()); - } - } - - public bool IsUnboundGeneric (BaseDeclaration context, TypeMapper mapper) - { - switch (Kind) { - case TypeSpecKind.Named: - NamedTypeSpec ns = (NamedTypeSpec)this; - if (context.IsTypeSpecGeneric (ns.ToString ())) - return true; - foreach (TypeSpec genparm in GenericParameters) { - if (genparm.IsUnboundGeneric (context, mapper)) - return true; - } - return false; - case TypeSpecKind.Closure: - ClosureTypeSpec cs = (ClosureTypeSpec)this; - return cs.Arguments.IsUnboundGeneric (context, mapper) && cs.ReturnType.IsUnboundGeneric (context, mapper); - case TypeSpecKind.Tuple: - TupleTypeSpec ts = (TupleTypeSpec)this; - foreach (TypeSpec elem in ts.Elements) { - if (elem.IsUnboundGeneric (context, mapper)) - return true; - } - return false; - case TypeSpecKind.ProtocolList: - return false; - default: - throw new NotSupportedException ("unknown TypeSpecKind " + this.Kind.ToString ()); - } - } - - - public override bool Equals (object obj) - { - TypeSpec spec = obj as TypeSpec; - if (spec == null) - return false; - if (Kind != spec.Kind) - return false; - if (!ListEqual (GenericParameters, spec.GenericParameters, false)) - return false; - if (IsInOut != spec.IsInOut) - return false; - // Don't compare IsAny - it's really not important (yet) - return LLEquals (spec, false); - } - - public bool EqualsPartialMatch (TypeSpec spec) - { - if (spec == null) - return false; - if (Kind != spec.Kind) - return false; - if (!ListEqual (GenericParameters, spec.GenericParameters, true)) - return false; - if (IsInOut != spec.IsInOut) - return false; - // Don't compare IsAny - it's really not important (yet) - return LLEquals (spec, true); - } - - public virtual bool EqualsReferenceInvaraint (TypeSpec type) - { - var a = ProjectAsNonReference (this); - var b = ProjectAsNonReference (type); - - if (b.Kind != a.Kind) - return false; - if (b.GetType () != a.GetType ()) - return false; - // shouldn't do Name equality except in functions - return a.LLEquals (b, false); - } - - public TypeSpec NonReferenceCloneOf () - { - if (!IsInOut) - return this; - var ty = MemberwiseClone () as TypeSpec; - ty.IsInOut = false; - return ty; - } - - static TypeSpec ProjectAsNonReference (TypeSpec a) - { - if (a.IsInOut) { - return a.NonReferenceCloneOf (); - } - var namedType = a as NamedTypeSpec; - if (namedType != null && namedType.GenericParameters.Count == 1) { - if (namedType.Name == "Swift.UnsafePointer" || namedType.Name == "Swift.UnsafeMutablePointer") - return namedType.GenericParameters [0]; - } - return a; - } - - - public override int GetHashCode () - { - return ToString ().GetHashCode (); - } - - protected static bool ListEqual (List one, List two, bool partialNameMatch) - { - if (one.Count != two.Count) - return false; - for (int i = 0; i < one.Count; i++) { - if (partialNameMatch) { - if (!one [i].EqualsPartialMatch (two [i])) - return false; - } else { - if (!one [i].Equals (two [i])) - return false; - } - } - return true; - } - - public static bool IsNullOrEmptyTuple (TypeSpec spec) - { - return spec == null || spec.IsEmptyTuple; - } - - public static bool BothNullOrEqual (TypeSpec one, TypeSpec two) - { - if (one == null && two == null) - return true; - if (one == null || two == null) - return false; - return one.Equals (two); - } - - public bool ContainsBoundGenericClosure () - { - return ContainsBoundGenericClosure (0); - } - - bool ContainsBoundGenericClosure (int depth) - { - if (this is NamedTypeSpec namedTypeSpec) { - foreach (var subSpec in namedTypeSpec.GenericParameters) { - if (subSpec.ContainsBoundGenericClosure (depth + 1)) - return true; - } - } else if (this is TupleTypeSpec tupleSpec) { - foreach (var subSpec in tupleSpec.Elements) { - if (subSpec.ContainsBoundGenericClosure (depth + 1)) - return true; - } - } else if (this is ClosureTypeSpec closureSpec) { - return depth > 0; - } - return false; - } - - public override string ToString () - { - return ToString (true); - } - - public string ToString (bool useFullNames) - { - StringBuilder builder = new StringBuilder (); - - foreach (var attr in Attributes) { - builder.Append (attr.ToString ()); - builder.Append (' '); - } - if (IsInOut) - builder.Append ("inout "); - - if (IsAny) - builder.Append ("any "); - - if (TypeLabel != null) { - builder.Append (TypeLabel).Append (": "); - } - builder.Append (LLToString (useFullNames)); - - if (ContainsGenericParameters) { - builder.Append ('<'); - for (int i = 0; i < GenericParameters.Count; i++) { - if (i > 0) - builder.Append (", "); - builder.Append (GenericParameters [i].ToString (useFullNames)); - } - builder.Append ('>'); - } - builder.Append (LLFinalStringParts ()); - - return builder.ToString (); - } - - static string [] intNames = { - "Swift.Int", "Swift.UInt", "Swift.Int8", "Swift.UInt8", - "Swift.Int16", "Swift.UInt16", "Swift.Int32", "Swift.UInt32", - "Swift.Int64", "Swift.UInt64", "Swift.Char" - }; - - public static bool IsIntegral (TypeSpec ts) - { - NamedTypeSpec named = ts as NamedTypeSpec; - if (named == null) - return false; - return Array.IndexOf (intNames, named.Name) >= 0; - } - - public static bool IsFloatingPoint (TypeSpec ts) - { - NamedTypeSpec named = ts as NamedTypeSpec; - if (named == null) - return false; - return named.Name == "Swift.Float" || named.Name == "Swift.Double" || named.Name == "CoreGraphics.CGFloat"; - } - - public static bool IsBoolean (TypeSpec ts) - { - NamedTypeSpec named = ts as NamedTypeSpec; - if (named == null) - return false; - return named.Name == "Swift.Bool"; - } - - public static bool IsBuiltInValueType (TypeSpec ts) - { - return IsIntegral (ts) || IsFloatingPoint (ts) || IsBoolean (ts); - } - - public TypeSpec WithInOutSet () - { - var theSpec = TypeSpecParser.Parse (this.ToString ()); - theSpec.IsInOut = true; - return theSpec; - } - - public bool IsDynamicSelf { - get { - return this is NamedTypeSpec ns && ns.Name == "Self"; - } - } - - public abstract bool HasDynamicSelf { - get; - } - - public static bool AnyHasDynamicSelf (List types) - { - return types.Any (t => t.HasDynamicSelf); - } - - public TypeSpec ReplaceName (string toFind, string replacement) - { - var result = this; - if (!String.IsNullOrEmpty (replacement)) - ReplaceName (this, toFind, replacement, ref result); - return result; - } - - static bool ReplaceName (TypeSpec original, string toFind, string replacement, ref TypeSpec result) - { - result = original; - var changed = false; - switch (original.Kind) { - case TypeSpecKind.Named: - changed = ReplaceName (original as NamedTypeSpec, toFind, replacement, ref result); - break; - case TypeSpecKind.ProtocolList: - changed = ReplaceName (original as ProtocolListTypeSpec, toFind, replacement, ref result); - break; - case TypeSpecKind.Closure: - changed = ReplaceName (original as ClosureTypeSpec, toFind, replacement, ref result); - break; - case TypeSpecKind.Tuple: - changed = ReplaceName (original as TupleTypeSpec, toFind, replacement, ref result); - break; - default: - throw new ArgumentOutOfRangeException ($"Unknown TypeSpec kind {original.Kind}"); - } - if (changed) { - result.Attributes.AddRange (original.Attributes); - result.TypeLabel = original.TypeLabel; - result.IsInOut = original.IsInOut; - result.IsAny = original.IsAny; - } - return changed; - } - - static bool ReplaceName (NamedTypeSpec named, string toFind, string replacement, ref TypeSpec result) - { - result = named; - var changed = false; - if (named.Name == toFind) { - changed = true; - result = new NamedTypeSpec (replacement); - } - var resultGenerics = new List (named.GenericParameters.Count); - var changedGenerics = ReplaceName (named.GenericParameters, toFind, replacement, resultGenerics); - - if (changedGenerics) { - if (!changed) { - result = new NamedTypeSpec (named.Name); - } - result.GenericParameters.AddRange (resultGenerics); - } else { - if (changed) - result.GenericParameters.AddRange (named.GenericParameters); - } - return changed || changedGenerics; - } - - static bool ReplaceName (List originalTypes, string toFind, string replacement, List resultTypes) - { - var changed = false; - foreach (var type in originalTypes) { - var result = type; - changed = ReplaceName (type, toFind, replacement, ref result) || changed; - resultTypes.Add (result); - } - return changed; - } - - static bool ReplaceName (TupleTypeSpec tuple, string toFind, string replacement, ref TypeSpec result) - { - List resultTypes = new List (tuple.Elements.Count); - if (ReplaceName (tuple.Elements, toFind, replacement, resultTypes)) { - result = new TupleTypeSpec (resultTypes); - return true; - } - result = tuple; - return false; - } - - static bool ReplaceName (ProtocolListTypeSpec protolist, string toFind, string replacement, ref TypeSpec result) - { - var originalProtos = new List (protolist.Protocols.Count); - var resultProtos = new List (protolist.Protocols.Count); - originalProtos.AddRange (protolist.Protocols.Keys); - if (ReplaceName (originalProtos, toFind, replacement, resultProtos)) { - result = new ProtocolListTypeSpec (resultProtos.OfType ()); - return true; - } - return false; - } - - static bool ReplaceName (ClosureTypeSpec closure, string toFind, string replacement, ref TypeSpec result) - { - var resultArgs = closure.Arguments; - var resultReturn = closure.ReturnType; - - var argsChanged = ReplaceName (closure.Arguments, toFind, replacement, ref resultArgs); - var returnChanged = ReplaceName (closure.ReturnType, toFind, replacement, ref resultReturn); - if (argsChanged || returnChanged) { - result = new ClosureTypeSpec (resultArgs, resultReturn); - return true; - } - return false; - } - } - - - public class NamedTypeSpec : TypeSpec { - public NamedTypeSpec (string name) - : base (TypeSpecKind.Named) - { - name = SwiftInterfaceReflector.SwiftInterfaceReflector.UnTick (name); - // Hack filter. - // For whatever reason, Any and AnyObject are not - // strictly in the Swift module. But they are. - // But they're not. - // What do I mean by this? - // Apple's demangler will print these as Swift.Any or - // Swift.AnyObject if the options are set to print - // fully qualified names, so I feel no remorse for doing - // this. - if (name == "Any") - name = "Swift.Any"; - else if (name == "AnyObject") - name = "Swift.AnyObject"; - Name = name; - } - - public NamedTypeSpec (string name, params TypeSpec[] genericSpecialization) - : this (name) - { - GenericParameters.AddRange (genericSpecialization); - } - - public NamedTypeSpec InnerType { get; set; } - - public bool IsProtocolList { get { return Name == "protocol"; } } - public string Name { get; private set; } - - protected override string LLToString (bool useFullName) - { - return useFullName ? Name : NameWithoutModule; - } - - protected override string LLFinalStringParts() - { - if (InnerType == null) - return ""; - return "." + InnerType; - } - - protected override bool LLEquals (TypeSpec other, bool partialNameMatch) - { - NamedTypeSpec spec = other as NamedTypeSpec; - if (spec == null) - return false; - var innersMatch = (InnerType == null && spec.InnerType == null) || (InnerType != null && InnerType.LLEquals (spec.InnerType, partialNameMatch)); - if (partialNameMatch) { - return NameWithoutModule == spec.NameWithoutModule && innersMatch; - } else { - return Name == spec.Name && innersMatch; - } - } - - public bool HasModule (BaseDeclaration context, TypeMapper typeMapper) - { - if (Name.Contains (".")) { - return !context.IsProtocolWithAssociatedTypesFullPath (new NamedTypeSpec (Name), typeMapper); - } else { - return false; - } - } - public string Module { - get { - return Name.Substring (0, Name.IndexOf ('.')); - } - } - public string NameWithoutModule { - get { - return Name.IndexOf ('.') >= 0 ? Name.Substring (Name.IndexOf ('.') + 1) : Name; - } - } - - public override bool HasDynamicSelf { - get { - if (Name == "Self") - return true; - return TypeSpec.AnyHasDynamicSelf (GenericParameters); - } - } - } - - - public class TupleTypeSpec : TypeSpec { - public TupleTypeSpec () - : base (TypeSpecKind.Tuple) - { - Elements = new List (); - } - - public TupleTypeSpec (TupleTypeSpec other) - : base (TypeSpecKind.Tuple) - { - Elements = new List (); - Elements.AddRange (other.Elements); - if (other.HasAttributes) - Attributes.AddRange (other.Attributes); - if (other.ContainsGenericParameters) - GenericParameters.AddRange (other.GenericParameters); - IsInOut = other.IsInOut; - } - - public TupleTypeSpec (IEnumerable elements) - : this () - { - Elements.AddRange (elements); - } - - public TupleTypeSpec (TypeSpec single) - : this () - { - Elements.Add (single); - } - - public List Elements { get; private set; } - - protected override string LLToString (bool useFullName) - { - StringBuilder builder = new StringBuilder (); - builder.Append ('('); - for (int i = 0; i < Elements.Count; i++) { - if (i > 0) - builder.Append (", "); - builder.Append (Elements [i].ToString (useFullName)); - } - builder.Append (')'); - return builder.ToString (); - } - - protected override bool LLEquals (TypeSpec other, bool partialNameMatch) - { - TupleTypeSpec spec = other as TupleTypeSpec; - if (spec == null) - return false; - return ListEqual (Elements, spec.Elements, partialNameMatch); - } - - public override bool IsEmptyTuple { - get { - return Elements.Count == 0; - } - } - - public override bool HasDynamicSelf => TypeSpec.AnyHasDynamicSelf (Elements); - - static TupleTypeSpec empty = new TupleTypeSpec (); - public static TupleTypeSpec Empty { get { return empty; } } - } - - public class ClosureTypeSpec : TypeSpec { - public ClosureTypeSpec () - : base (TypeSpecKind.Closure) - { - } - - public ClosureTypeSpec (TypeSpec arguments, TypeSpec returnType) - : this () - { - Arguments = arguments; - ReturnType = returnType; - } - - static ClosureTypeSpec voidVoid = new ClosureTypeSpec (TupleTypeSpec.Empty, TupleTypeSpec.Empty); - - public static ClosureTypeSpec VoidVoid { get { return voidVoid; } } - - public TypeSpec Arguments { get; set; } - public TypeSpec ReturnType { get; set; } - public bool Throws { get; set; } - public bool IsAsync { get; set; } - - public bool HasReturn () - { - return ReturnType != null && !ReturnType.IsEmptyTuple; - } - - public bool HasArguments () - { - return Arguments != null && !Arguments.IsEmptyTuple; - } - - public TupleTypeSpec ArgumentsAsTuple { - get { - if (Arguments is TupleTypeSpec tuple) - return tuple; - return new TupleTypeSpec (Arguments); - } - } - - public int ArgumentCount () - { - if (!HasArguments ()) - return 0; - if (Arguments is TupleTypeSpec tupe) { - return tupe.Elements.Count; - } - return 1; - } - - public IEnumerable EachArgument () - { - if (!HasArguments ()) - yield break; - TupleTypeSpec argList = Arguments as TupleTypeSpec; - if (argList != null) { - foreach (TypeSpec arg in argList.Elements) - yield return arg; - } else { - yield return Arguments; - } - } - - public TypeSpec GetArgument (int index) - { - if (index < 0 || index >= ArgumentCount ()) - throw new ArgumentOutOfRangeException (nameof (index)); - if (Arguments is TupleTypeSpec tuple) - return tuple.Elements [index]; - return Arguments; - } - - public bool IsEscaping { - get { - return HasAttributes && Attributes.Exists (attr => attr.Name == "escaping"); - } - } - - public bool IsAutoClosure { - get { - return HasAttributes && Attributes.Exists (attr => attr.Name == "autoclosure"); - } - } - - protected override string LLToString (bool useFullName) - { - StringBuilder builder = new StringBuilder (); - builder.Append (Arguments.ToString (useFullName)); - if (Throws) - builder.Append (" throws -> "); - else - builder.Append (" -> "); - builder.Append (ReturnType.ToString (useFullName)); - return builder.ToString (); - } - - protected override bool LLEquals (TypeSpec obj, bool partialNameMatch) - { - ClosureTypeSpec spec = obj as ClosureTypeSpec; - if (spec == null) - return false; - - if (partialNameMatch) { - if (Arguments == null && spec.Arguments == null && - ReturnType == null && spec.ReturnType == null) { - return true; - } - if (Arguments == null || spec.Arguments == null) - return false; - if (ReturnType == null || spec.ReturnType == null) - return false; - return Arguments.EqualsPartialMatch (spec.Arguments) && - ReturnType.EqualsPartialMatch (spec.ReturnType); - - } else { - var specArgs = spec.Arguments is TupleTypeSpec ? spec.Arguments : new TupleTypeSpec (spec.Arguments); - var thisArgs = Arguments is TupleTypeSpec ? Arguments : new TupleTypeSpec (Arguments); - return BothNullOrEqual (thisArgs, specArgs) && - BothNullOrEqual (ReturnType, spec.ReturnType); - } - } - - public override bool HasDynamicSelf { - get { - if (Arguments.HasDynamicSelf) - return true; - if (!IsNullOrEmptyTuple (ReturnType) && ReturnType.HasDynamicSelf) - return true; - return false; - } - } - } - - public class ProtocolListTypeSpec : TypeSpec { - - class SpecComparer : IComparer { - public int Compare (TypeSpec x, TypeSpec y) - { - if (x == null) - throw new ArgumentNullException (nameof (x)); - if (y == null) - throw new ArgumentNullException (nameof (y)); - - return StringComparer.Ordinal.Compare (x.ToString (), y.ToString ()); - } - } - - class SpecEqComparer : IEqualityComparer { - bool partialNameMatch; - public SpecEqComparer (bool partialNameMatch) - { - this.partialNameMatch = partialNameMatch; - } - - public bool Equals (TypeSpec x, TypeSpec y) - { - if (partialNameMatch) - return x.EqualsPartialMatch (y); - return x.Equals (y); - } - - public int GetHashCode (TypeSpec obj) - { - throw new NotImplementedException (); - } - } - - public ProtocolListTypeSpec () - : base (TypeSpecKind.ProtocolList) - { - Protocols = new SortedList (new SpecComparer ()); - } - - public ProtocolListTypeSpec (IEnumerable protos) - : this () - { - foreach (var proto in protos) - Protocols.Add (proto, false); - } - - public SortedList Protocols { get; private set; } - - protected override bool LLEquals (TypeSpec other, bool partialNameMatch) - { - var otherProtos = other as ProtocolListTypeSpec; - if (otherProtos == null) - return false; - if (otherProtos.Protocols.Count != Protocols.Count) - return false; - var eqComparer = new SpecEqComparer (partialNameMatch); - - return Protocols.Keys.SequenceEqual (otherProtos.Protocols.Keys, eqComparer); - } - - protected override string LLToString (bool useFullName) - { - return Protocols.Keys.Select (proto => proto.ToString ()).InterleaveStrings (" & "); - } - - public override bool HasDynamicSelf => false; - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeSpecAttribute + { + public TypeSpecAttribute(string name) + { + Name = name; + Parameters = new List(); + } + public string Name { get; set; } + public List Parameters { get; private set; } + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append('@'); + sb.Append(Name); + if (Parameters.Count > 0) + { + sb.Append('('); + for (int i = 0; i < Parameters.Count; i++) + { + if (i > 0) + sb.Append(", "); + sb.Append(Parameters[i]); + } + sb.Append(')'); + } + return sb.ToString(); + } + } + + public abstract class TypeSpec + { + protected TypeSpec(TypeSpecKind kind) + { + Kind = kind; + GenericParameters = new List(); + Attributes = new List(); + } + + public TypeSpecKind Kind { get; private set; } + public List GenericParameters { get; private set; } + public bool ContainsGenericParameters { get { return GenericParameters.Count != 0; } } + public List Attributes { get; private set; } + public bool HasAttributes { get { return Attributes.Count != 0; } } + public bool IsInOut { get; set; } + public bool IsAny { get; set; } + public virtual bool IsEmptyTuple { get { return false; } } + protected abstract string LLToString(bool useFullName); + protected virtual string LLFinalStringParts() { return ""; } + protected abstract bool LLEquals(TypeSpec other, bool partialNameMatch); + public string TypeLabel { get; set; } + public bool IsArray + { + get + { + NamedTypeSpec ns = this as NamedTypeSpec; + return ns != null && ns.Name == "Swift.Array"; + } + } + + public bool IsBoundGeneric(BaseDeclaration context, TypeMapper mapper) + { + switch (this.Kind) + { + case TypeSpecKind.Named: + NamedTypeSpec ns = (NamedTypeSpec)this; + Entity en = mapper.TryGetEntityForSwiftClassName(ns.Name); + if (en == null) + { + if (context.IsTypeSpecGeneric(ns)) + return false; // unbound + } + foreach (TypeSpec genParm in GenericParameters) + { + if (genParm.IsUnboundGeneric(context, mapper)) + return false; // unbound + } + return true; + case TypeSpecKind.Closure: + ClosureTypeSpec cs = (ClosureTypeSpec)this; + return cs.Arguments.IsBoundGeneric(context, mapper) && cs.ReturnType.IsBoundGeneric(context, mapper); + case TypeSpecKind.Tuple: + TupleTypeSpec ts = (TupleTypeSpec)this; + foreach (TypeSpec elem in ts.Elements) + { + if (elem.IsUnboundGeneric(context, mapper)) + return false; + } + return true; + default: + throw new NotSupportedException("unknown TypeSpecKind " + this.Kind.ToString()); + } + } + + public bool IsUnboundGeneric(BaseDeclaration context, TypeMapper mapper) + { + switch (Kind) + { + case TypeSpecKind.Named: + NamedTypeSpec ns = (NamedTypeSpec)this; + if (context.IsTypeSpecGeneric(ns.ToString())) + return true; + foreach (TypeSpec genparm in GenericParameters) + { + if (genparm.IsUnboundGeneric(context, mapper)) + return true; + } + return false; + case TypeSpecKind.Closure: + ClosureTypeSpec cs = (ClosureTypeSpec)this; + return cs.Arguments.IsUnboundGeneric(context, mapper) && cs.ReturnType.IsUnboundGeneric(context, mapper); + case TypeSpecKind.Tuple: + TupleTypeSpec ts = (TupleTypeSpec)this; + foreach (TypeSpec elem in ts.Elements) + { + if (elem.IsUnboundGeneric(context, mapper)) + return true; + } + return false; + case TypeSpecKind.ProtocolList: + return false; + default: + throw new NotSupportedException("unknown TypeSpecKind " + this.Kind.ToString()); + } + } + + + public override bool Equals(object obj) + { + TypeSpec spec = obj as TypeSpec; + if (spec == null) + return false; + if (Kind != spec.Kind) + return false; + if (!ListEqual(GenericParameters, spec.GenericParameters, false)) + return false; + if (IsInOut != spec.IsInOut) + return false; + // Don't compare IsAny - it's really not important (yet) + return LLEquals(spec, false); + } + + public bool EqualsPartialMatch(TypeSpec spec) + { + if (spec == null) + return false; + if (Kind != spec.Kind) + return false; + if (!ListEqual(GenericParameters, spec.GenericParameters, true)) + return false; + if (IsInOut != spec.IsInOut) + return false; + // Don't compare IsAny - it's really not important (yet) + return LLEquals(spec, true); + } + + public virtual bool EqualsReferenceInvaraint(TypeSpec type) + { + var a = ProjectAsNonReference(this); + var b = ProjectAsNonReference(type); + + if (b.Kind != a.Kind) + return false; + if (b.GetType() != a.GetType()) + return false; + // shouldn't do Name equality except in functions + return a.LLEquals(b, false); + } + + public TypeSpec NonReferenceCloneOf() + { + if (!IsInOut) + return this; + var ty = MemberwiseClone() as TypeSpec; + ty.IsInOut = false; + return ty; + } + + static TypeSpec ProjectAsNonReference(TypeSpec a) + { + if (a.IsInOut) + { + return a.NonReferenceCloneOf(); + } + var namedType = a as NamedTypeSpec; + if (namedType != null && namedType.GenericParameters.Count == 1) + { + if (namedType.Name == "Swift.UnsafePointer" || namedType.Name == "Swift.UnsafeMutablePointer") + return namedType.GenericParameters[0]; + } + return a; + } + + + public override int GetHashCode() + { + return ToString().GetHashCode(); + } + + protected static bool ListEqual(List one, List two, bool partialNameMatch) + { + if (one.Count != two.Count) + return false; + for (int i = 0; i < one.Count; i++) + { + if (partialNameMatch) + { + if (!one[i].EqualsPartialMatch(two[i])) + return false; + } + else + { + if (!one[i].Equals(two[i])) + return false; + } + } + return true; + } + + public static bool IsNullOrEmptyTuple(TypeSpec spec) + { + return spec == null || spec.IsEmptyTuple; + } + + public static bool BothNullOrEqual(TypeSpec one, TypeSpec two) + { + if (one == null && two == null) + return true; + if (one == null || two == null) + return false; + return one.Equals(two); + } + + public bool ContainsBoundGenericClosure() + { + return ContainsBoundGenericClosure(0); + } + + bool ContainsBoundGenericClosure(int depth) + { + if (this is NamedTypeSpec namedTypeSpec) + { + foreach (var subSpec in namedTypeSpec.GenericParameters) + { + if (subSpec.ContainsBoundGenericClosure(depth + 1)) + return true; + } + } + else if (this is TupleTypeSpec tupleSpec) + { + foreach (var subSpec in tupleSpec.Elements) + { + if (subSpec.ContainsBoundGenericClosure(depth + 1)) + return true; + } + } + else if (this is ClosureTypeSpec closureSpec) + { + return depth > 0; + } + return false; + } + + public override string ToString() + { + return ToString(true); + } + + public string ToString(bool useFullNames) + { + StringBuilder builder = new StringBuilder(); + + foreach (var attr in Attributes) + { + builder.Append(attr.ToString()); + builder.Append(' '); + } + if (IsInOut) + builder.Append("inout "); + + if (IsAny) + builder.Append("any "); + + if (TypeLabel != null) + { + builder.Append(TypeLabel).Append(": "); + } + builder.Append(LLToString(useFullNames)); + + if (ContainsGenericParameters) + { + builder.Append('<'); + for (int i = 0; i < GenericParameters.Count; i++) + { + if (i > 0) + builder.Append(", "); + builder.Append(GenericParameters[i].ToString(useFullNames)); + } + builder.Append('>'); + } + builder.Append(LLFinalStringParts()); + + return builder.ToString(); + } + + static string[] intNames = { + "Swift.Int", "Swift.UInt", "Swift.Int8", "Swift.UInt8", + "Swift.Int16", "Swift.UInt16", "Swift.Int32", "Swift.UInt32", + "Swift.Int64", "Swift.UInt64", "Swift.Char" + }; + + public static bool IsIntegral(TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return Array.IndexOf(intNames, named.Name) >= 0; + } + + public static bool IsFloatingPoint(TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return named.Name == "Swift.Float" || named.Name == "Swift.Double" || named.Name == "CoreGraphics.CGFloat"; + } + + public static bool IsBoolean(TypeSpec ts) + { + NamedTypeSpec named = ts as NamedTypeSpec; + if (named == null) + return false; + return named.Name == "Swift.Bool"; + } + + public static bool IsBuiltInValueType(TypeSpec ts) + { + return IsIntegral(ts) || IsFloatingPoint(ts) || IsBoolean(ts); + } + + public TypeSpec WithInOutSet() + { + var theSpec = TypeSpecParser.Parse(this.ToString()); + theSpec.IsInOut = true; + return theSpec; + } + + public bool IsDynamicSelf + { + get + { + return this is NamedTypeSpec ns && ns.Name == "Self"; + } + } + + public abstract bool HasDynamicSelf + { + get; + } + + public static bool AnyHasDynamicSelf(List types) + { + return types.Any(t => t.HasDynamicSelf); + } + + public TypeSpec ReplaceName(string toFind, string replacement) + { + var result = this; + if (!String.IsNullOrEmpty(replacement)) + ReplaceName(this, toFind, replacement, ref result); + return result; + } + + static bool ReplaceName(TypeSpec original, string toFind, string replacement, ref TypeSpec result) + { + result = original; + var changed = false; + switch (original.Kind) + { + case TypeSpecKind.Named: + changed = ReplaceName(original as NamedTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.ProtocolList: + changed = ReplaceName(original as ProtocolListTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.Closure: + changed = ReplaceName(original as ClosureTypeSpec, toFind, replacement, ref result); + break; + case TypeSpecKind.Tuple: + changed = ReplaceName(original as TupleTypeSpec, toFind, replacement, ref result); + break; + default: + throw new ArgumentOutOfRangeException($"Unknown TypeSpec kind {original.Kind}"); + } + if (changed) + { + result.Attributes.AddRange(original.Attributes); + result.TypeLabel = original.TypeLabel; + result.IsInOut = original.IsInOut; + result.IsAny = original.IsAny; + } + return changed; + } + + static bool ReplaceName(NamedTypeSpec named, string toFind, string replacement, ref TypeSpec result) + { + result = named; + var changed = false; + if (named.Name == toFind) + { + changed = true; + result = new NamedTypeSpec(replacement); + } + var resultGenerics = new List(named.GenericParameters.Count); + var changedGenerics = ReplaceName(named.GenericParameters, toFind, replacement, resultGenerics); + + if (changedGenerics) + { + if (!changed) + { + result = new NamedTypeSpec(named.Name); + } + result.GenericParameters.AddRange(resultGenerics); + } + else + { + if (changed) + result.GenericParameters.AddRange(named.GenericParameters); + } + return changed || changedGenerics; + } + + static bool ReplaceName(List originalTypes, string toFind, string replacement, List resultTypes) + { + var changed = false; + foreach (var type in originalTypes) + { + var result = type; + changed = ReplaceName(type, toFind, replacement, ref result) || changed; + resultTypes.Add(result); + } + return changed; + } + + static bool ReplaceName(TupleTypeSpec tuple, string toFind, string replacement, ref TypeSpec result) + { + List resultTypes = new List(tuple.Elements.Count); + if (ReplaceName(tuple.Elements, toFind, replacement, resultTypes)) + { + result = new TupleTypeSpec(resultTypes); + return true; + } + result = tuple; + return false; + } + + static bool ReplaceName(ProtocolListTypeSpec protolist, string toFind, string replacement, ref TypeSpec result) + { + var originalProtos = new List(protolist.Protocols.Count); + var resultProtos = new List(protolist.Protocols.Count); + originalProtos.AddRange(protolist.Protocols.Keys); + if (ReplaceName(originalProtos, toFind, replacement, resultProtos)) + { + result = new ProtocolListTypeSpec(resultProtos.OfType()); + return true; + } + return false; + } + + static bool ReplaceName(ClosureTypeSpec closure, string toFind, string replacement, ref TypeSpec result) + { + var resultArgs = closure.Arguments; + var resultReturn = closure.ReturnType; + + var argsChanged = ReplaceName(closure.Arguments, toFind, replacement, ref resultArgs); + var returnChanged = ReplaceName(closure.ReturnType, toFind, replacement, ref resultReturn); + if (argsChanged || returnChanged) + { + result = new ClosureTypeSpec(resultArgs, resultReturn); + return true; + } + return false; + } + } + + + public class NamedTypeSpec : TypeSpec + { + public NamedTypeSpec(string name) + : base(TypeSpecKind.Named) + { + name = SwiftInterfaceReflector.SwiftInterfaceReflector.UnTick(name); + // Hack filter. + // For whatever reason, Any and AnyObject are not + // strictly in the Swift module. But they are. + // But they're not. + // What do I mean by this? + // Apple's demangler will print these as Swift.Any or + // Swift.AnyObject if the options are set to print + // fully qualified names, so I feel no remorse for doing + // this. + if (name == "Any") + name = "Swift.Any"; + else if (name == "AnyObject") + name = "Swift.AnyObject"; + Name = name; + } + + public NamedTypeSpec(string name, params TypeSpec[] genericSpecialization) + : this(name) + { + GenericParameters.AddRange(genericSpecialization); + } + + public NamedTypeSpec InnerType { get; set; } + + public bool IsProtocolList { get { return Name == "protocol"; } } + public string Name { get; private set; } + + protected override string LLToString(bool useFullName) + { + return useFullName ? Name : NameWithoutModule; + } + + protected override string LLFinalStringParts() + { + if (InnerType == null) + return ""; + return "." + InnerType; + } + + protected override bool LLEquals(TypeSpec other, bool partialNameMatch) + { + NamedTypeSpec spec = other as NamedTypeSpec; + if (spec == null) + return false; + var innersMatch = (InnerType == null && spec.InnerType == null) || (InnerType != null && InnerType.LLEquals(spec.InnerType, partialNameMatch)); + if (partialNameMatch) + { + return NameWithoutModule == spec.NameWithoutModule && innersMatch; + } + else + { + return Name == spec.Name && innersMatch; + } + } + + public bool HasModule(BaseDeclaration context, TypeMapper typeMapper) + { + if (Name.Contains(".")) + { + return !context.IsProtocolWithAssociatedTypesFullPath(new NamedTypeSpec(Name), typeMapper); + } + else + { + return false; + } + } + public string Module + { + get + { + return Name.Substring(0, Name.IndexOf('.')); + } + } + public string NameWithoutModule + { + get + { + return Name.IndexOf('.') >= 0 ? Name.Substring(Name.IndexOf('.') + 1) : Name; + } + } + + public override bool HasDynamicSelf + { + get + { + if (Name == "Self") + return true; + return TypeSpec.AnyHasDynamicSelf(GenericParameters); + } + } + } + + + public class TupleTypeSpec : TypeSpec + { + public TupleTypeSpec() + : base(TypeSpecKind.Tuple) + { + Elements = new List(); + } + + public TupleTypeSpec(TupleTypeSpec other) + : base(TypeSpecKind.Tuple) + { + Elements = new List(); + Elements.AddRange(other.Elements); + if (other.HasAttributes) + Attributes.AddRange(other.Attributes); + if (other.ContainsGenericParameters) + GenericParameters.AddRange(other.GenericParameters); + IsInOut = other.IsInOut; + } + + public TupleTypeSpec(IEnumerable elements) + : this() + { + Elements.AddRange(elements); + } + + public TupleTypeSpec(TypeSpec single) + : this() + { + Elements.Add(single); + } + + public List Elements { get; private set; } + + protected override string LLToString(bool useFullName) + { + StringBuilder builder = new StringBuilder(); + builder.Append('('); + for (int i = 0; i < Elements.Count; i++) + { + if (i > 0) + builder.Append(", "); + builder.Append(Elements[i].ToString(useFullName)); + } + builder.Append(')'); + return builder.ToString(); + } + + protected override bool LLEquals(TypeSpec other, bool partialNameMatch) + { + TupleTypeSpec spec = other as TupleTypeSpec; + if (spec == null) + return false; + return ListEqual(Elements, spec.Elements, partialNameMatch); + } + + public override bool IsEmptyTuple + { + get + { + return Elements.Count == 0; + } + } + + public override bool HasDynamicSelf => TypeSpec.AnyHasDynamicSelf(Elements); + + static TupleTypeSpec empty = new TupleTypeSpec(); + public static TupleTypeSpec Empty { get { return empty; } } + } + + public class ClosureTypeSpec : TypeSpec + { + public ClosureTypeSpec() + : base(TypeSpecKind.Closure) + { + } + + public ClosureTypeSpec(TypeSpec arguments, TypeSpec returnType) + : this() + { + Arguments = arguments; + ReturnType = returnType; + } + + static ClosureTypeSpec voidVoid = new ClosureTypeSpec(TupleTypeSpec.Empty, TupleTypeSpec.Empty); + + public static ClosureTypeSpec VoidVoid { get { return voidVoid; } } + + public TypeSpec Arguments { get; set; } + public TypeSpec ReturnType { get; set; } + public bool Throws { get; set; } + public bool IsAsync { get; set; } + + public bool HasReturn() + { + return ReturnType != null && !ReturnType.IsEmptyTuple; + } + + public bool HasArguments() + { + return Arguments != null && !Arguments.IsEmptyTuple; + } + + public TupleTypeSpec ArgumentsAsTuple + { + get + { + if (Arguments is TupleTypeSpec tuple) + return tuple; + return new TupleTypeSpec(Arguments); + } + } + + public int ArgumentCount() + { + if (!HasArguments()) + return 0; + if (Arguments is TupleTypeSpec tupe) + { + return tupe.Elements.Count; + } + return 1; + } + + public IEnumerable EachArgument() + { + if (!HasArguments()) + yield break; + TupleTypeSpec argList = Arguments as TupleTypeSpec; + if (argList != null) + { + foreach (TypeSpec arg in argList.Elements) + yield return arg; + } + else + { + yield return Arguments; + } + } + + public TypeSpec GetArgument(int index) + { + if (index < 0 || index >= ArgumentCount()) + throw new ArgumentOutOfRangeException(nameof(index)); + if (Arguments is TupleTypeSpec tuple) + return tuple.Elements[index]; + return Arguments; + } + + public bool IsEscaping + { + get + { + return HasAttributes && Attributes.Exists(attr => attr.Name == "escaping"); + } + } + + public bool IsAutoClosure + { + get + { + return HasAttributes && Attributes.Exists(attr => attr.Name == "autoclosure"); + } + } + + protected override string LLToString(bool useFullName) + { + StringBuilder builder = new StringBuilder(); + builder.Append(Arguments.ToString(useFullName)); + if (Throws) + builder.Append(" throws -> "); + else + builder.Append(" -> "); + builder.Append(ReturnType.ToString(useFullName)); + return builder.ToString(); + } + + protected override bool LLEquals(TypeSpec obj, bool partialNameMatch) + { + ClosureTypeSpec spec = obj as ClosureTypeSpec; + if (spec == null) + return false; + + if (partialNameMatch) + { + if (Arguments == null && spec.Arguments == null && + ReturnType == null && spec.ReturnType == null) + { + return true; + } + if (Arguments == null || spec.Arguments == null) + return false; + if (ReturnType == null || spec.ReturnType == null) + return false; + return Arguments.EqualsPartialMatch(spec.Arguments) && + ReturnType.EqualsPartialMatch(spec.ReturnType); + + } + else + { + var specArgs = spec.Arguments is TupleTypeSpec ? spec.Arguments : new TupleTypeSpec(spec.Arguments); + var thisArgs = Arguments is TupleTypeSpec ? Arguments : new TupleTypeSpec(Arguments); + return BothNullOrEqual(thisArgs, specArgs) && + BothNullOrEqual(ReturnType, spec.ReturnType); + } + } + + public override bool HasDynamicSelf + { + get + { + if (Arguments.HasDynamicSelf) + return true; + if (!IsNullOrEmptyTuple(ReturnType) && ReturnType.HasDynamicSelf) + return true; + return false; + } + } + } + + public class ProtocolListTypeSpec : TypeSpec + { + + class SpecComparer : IComparer + { + public int Compare(TypeSpec x, TypeSpec y) + { + if (x == null) + throw new ArgumentNullException(nameof(x)); + if (y == null) + throw new ArgumentNullException(nameof(y)); + + return StringComparer.Ordinal.Compare(x.ToString(), y.ToString()); + } + } + + class SpecEqComparer : IEqualityComparer + { + bool partialNameMatch; + public SpecEqComparer(bool partialNameMatch) + { + this.partialNameMatch = partialNameMatch; + } + + public bool Equals(TypeSpec x, TypeSpec y) + { + if (partialNameMatch) + return x.EqualsPartialMatch(y); + return x.Equals(y); + } + + public int GetHashCode(TypeSpec obj) + { + throw new NotImplementedException(); + } + } + + public ProtocolListTypeSpec() + : base(TypeSpecKind.ProtocolList) + { + Protocols = new SortedList(new SpecComparer()); + } + + public ProtocolListTypeSpec(IEnumerable protos) + : this() + { + foreach (var proto in protos) + Protocols.Add(proto, false); + } + + public SortedList Protocols { get; private set; } + + protected override bool LLEquals(TypeSpec other, bool partialNameMatch) + { + var otherProtos = other as ProtocolListTypeSpec; + if (otherProtos == null) + return false; + if (otherProtos.Protocols.Count != Protocols.Count) + return false; + var eqComparer = new SpecEqComparer(partialNameMatch); + + return Protocols.Keys.SequenceEqual(otherProtos.Protocols.Keys, eqComparer); + } + + protected override string LLToString(bool useFullName) + { + return Protocols.Keys.Select(proto => proto.ToString()).InterleaveStrings(" & "); + } + + public override bool HasDynamicSelf => false; + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs index b4431af3e7a1..74466147b15d 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs @@ -7,296 +7,338 @@ using SwiftReflector.ExceptionTools; using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeSpecParser { - TextReader reader; - TypeSpecTokenizer tokenizer; - - TypeSpecParser (TextReader reader) - { - this.reader = reader; - tokenizer = new TypeSpecTokenizer (reader); - } - - TypeSpec Parse () - { - TypeSpecToken token = tokenizer.Peek (); - TypeSpec type = null; - List attrs = null; - var inout = false; - var isAny = false; - string typeLabel = null; - var throwsClosure = false; - var asyncClosure = false; - var expectClosure = false; - - // Prefix - - // parse any attributes - if (token.Kind == TypeTokenKind.At) { - attrs = ParseAttributes (); - token = tokenizer.Peek (); - } - - // looks like it's inout - if (token.Kind == TypeTokenKind.TypeName && token.Value == "inout") { - inout = true; - tokenizer.Next (); - token = tokenizer.Peek (); - } - - if (token.Kind == TypeTokenKind.TypeName && token.Value == "any") { - isAny = true; - tokenizer.Next (); - token = tokenizer.Peek (); - } - - if (token.Kind == TypeTokenKind.TypeLabel) { - typeLabel = token.Value; - tokenizer.Next (); - token = tokenizer.Peek (); - } - - - // meat - - - if (token.Kind == TypeTokenKind.LeftParenthesis) { // tuple - tokenizer.Next (); - TupleTypeSpec tuple = ParseTuple (); - type = tuple.Elements.Count == 1 ? tuple.Elements [0] : tuple; - typeLabel = type.TypeLabel; - type.TypeLabel = null; - } else if (token.Kind == TypeTokenKind.TypeName) { // name - tokenizer.Next (); - var tokenValue = token.Value.StartsWith ("ObjectiveC.", StringComparison.Ordinal) ? - "Foundation" + token.Value.Substring ("ObjectiveC".Length) : token.Value; - if (tokenValue == "Swift.Void") - type = TupleTypeSpec.Empty; - else - type = new NamedTypeSpec (tokenValue); - } else if (token.Kind == TypeTokenKind.LeftBracket) { // array - tokenizer.Next (); - type = ParseArray (); - } else { // illegal - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 0, $"Unexpected token {token.Value}."); - } - - if (tokenizer.NextIs ("async")) { - tokenizer.Next (); - asyncClosure = true; - expectClosure = true; - } - - if (tokenizer.NextIs ("throws")) { - tokenizer.Next (); - throwsClosure = true; - expectClosure = true; - } - - if (tokenizer.Peek ().Kind == TypeTokenKind.Arrow) { - tokenizer.Next (); - type = ParseClosure (type, throwsClosure, asyncClosure); - expectClosure = false; - throwsClosure = false; - asyncClosure = false; - } else if (expectClosure) { - var errorCase = asyncClosure && throwsClosure ? "'async throws'" : asyncClosure ? "'async'" : "'throws'"; - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 1, $"Unexpected token {tokenizer.Peek ().Value} after {errorCase} in a closure."); - } else if (tokenizer.Peek ().Kind == TypeTokenKind.LeftAngle) { - tokenizer.Next (); - type = Genericize (type); - } - - if (tokenizer.Peek().Kind == TypeTokenKind.Period) { - tokenizer.Next (); - var currType = type as NamedTypeSpec; - if (currType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 2, $"In parsing an inner type (type.type), first element is a {type.Kind} instead of a NamedTypeSpec."); - var nextType = Parse () as NamedTypeSpec; - if (nextType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 3, $"In parsing an inner type (type.type), the second element is a {nextType.Kind} instead of a NamedTypeSpec"); - currType.InnerType = nextType; - } - - // Postfix - - if (tokenizer.Peek ().Kind == TypeTokenKind.Ampersand) { - type = ParseProtocolList (type as NamedTypeSpec); - } - - while (tokenizer.Peek ().Kind == TypeTokenKind.QuestionMark) { - tokenizer.Next (); - type = WrapAsBoundGeneric (type, "Swift.Optional"); - } - - if (tokenizer.Peek ().Kind == TypeTokenKind.ExclamationPoint) { - tokenizer.Next (); - type = WrapAsBoundGeneric (type, "Swift.ImplicitlyUnwrappedOptional"); - } - - type.IsInOut = inout; - type.IsAny = isAny; - type.TypeLabel = typeLabel; - - if (type != null && attrs != null) { - type.Attributes.AddRange (attrs); - } - - return type; - } - - List ParseAttributes () - { - // An attribute is - // @name - // or - // @name [ parameters ] - // The spec says that it could be ( parameters ), [ parameters ], or { parameters } - // but the reflection code should make certain that it's [ parameters ]. - List attrs = new List (); - while (true) { - if (tokenizer.Peek ().Kind != TypeTokenKind.At) { - return attrs; - } - tokenizer.Next (); - if (tokenizer.Peek ().Kind != TypeTokenKind.TypeName) { - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 5, $"Unexpected token {tokenizer.Peek ().Value}, expected a name while parsing an attribute."); - } - string name = tokenizer.Next ().Value; - TypeSpecAttribute attr = new TypeSpecAttribute (name); - if (tokenizer.Peek ().Kind == TypeTokenKind.LeftBracket) { - tokenizer.Next (); - ParseAttributeParameters (attr.Parameters); - } - attrs.Add (attr); - } - } - - void ParseAttributeParameters (List parameters) - { - // Attribute parameters are funny - // The contents between the brackets vary. - // They may be comma separated. They may not. - // Therefore this code is likely to break, but since I'm responsible for - // generating the text of the attributes parsed here, I can try to ensure - // that it will always fit the pattern. - while (true) { - if (tokenizer.Peek ().Kind == TypeTokenKind.RightBracket) { - tokenizer.Next (); - return; - } - TypeSpecToken value = tokenizer.Next (); - if (value.Kind != TypeTokenKind.TypeName) { - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 6, $"Unexpected token {value.Value} while parsing attribute parameter."); - } - parameters.Add (value.Value); - if (tokenizer.Peek ().Kind == TypeTokenKind.Comma) { - tokenizer.Next (); - } - } - } - - TypeSpec ParseProtocolList (NamedTypeSpec first) - { - Exceptions.ThrowOnNull (first, nameof (first)); - var protocols = new List (); - protocols.Add (first); - while (true) { - if (tokenizer.Peek ().Kind != TypeTokenKind.Ampersand) - break; - tokenizer.Next (); - var nextName = tokenizer.Next (); - if (nextName.Kind != TypeTokenKind.TypeName) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 13, $"Unexpected token '{nextName.Value}' with kind {nextName.Kind} while parsing a protocol list"); - protocols.Add (new NamedTypeSpec (nextName.Value)); - } - return new ProtocolListTypeSpec (protocols); - } - - void ConsumeList (List elements, TypeTokenKind terminator, string typeImParsing) - { - while (true) { - if (tokenizer.Peek ().Kind == terminator) { - tokenizer.Next (); - return; - } - TypeSpec next = Parse (); - if (next == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 8, $"Unexpected end while parsing a {typeImParsing}"); - elements.Add (next); - if (tokenizer.Peek ().Kind == TypeTokenKind.Comma) { - tokenizer.Next (); - } - } - } - - TypeSpec Genericize (TypeSpec type) - { - ConsumeList (type.GenericParameters, TypeTokenKind.RightAngle, "generic parameter list"); - return type; - } - - TypeSpec WrapAsBoundGeneric(TypeSpec type, string name) - { - var result = new NamedTypeSpec (name); - result.GenericParameters.Add (type); - return result; - } - - TupleTypeSpec ParseTuple () - { - TupleTypeSpec tuple = new TupleTypeSpec (); - ConsumeList (tuple.Elements, TypeTokenKind.RightParenthesis, "tuple"); - return tuple; - } - - NamedTypeSpec ParseArray() - { - var keyType = Parse (); - TypeSpec valueType = null; - if (keyType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 9, "Unexpected end while parsing an array or dictionary."); - if (tokenizer.Peek ().Kind == TypeTokenKind.Colon) { - tokenizer.Next (); - valueType = Parse (); - if (valueType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 10, "Unexpected end while parsing a dictionary value type."); - } else if (tokenizer.Peek ().Kind != TypeTokenKind.RightBracket) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 11, "Expected a right bracket after an array or dictionary."); - - tokenizer.Next (); - - if (valueType == null) { - var array = new NamedTypeSpec ("Swift.Array"); - array.GenericParameters.Add (keyType); - return array; - } else { - var dictionary = new NamedTypeSpec ("Swift.Dictionary"); - dictionary.GenericParameters.Add (keyType); - dictionary.GenericParameters.Add (valueType); - return dictionary; - } - } - - ClosureTypeSpec ParseClosure (TypeSpec arg, bool throws, bool isAsync) - { - TypeSpec returnType = Parse (); - if (returnType == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 12, "Unexpected end while parsing a closure."); - ClosureTypeSpec closure = new ClosureTypeSpec (); - closure.Arguments = arg; - closure.ReturnType = returnType; - closure.Throws = throws; - closure.IsAsync = isAsync; - return closure; - } - - public static TypeSpec Parse (string typeName) - { - TypeSpecParser parser = new TypeSpecParser (new StringReader (typeName)); - return parser.Parse (); - } - } +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeSpecParser + { + TextReader reader; + TypeSpecTokenizer tokenizer; + + TypeSpecParser(TextReader reader) + { + this.reader = reader; + tokenizer = new TypeSpecTokenizer(reader); + } + + TypeSpec Parse() + { + TypeSpecToken token = tokenizer.Peek(); + TypeSpec type = null; + List attrs = null; + var inout = false; + var isAny = false; + string typeLabel = null; + var throwsClosure = false; + var asyncClosure = false; + var expectClosure = false; + + // Prefix + + // parse any attributes + if (token.Kind == TypeTokenKind.At) + { + attrs = ParseAttributes(); + token = tokenizer.Peek(); + } + + // looks like it's inout + if (token.Kind == TypeTokenKind.TypeName && token.Value == "inout") + { + inout = true; + tokenizer.Next(); + token = tokenizer.Peek(); + } + + if (token.Kind == TypeTokenKind.TypeName && token.Value == "any") + { + isAny = true; + tokenizer.Next(); + token = tokenizer.Peek(); + } + + if (token.Kind == TypeTokenKind.TypeLabel) + { + typeLabel = token.Value; + tokenizer.Next(); + token = tokenizer.Peek(); + } + + + // meat + + + if (token.Kind == TypeTokenKind.LeftParenthesis) + { // tuple + tokenizer.Next(); + TupleTypeSpec tuple = ParseTuple(); + type = tuple.Elements.Count == 1 ? tuple.Elements[0] : tuple; + typeLabel = type.TypeLabel; + type.TypeLabel = null; + } + else if (token.Kind == TypeTokenKind.TypeName) + { // name + tokenizer.Next(); + var tokenValue = token.Value.StartsWith("ObjectiveC.", StringComparison.Ordinal) ? + "Foundation" + token.Value.Substring("ObjectiveC".Length) : token.Value; + if (tokenValue == "Swift.Void") + type = TupleTypeSpec.Empty; + else + type = new NamedTypeSpec(tokenValue); + } + else if (token.Kind == TypeTokenKind.LeftBracket) + { // array + tokenizer.Next(); + type = ParseArray(); + } + else + { // illegal + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 0, $"Unexpected token {token.Value}."); + } + + if (tokenizer.NextIs("async")) + { + tokenizer.Next(); + asyncClosure = true; + expectClosure = true; + } + + if (tokenizer.NextIs("throws")) + { + tokenizer.Next(); + throwsClosure = true; + expectClosure = true; + } + + if (tokenizer.Peek().Kind == TypeTokenKind.Arrow) + { + tokenizer.Next(); + type = ParseClosure(type, throwsClosure, asyncClosure); + expectClosure = false; + throwsClosure = false; + asyncClosure = false; + } + else if (expectClosure) + { + var errorCase = asyncClosure && throwsClosure ? "'async throws'" : asyncClosure ? "'async'" : "'throws'"; + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 1, $"Unexpected token {tokenizer.Peek().Value} after {errorCase} in a closure."); + } + else if (tokenizer.Peek().Kind == TypeTokenKind.LeftAngle) + { + tokenizer.Next(); + type = Genericize(type); + } + + if (tokenizer.Peek().Kind == TypeTokenKind.Period) + { + tokenizer.Next(); + var currType = type as NamedTypeSpec; + if (currType == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 2, $"In parsing an inner type (type.type), first element is a {type.Kind} instead of a NamedTypeSpec."); + var nextType = Parse() as NamedTypeSpec; + if (nextType == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 3, $"In parsing an inner type (type.type), the second element is a {nextType.Kind} instead of a NamedTypeSpec"); + currType.InnerType = nextType; + } + + // Postfix + + if (tokenizer.Peek().Kind == TypeTokenKind.Ampersand) + { + type = ParseProtocolList(type as NamedTypeSpec); + } + + while (tokenizer.Peek().Kind == TypeTokenKind.QuestionMark) + { + tokenizer.Next(); + type = WrapAsBoundGeneric(type, "Swift.Optional"); + } + + if (tokenizer.Peek().Kind == TypeTokenKind.ExclamationPoint) + { + tokenizer.Next(); + type = WrapAsBoundGeneric(type, "Swift.ImplicitlyUnwrappedOptional"); + } + + type.IsInOut = inout; + type.IsAny = isAny; + type.TypeLabel = typeLabel; + + if (type != null && attrs != null) + { + type.Attributes.AddRange(attrs); + } + + return type; + } + + List ParseAttributes() + { + // An attribute is + // @name + // or + // @name [ parameters ] + // The spec says that it could be ( parameters ), [ parameters ], or { parameters } + // but the reflection code should make certain that it's [ parameters ]. + List attrs = new List(); + while (true) + { + if (tokenizer.Peek().Kind != TypeTokenKind.At) + { + return attrs; + } + tokenizer.Next(); + if (tokenizer.Peek().Kind != TypeTokenKind.TypeName) + { + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 5, $"Unexpected token {tokenizer.Peek().Value}, expected a name while parsing an attribute."); + } + string name = tokenizer.Next().Value; + TypeSpecAttribute attr = new TypeSpecAttribute(name); + if (tokenizer.Peek().Kind == TypeTokenKind.LeftBracket) + { + tokenizer.Next(); + ParseAttributeParameters(attr.Parameters); + } + attrs.Add(attr); + } + } + + void ParseAttributeParameters(List parameters) + { + // Attribute parameters are funny + // The contents between the brackets vary. + // They may be comma separated. They may not. + // Therefore this code is likely to break, but since I'm responsible for + // generating the text of the attributes parsed here, I can try to ensure + // that it will always fit the pattern. + while (true) + { + if (tokenizer.Peek().Kind == TypeTokenKind.RightBracket) + { + tokenizer.Next(); + return; + } + TypeSpecToken value = tokenizer.Next(); + if (value.Kind != TypeTokenKind.TypeName) + { + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 6, $"Unexpected token {value.Value} while parsing attribute parameter."); + } + parameters.Add(value.Value); + if (tokenizer.Peek().Kind == TypeTokenKind.Comma) + { + tokenizer.Next(); + } + } + } + + TypeSpec ParseProtocolList(NamedTypeSpec first) + { + Exceptions.ThrowOnNull(first, nameof(first)); + var protocols = new List(); + protocols.Add(first); + while (true) + { + if (tokenizer.Peek().Kind != TypeTokenKind.Ampersand) + break; + tokenizer.Next(); + var nextName = tokenizer.Next(); + if (nextName.Kind != TypeTokenKind.TypeName) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 13, $"Unexpected token '{nextName.Value}' with kind {nextName.Kind} while parsing a protocol list"); + protocols.Add(new NamedTypeSpec(nextName.Value)); + } + return new ProtocolListTypeSpec(protocols); + } + + void ConsumeList(List elements, TypeTokenKind terminator, string typeImParsing) + { + while (true) + { + if (tokenizer.Peek().Kind == terminator) + { + tokenizer.Next(); + return; + } + TypeSpec next = Parse(); + if (next == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 8, $"Unexpected end while parsing a {typeImParsing}"); + elements.Add(next); + if (tokenizer.Peek().Kind == TypeTokenKind.Comma) + { + tokenizer.Next(); + } + } + } + + TypeSpec Genericize(TypeSpec type) + { + ConsumeList(type.GenericParameters, TypeTokenKind.RightAngle, "generic parameter list"); + return type; + } + + TypeSpec WrapAsBoundGeneric(TypeSpec type, string name) + { + var result = new NamedTypeSpec(name); + result.GenericParameters.Add(type); + return result; + } + + TupleTypeSpec ParseTuple() + { + TupleTypeSpec tuple = new TupleTypeSpec(); + ConsumeList(tuple.Elements, TypeTokenKind.RightParenthesis, "tuple"); + return tuple; + } + + NamedTypeSpec ParseArray() + { + var keyType = Parse(); + TypeSpec valueType = null; + if (keyType == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 9, "Unexpected end while parsing an array or dictionary."); + if (tokenizer.Peek().Kind == TypeTokenKind.Colon) + { + tokenizer.Next(); + valueType = Parse(); + if (valueType == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 10, "Unexpected end while parsing a dictionary value type."); + } + else if (tokenizer.Peek().Kind != TypeTokenKind.RightBracket) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 11, "Expected a right bracket after an array or dictionary."); + + tokenizer.Next(); + + if (valueType == null) + { + var array = new NamedTypeSpec("Swift.Array"); + array.GenericParameters.Add(keyType); + return array; + } + else + { + var dictionary = new NamedTypeSpec("Swift.Dictionary"); + dictionary.GenericParameters.Add(keyType); + dictionary.GenericParameters.Add(valueType); + return dictionary; + } + } + + ClosureTypeSpec ParseClosure(TypeSpec arg, bool throws, bool isAsync) + { + TypeSpec returnType = Parse(); + if (returnType == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 12, "Unexpected end while parsing a closure."); + ClosureTypeSpec closure = new ClosureTypeSpec(); + closure.Arguments = arg; + closure.ReturnType = returnType; + closure.Throws = throws; + closure.IsAsync = isAsync; + return closure; + } + + public static TypeSpec Parse(string typeName) + { + TypeSpecParser parser = new TypeSpecParser(new StringReader(typeName)); + return parser.Parse(); + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs index 742401a1717a..7ab2db7b76e3 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs @@ -3,59 +3,61 @@ using SwiftRuntimeLibrary; -namespace SwiftReflector.SwiftXmlReflection { - public class TypeSpecToken { - TypeSpecToken (TypeTokenKind kind, string value) - { - Kind = kind; - Value = value; - } - public TypeTokenKind Kind { get; private set; } - public string Value { get; private set; } - public static TypeSpecToken LabelFromString (string value) - { - return new TypeSpecToken (TypeTokenKind.TypeLabel, Exceptions.ThrowOnNull (value, "value")); - } - public static TypeSpecToken FromString (string value) - { - return new TypeSpecToken (TypeTokenKind.TypeName, Exceptions.ThrowOnNull (value, "value")); - } - static TypeSpecToken leftparenthesis = new TypeSpecToken (TypeTokenKind.LeftParenthesis, "("); - static TypeSpecToken rightparenthesis = new TypeSpecToken (TypeTokenKind.RightParenthesis, ")"); - static TypeSpecToken leftangle = new TypeSpecToken (TypeTokenKind.LeftAngle, "<"); - static TypeSpecToken rightangle = new TypeSpecToken (TypeTokenKind.RightAngle, ">"); - static TypeSpecToken comma = new TypeSpecToken (TypeTokenKind.Comma, ","); - static TypeSpecToken arrow = new TypeSpecToken (TypeTokenKind.Arrow, "->"); - static TypeSpecToken at = new TypeSpecToken (TypeTokenKind.At, "@"); - static TypeSpecToken questionmark = new TypeSpecToken (TypeTokenKind.QuestionMark, "?"); - static TypeSpecToken exclamationpoint = new TypeSpecToken (TypeTokenKind.ExclamationPoint, "!"); - static TypeSpecToken done = new TypeSpecToken (TypeTokenKind.Done, ""); - static TypeSpecToken leftbracket = new TypeSpecToken (TypeTokenKind.LeftBracket, "["); - static TypeSpecToken rightbracket = new TypeSpecToken (TypeTokenKind.RightBracket, "]"); - static TypeSpecToken colon = new TypeSpecToken (TypeTokenKind.Colon, ":"); - static TypeSpecToken period = new TypeSpecToken (TypeTokenKind.Period, ".'"); - static TypeSpecToken ampersand = new TypeSpecToken (TypeTokenKind.Ampersand, "&"); +namespace SwiftReflector.SwiftXmlReflection +{ + public class TypeSpecToken + { + TypeSpecToken(TypeTokenKind kind, string value) + { + Kind = kind; + Value = value; + } + public TypeTokenKind Kind { get; private set; } + public string Value { get; private set; } + public static TypeSpecToken LabelFromString(string value) + { + return new TypeSpecToken(TypeTokenKind.TypeLabel, Exceptions.ThrowOnNull(value, "value")); + } + public static TypeSpecToken FromString(string value) + { + return new TypeSpecToken(TypeTokenKind.TypeName, Exceptions.ThrowOnNull(value, "value")); + } + static TypeSpecToken leftparenthesis = new TypeSpecToken(TypeTokenKind.LeftParenthesis, "("); + static TypeSpecToken rightparenthesis = new TypeSpecToken(TypeTokenKind.RightParenthesis, ")"); + static TypeSpecToken leftangle = new TypeSpecToken(TypeTokenKind.LeftAngle, "<"); + static TypeSpecToken rightangle = new TypeSpecToken(TypeTokenKind.RightAngle, ">"); + static TypeSpecToken comma = new TypeSpecToken(TypeTokenKind.Comma, ","); + static TypeSpecToken arrow = new TypeSpecToken(TypeTokenKind.Arrow, "->"); + static TypeSpecToken at = new TypeSpecToken(TypeTokenKind.At, "@"); + static TypeSpecToken questionmark = new TypeSpecToken(TypeTokenKind.QuestionMark, "?"); + static TypeSpecToken exclamationpoint = new TypeSpecToken(TypeTokenKind.ExclamationPoint, "!"); + static TypeSpecToken done = new TypeSpecToken(TypeTokenKind.Done, ""); + static TypeSpecToken leftbracket = new TypeSpecToken(TypeTokenKind.LeftBracket, "["); + static TypeSpecToken rightbracket = new TypeSpecToken(TypeTokenKind.RightBracket, "]"); + static TypeSpecToken colon = new TypeSpecToken(TypeTokenKind.Colon, ":"); + static TypeSpecToken period = new TypeSpecToken(TypeTokenKind.Period, ".'"); + static TypeSpecToken ampersand = new TypeSpecToken(TypeTokenKind.Ampersand, "&"); - public static TypeSpecToken LeftParenthesis { get { return leftparenthesis; } } - public static TypeSpecToken RightParenthesis { get { return rightparenthesis; } } - public static TypeSpecToken LeftAngle { get { return leftangle; } } - public static TypeSpecToken RightAngle { get { return rightangle; } } - public static TypeSpecToken Comma { get { return comma; } } - public static TypeSpecToken Arrow { get { return arrow; } } - public static TypeSpecToken At { get { return at; } } - public static TypeSpecToken QuestionMark { get { return questionmark; } } - public static TypeSpecToken ExclamationPoint { get { return exclamationpoint; }} - public static TypeSpecToken Done { get { return done; } } - public static TypeSpecToken LeftBracket { get { return leftbracket; } } - public static TypeSpecToken RightBracket { get { return rightbracket; } } - public static TypeSpecToken Colon { get { return colon; } } - public static TypeSpecToken Period { get { return period; } } - public static TypeSpecToken Ampersand { get { return ampersand; } } - public override string ToString () - { - return Value; - } - } + public static TypeSpecToken LeftParenthesis { get { return leftparenthesis; } } + public static TypeSpecToken RightParenthesis { get { return rightparenthesis; } } + public static TypeSpecToken LeftAngle { get { return leftangle; } } + public static TypeSpecToken RightAngle { get { return rightangle; } } + public static TypeSpecToken Comma { get { return comma; } } + public static TypeSpecToken Arrow { get { return arrow; } } + public static TypeSpecToken At { get { return at; } } + public static TypeSpecToken QuestionMark { get { return questionmark; } } + public static TypeSpecToken ExclamationPoint { get { return exclamationpoint; } } + public static TypeSpecToken Done { get { return done; } } + public static TypeSpecToken LeftBracket { get { return leftbracket; } } + public static TypeSpecToken RightBracket { get { return rightbracket; } } + public static TypeSpecToken Colon { get { return colon; } } + public static TypeSpecToken Period { get { return period; } } + public static TypeSpecToken Ampersand { get { return ampersand; } } + public override string ToString() + { + return Value; + } + } } diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs index bfea78bfd64e..c7218d134de8 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs @@ -6,195 +6,220 @@ using System.IO; using SwiftReflector.ExceptionTools; -namespace SwiftReflector.SwiftXmlReflection { +namespace SwiftReflector.SwiftXmlReflection +{ - public class TypeSpecTokenizer { - enum State { - Start, - InName, - InArrow, - }; + public class TypeSpecTokenizer + { + enum State + { + Start, + InName, + InArrow, + }; - State state; - StringBuilder buffer; - TextReader reader; - static string invalidNameChars; + State state; + StringBuilder buffer; + TextReader reader; + static string invalidNameChars; - static TypeSpecTokenizer () - { - // OK - thanks Apple. Since identifiers in Swift can be any messed up unicode, including emoji, we - // can't just ask "IsLetterOrNumber". Instead, I build the set of characters that are specifically - // forbidden. Guh. - StringBuilder sb = new StringBuilder (); - for (char c = (char)0; c < '.'; c++) { - sb.Append (c); - } - sb.Append ('/'); - for (char c = ':'; c < 'A'; c++) { - sb.Append (c); - } - for (char c = '['; c < '_'; c++) { - sb.Append (c); - } - sb.Append ('`'); - for (char c = '{'; c <= (char)127; c++) { - sb.Append (c); - } - invalidNameChars = sb.ToString (); - } + static TypeSpecTokenizer() + { + // OK - thanks Apple. Since identifiers in Swift can be any messed up unicode, including emoji, we + // can't just ask "IsLetterOrNumber". Instead, I build the set of characters that are specifically + // forbidden. Guh. + StringBuilder sb = new StringBuilder(); + for (char c = (char)0; c < '.'; c++) + { + sb.Append(c); + } + sb.Append('/'); + for (char c = ':'; c < 'A'; c++) + { + sb.Append(c); + } + for (char c = '['; c < '_'; c++) + { + sb.Append(c); + } + sb.Append('`'); + for (char c = '{'; c <= (char)127; c++) + { + sb.Append(c); + } + invalidNameChars = sb.ToString(); + } - public TypeSpecTokenizer (TextReader reader) - { - this.reader = reader; - buffer = new StringBuilder (); - state = State.Start; - } + public TypeSpecTokenizer(TextReader reader) + { + this.reader = reader; + buffer = new StringBuilder(); + state = State.Start; + } - TypeSpecToken curr = null; + TypeSpecToken curr = null; - public TypeSpecToken Peek () - { - if (curr == null) { - curr = Next (); - } - return curr; - } + public TypeSpecToken Peek() + { + if (curr == null) + { + curr = Next(); + } + return curr; + } - public TypeSpecToken Next () - { - if (curr != null) { - TypeSpecToken retval = curr; - curr = null; - return retval; - } - TypeSpecToken token = null; - do { - switch (state) { - case State.InName: - token = DoName (); - break; - case State.InArrow: - token = DoArrow (); - break; - case State.Start: - token = DoStart (); - break; - } - } while (token == null); - return token; - } + public TypeSpecToken Next() + { + if (curr != null) + { + TypeSpecToken retval = curr; + curr = null; + return retval; + } + TypeSpecToken token = null; + do + { + switch (state) + { + case State.InName: + token = DoName(); + break; + case State.InArrow: + token = DoArrow(); + break; + case State.Start: + token = DoStart(); + break; + } + } while (token == null); + return token; + } - public bool NextIs (string name) - { - return Peek ().Kind == TypeTokenKind.TypeName && Peek ().Value == name; - } + public bool NextIs(string name) + { + return Peek().Kind == TypeTokenKind.TypeName && Peek().Value == name; + } - TypeSpecToken DoName () - { - int curr = reader.Peek (); - if (curr < 0 || InvalidNameCharacter ((char)curr)) { - if (curr == ':') { - reader.Read (); // drop the colon - state = State.Start; - TypeSpecToken token = TypeSpecToken.LabelFromString (buffer.ToString ()); - buffer.Clear (); - return token; - } else { - state = State.Start; - TypeSpecToken token = TypeSpecToken.FromString (buffer.ToString ()); - buffer.Clear (); - return token; - } - } else { - buffer.Append ((char)reader.Read ()); - return null; - } - } + TypeSpecToken DoName() + { + int curr = reader.Peek(); + if (curr < 0 || InvalidNameCharacter((char)curr)) + { + if (curr == ':') + { + reader.Read(); // drop the colon + state = State.Start; + TypeSpecToken token = TypeSpecToken.LabelFromString(buffer.ToString()); + buffer.Clear(); + return token; + } + else + { + state = State.Start; + TypeSpecToken token = TypeSpecToken.FromString(buffer.ToString()); + buffer.Clear(); + return token; + } + } + else + { + buffer.Append((char)reader.Read()); + return null; + } + } - TypeSpecToken DoArrow () - { - if (buffer.Length == 0) { - if (reader.Peek () == (int)'-') { - buffer.Append ((char)reader.Read ()); - return null; - } - } else { - if (reader.Peek () == (int)'>') { - reader.Read (); - buffer.Clear (); - state = State.Start; - return TypeSpecToken.Arrow; - } - } - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 4, $"Unexpected character {(char)reader.Peek ()} while parsing '->'."); - } + TypeSpecToken DoArrow() + { + if (buffer.Length == 0) + { + if (reader.Peek() == (int)'-') + { + buffer.Append((char)reader.Read()); + return null; + } + } + else + { + if (reader.Peek() == (int)'>') + { + reader.Read(); + buffer.Clear(); + state = State.Start; + return TypeSpecToken.Arrow; + } + } + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 4, $"Unexpected character {(char)reader.Peek()} while parsing '->'."); + } - TypeSpecToken DoStart () - { - int currentChar = reader.Peek (); - if (currentChar < 0) - return TypeSpecToken.Done; - char c = (char)currentChar; - switch (c) { - case '(': - reader.Read (); - return TypeSpecToken.LeftParenthesis; - case ')': - reader.Read (); - return TypeSpecToken.RightParenthesis; - case '<': - reader.Read (); - return TypeSpecToken.LeftAngle; - case '>': - reader.Read (); - return TypeSpecToken.RightAngle; - case ',': - reader.Read (); - return TypeSpecToken.Comma; - case '@': - reader.Read (); - return TypeSpecToken.At; - case '?': - reader.Read (); - return TypeSpecToken.QuestionMark; - case '!': - reader.Read (); - return TypeSpecToken.ExclamationPoint; - case '-': - state = State.InArrow; - return null; - case '[': - reader.Read (); - return TypeSpecToken.LeftBracket; - case ']': - reader.Read (); - return TypeSpecToken.RightBracket; - case ':': - reader.Read (); - return TypeSpecToken.Colon; - case '.': - reader.Read (); - return TypeSpecToken.Period; - case '&': - reader.Read (); - return TypeSpecToken.Ampersand; - default: - if (Char.IsWhiteSpace (c)) { - reader.Read (); - return null; - } - if (InvalidNameCharacter (c)) { - throw ErrorHelper.CreateError (ReflectorError.kTypeParseBase + 7, $"Unexpected/illegal char {c}"); - } - state = State.InName; - return null; - } - } + TypeSpecToken DoStart() + { + int currentChar = reader.Peek(); + if (currentChar < 0) + return TypeSpecToken.Done; + char c = (char)currentChar; + switch (c) + { + case '(': + reader.Read(); + return TypeSpecToken.LeftParenthesis; + case ')': + reader.Read(); + return TypeSpecToken.RightParenthesis; + case '<': + reader.Read(); + return TypeSpecToken.LeftAngle; + case '>': + reader.Read(); + return TypeSpecToken.RightAngle; + case ',': + reader.Read(); + return TypeSpecToken.Comma; + case '@': + reader.Read(); + return TypeSpecToken.At; + case '?': + reader.Read(); + return TypeSpecToken.QuestionMark; + case '!': + reader.Read(); + return TypeSpecToken.ExclamationPoint; + case '-': + state = State.InArrow; + return null; + case '[': + reader.Read(); + return TypeSpecToken.LeftBracket; + case ']': + reader.Read(); + return TypeSpecToken.RightBracket; + case ':': + reader.Read(); + return TypeSpecToken.Colon; + case '.': + reader.Read(); + return TypeSpecToken.Period; + case '&': + reader.Read(); + return TypeSpecToken.Ampersand; + default: + if (Char.IsWhiteSpace(c)) + { + reader.Read(); + return null; + } + if (InvalidNameCharacter(c)) + { + throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 7, $"Unexpected/illegal char {c}"); + } + state = State.InName; + return null; + } + } - static bool InvalidNameCharacter (char c) - { - return invalidNameChars.IndexOf (c) >= 0; - } - } + static bool InvalidNameCharacter(char c) + { + return invalidNameChars.IndexOf(c) >= 0; + } + } } diff --git a/src/SwiftReflector/TopLevelFunctionCompiler.cs b/src/SwiftReflector/TopLevelFunctionCompiler.cs index 1a22c991008b..aca0ac95a416 100644 --- a/src/SwiftReflector/TopLevelFunctionCompiler.cs +++ b/src/SwiftReflector/TopLevelFunctionCompiler.cs @@ -12,324 +12,368 @@ using SwiftRuntimeLibrary; using SwiftReflector.Demangling; -namespace SwiftReflector { - public class TopLevelFunctionCompiler { - TypeMapper typeMap; - Dictionary mangledToCSharp = new Dictionary (); - - public TopLevelFunctionCompiler (TypeMapper typeMap) - { - this.typeMap = typeMap; - } - - public CSProperty CompileProperty (string propertyName, CSUsingPackages packs, SwiftType swiftPropertyType, bool hasGetter, bool hasSetter, - CSMethodKind methodKind) - { - propertyName = typeMap.SanitizeIdentifier (propertyName); - NetTypeBundle propertyType = typeMap.MapType (swiftPropertyType, false); - - if (!(swiftPropertyType is SwiftGenericArgReferenceType)) - AddUsingBlock (packs, propertyType); - ICodeElement [] uselessLine = new ICodeElement [] { CSReturn.ReturnLine (new CSIdentifier ("useless")) }; - - CSCodeBlock getterBlock = null; - if (hasGetter) - getterBlock = new CSCodeBlock (uselessLine); - CSCodeBlock setterBlock = null; - if (hasSetter) - setterBlock = new CSCodeBlock (uselessLine); - - CSProperty theProp = new CSProperty (propertyType.ToCSType (packs), methodKind, - new CSIdentifier (propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); - if (getterBlock != null) - getterBlock.Clear (); - if (setterBlock != null) - setterBlock.Clear (); - - return theProp; - } - - public CSProperty CompileProperty (CSUsingPackages packs, string propertyName, - FunctionDeclaration getter, FunctionDeclaration setter, CSMethodKind methodKind = CSMethodKind.None) - { - var swiftPropertyType = GetPropertyType (getter, setter); - NetTypeBundle propertyType = null; - if (TypeMapper.IsCompoundProtocolListType (swiftPropertyType)) { - propertyType = new NetTypeBundle ("System", "object", false, false, EntityType.ProtocolList); - } else { - propertyType = typeMap.MapType (getter, swiftPropertyType, false, true); - } - propertyName = propertyName ?? typeMap.SanitizeIdentifier (getter != null ? getter.PropertyName : setter.PropertyName); - bool isSubscript = getter != null ? getter.IsSubscript : - setter.IsSubscript; - - if (!getter.IsTypeSpecGeneric (swiftPropertyType)) - AddUsingBlock (packs, propertyType); - - var uselessLine = new ICodeElement [] { CSReturn.ReturnLine (new CSIdentifier ("useless")) }; - - CSCodeBlock getterBlock = null; - if (getter != null) - getterBlock = new CSCodeBlock (uselessLine); - CSCodeBlock setterBlock = null; - if (setter != null) - setterBlock = new CSCodeBlock (uselessLine); - - CSProperty theProp = null; - var csPropType = propertyType.ToCSType (packs); - if (isSubscript) { - List swiftParms = null; - if (getter != null) { - swiftParms = getter.ParameterLists [1]; - } else { - swiftParms = setter.ParameterLists [1].Skip (1).ToList (); - } - var args = typeMap.MapParameterList (getter, swiftParms, false, false, null, null, packs); - args.ForEach (a => AddUsingBlock (packs, a.Type)); - - var csParams = - new CSParameterList ( - args.Select (a => - new CSParameter (a.Type.ToCSType (packs), - new CSIdentifier (a.Name), a.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null))); - theProp = new CSProperty (csPropType, methodKind, CSVisibility.Public, getterBlock, - CSVisibility.Public, setterBlock, csParams); - - - } else { - theProp = new CSProperty (csPropType, methodKind, - new CSIdentifier (propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); - } - // if (propertyType.Throws) - // DecoratePropWithThrows (theProp, packs); - if (getterBlock != null) - getterBlock.Clear (); - if (setterBlock != null) - setterBlock.Clear (); - - return theProp; - } - - SwiftType GetPropertyType (SwiftPropertyType getter, SwiftPropertyType setter) - { - if (getter != null) { - return getter.ReturnType; - } - if (setter != null) { - if (setter.IsSubscript) { - return ((SwiftTupleType)setter.Parameters).Contents [0]; - } else { - return setter.Parameters; - } - } - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 0, "neither getter nor setter provided"); - } - - TypeSpec GetPropertyType (FunctionDeclaration getter, FunctionDeclaration setter) - { - if (getter != null) { - return getter.ReturnTypeSpec; - } - if (setter != null) { - // same for subscript and prop - return setter.ParameterLists [1] [0].TypeSpec; - } - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 1, "neither getter nor setter provided"); - } - - public CSMethod CompileMethod (FunctionDeclaration func, CSUsingPackages packs, string libraryPath, - string mangledName, string functionName, bool isPinvoke, bool isFinal, bool isStatic) - { - isStatic = isStatic || func.IsExtension; - var extraProtoArgs = new CSGenericTypeDeclarationCollection (); - var extraProtoConstraints = new CSGenericConstraintCollection (); - var args = typeMap.MapParameterList (func, func.ParameterLists.Last (), isPinvoke, false, extraProtoArgs, extraProtoConstraints, packs); - if (isPinvoke && func.ParameterLists.Count > 1) { - var metaTypeBundle = new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, false, EntityType.None); - NetParam p = new NetParam ("metaClass", metaTypeBundle); - args.Add (p); - } - - NetTypeBundle returnType = null; - if (func.ReturnTypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) { - returnType = new NetTypeBundle ("System", "object", false, false, EntityType.ProtocolList); - } else { - returnType = typeMap.MapType (func, func.ReturnTypeSpec, isPinvoke, true); - } - - string funcName = functionName ?? typeMap.SanitizeIdentifier (func.Name); - - if (isPinvoke && !mangledToCSharp.ContainsKey (mangledName)) - mangledToCSharp.Add (mangledName, funcName); - - args.ForEach (a => AddUsingBlock (packs, a.Type)); - - if (returnType != null && !(func.IsTypeSpecGeneric (func.ReturnTypeSpec))) - AddUsingBlock (packs, returnType); - - CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType (packs); - - var csParams = new CSParameterList (); - foreach (var arg in args) { - var csType = arg.Type.ToCSType (packs); - // if (arg.Type.Throws) - // csType = DecorateTypeWithThrows (csType, packs); - csParams.Add (new CSParameter (csType, new CSIdentifier (arg.Name), - arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)); - - } - - if (isPinvoke) { - // AddExtraGenericArguments (func, csParams, packs); - var pinvoke = CSMethod.InternalPInvoke (csReturnType, funcName, libraryPath, - mangledName.Substring (1), csParams); - if (csReturnType is CSSimpleType simple && simple.Name == "bool") { - CSAttribute.ReturnMarshalAsI1.AttachBefore (pinvoke); - } - return pinvoke; - } else { - CSMethod retval = null; - if (func.IsConstructor) { - retval = CSMethod.PublicConstructor (funcName, csParams, new CSCodeBlock ()); - } else { - if (isFinal) - retval = new CSMethod (CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.None, csReturnType, new CSIdentifier (funcName), - csParams, new CSCodeBlock ()); - else - retval = new CSMethod (CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.Virtual, csReturnType, new CSIdentifier (funcName), - csParams, new CSCodeBlock ()); - } - if (extraProtoArgs.Count > 0) { - retval.GenericParameters.AddRange (extraProtoArgs); - retval.GenericConstraints.AddRange (extraProtoConstraints); - } - return retval; - } - } - - public static bool GenericArgumentIsReferencedByGenericClassInParameterList (SwiftBaseFunctionType func, GenericArgument arg) - { - foreach (SwiftType st in func.EachParameter) { - if (st is SwiftUnboundGenericType) { - var sut = (SwiftUnboundGenericType)st; - if (!sut.DependentType.IsClass) - continue; - // there appears to be a bug in the swift compiler that doesn't accept certain - // generic patterns that will ensure that sut.Arguments won't ever have more than 1 - // element in it in cases that we care about, but what the heck - do the general case. - foreach (GenericArgument gen in sut.Arguments) { - if (gen.Depth == arg.Depth && gen.Index == arg.Index) - return true; - } - } - } - return false; - } - - public static bool GenericDeclarationIsReferencedByGenericClassInParameterList (FunctionDeclaration func, GenericDeclaration genDecl, TypeMapper mapper) - { - foreach (ParameterItem pi in func.ParameterLists.Last ()) { - if (pi.TypeSpec is NamedTypeSpec) { - // this inner section should probably be recursive, but I was unable to - // even test if SomeClass> is valid because the swift compiler - // wouldn't take it. - var ns = (NamedTypeSpec)pi.TypeSpec; - if (ns.ContainsGenericParameters) { - Entity en = mapper.GetEntityForTypeSpec (ns); - if (en != null && en.EntityType == EntityType.Class) { - foreach (TypeSpec genTS in ns.GenericParameters) { - var nsGen = genTS as NamedTypeSpec; - if (nsGen != null) { - if (genDecl.Name == nsGen.Name) - return true; - } - } - } - } - } - } - return false; - } - - public string CSMethodForMangledName (string mangledName) - { - return mangledToCSharp [SwiftRuntimeLibrary.Exceptions.ThrowOnNull (mangledName, "mangledName")]; - } - - static void AddUsingBlock (CSUsingPackages packs, NetTypeBundle type) - { - if (type.IsVoid || String.IsNullOrEmpty (type.NameSpace)) - return; - packs.AddIfNotPresent (type.NameSpace); - } - - - int TotalProtocolConstraints (GenericArgument gen) - { - int count = 0; - foreach (var constraint in gen.Constraints) { - var ct = constraint as SwiftClassType; - if (ct == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 11, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); - if (ct.EntityKind == MemberNesting.Protocol) - count++; - } - return count; - } - int TotalProtocolConstraints (GenericDeclaration gen) - { - int count = 0; - foreach (BaseConstraint constraint in gen.Constraints) { - var inh = constraint as InheritanceConstraint; - if (inh == null) - continue; - // throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 12, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); - var en = typeMap.GetEntityForTypeSpec (inh.InheritsTypeSpec); - if (en.EntityType == EntityType.Protocol) - count++; - } - return count; - } - - bool IsObjCStruct (NetParam ntb, SwiftType parmType) - { - if (ntb.Type.Entity != EntityType.Struct) - return false; - - // if the Entity is EntityType.Struct, it's guaranteed to be a SwiftClassType - var structType = parmType as SwiftClassType; - var entity = typeMap.GetEntityForSwiftClassName (structType.ClassName.ToFullyQualifiedName (true)); - if (entity == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 5, $"Unable to get the entity for struct type {structType.ClassName.ToFullyQualifiedName (true)}"); - return entity.Type.IsObjC; - } - - bool IsObjCStruct (TypeSpec typeSpec) - { - if (!(typeSpec is NamedTypeSpec)) - return false; - var entity = typeMap.GetEntityForTypeSpec (typeSpec); - if (entity == null) - throw ErrorHelper.CreateError (ReflectorError.kCompilerReferenceBase + 6, $"Unable to get the entity for type {typeSpec.ToString ()}"); - return entity.IsObjCStruct; - } - - void RemapSwiftClosureRepresensation (List args) - { - for (int i = 0; i < args.Count; i++) { - if (args[i].Type.FullName == "SwiftRuntimeLibrary.SwiftClosureRepresentation") { - var bundle = new NetTypeBundle ("SwiftRuntimeLibrary", "BlindSwiftClosureRepresentation", false, args [i].Type.IsReference, EntityType.Closure); - args [i] = new NetParam (args [i].Name, bundle); - } - } - } - - public static bool TypeSpecCanThrow (TypeSpec t, bool isPinvoke) - { - if (t == null) - return false; - return !isPinvoke && t is ClosureTypeSpec cl && cl.Throws; - } - } +namespace SwiftReflector +{ + public class TopLevelFunctionCompiler + { + TypeMapper typeMap; + Dictionary mangledToCSharp = new Dictionary(); + + public TopLevelFunctionCompiler(TypeMapper typeMap) + { + this.typeMap = typeMap; + } + + public CSProperty CompileProperty(string propertyName, CSUsingPackages packs, SwiftType swiftPropertyType, bool hasGetter, bool hasSetter, + CSMethodKind methodKind) + { + propertyName = typeMap.SanitizeIdentifier(propertyName); + NetTypeBundle propertyType = typeMap.MapType(swiftPropertyType, false); + + if (!(swiftPropertyType is SwiftGenericArgReferenceType)) + AddUsingBlock(packs, propertyType); + ICodeElement[] uselessLine = new ICodeElement[] { CSReturn.ReturnLine(new CSIdentifier("useless")) }; + + CSCodeBlock getterBlock = null; + if (hasGetter) + getterBlock = new CSCodeBlock(uselessLine); + CSCodeBlock setterBlock = null; + if (hasSetter) + setterBlock = new CSCodeBlock(uselessLine); + + CSProperty theProp = new CSProperty(propertyType.ToCSType(packs), methodKind, + new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); + if (getterBlock != null) + getterBlock.Clear(); + if (setterBlock != null) + setterBlock.Clear(); + + return theProp; + } + + public CSProperty CompileProperty(CSUsingPackages packs, string propertyName, + FunctionDeclaration getter, FunctionDeclaration setter, CSMethodKind methodKind = CSMethodKind.None) + { + var swiftPropertyType = GetPropertyType(getter, setter); + NetTypeBundle propertyType = null; + if (TypeMapper.IsCompoundProtocolListType(swiftPropertyType)) + { + propertyType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList); + } + else + { + propertyType = typeMap.MapType(getter, swiftPropertyType, false, true); + } + propertyName = propertyName ?? typeMap.SanitizeIdentifier(getter != null ? getter.PropertyName : setter.PropertyName); + bool isSubscript = getter != null ? getter.IsSubscript : + setter.IsSubscript; + + if (!getter.IsTypeSpecGeneric(swiftPropertyType)) + AddUsingBlock(packs, propertyType); + + var uselessLine = new ICodeElement[] { CSReturn.ReturnLine(new CSIdentifier("useless")) }; + + CSCodeBlock getterBlock = null; + if (getter != null) + getterBlock = new CSCodeBlock(uselessLine); + CSCodeBlock setterBlock = null; + if (setter != null) + setterBlock = new CSCodeBlock(uselessLine); + + CSProperty theProp = null; + var csPropType = propertyType.ToCSType(packs); + if (isSubscript) + { + List swiftParms = null; + if (getter != null) + { + swiftParms = getter.ParameterLists[1]; + } + else + { + swiftParms = setter.ParameterLists[1].Skip(1).ToList(); + } + var args = typeMap.MapParameterList(getter, swiftParms, false, false, null, null, packs); + args.ForEach(a => AddUsingBlock(packs, a.Type)); + + var csParams = + new CSParameterList( + args.Select(a => + new CSParameter(a.Type.ToCSType(packs), + new CSIdentifier(a.Name), a.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null))); + theProp = new CSProperty(csPropType, methodKind, CSVisibility.Public, getterBlock, + CSVisibility.Public, setterBlock, csParams); + + + } + else + { + theProp = new CSProperty(csPropType, methodKind, + new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); + } + // if (propertyType.Throws) + // DecoratePropWithThrows (theProp, packs); + if (getterBlock != null) + getterBlock.Clear(); + if (setterBlock != null) + setterBlock.Clear(); + + return theProp; + } + + SwiftType GetPropertyType(SwiftPropertyType getter, SwiftPropertyType setter) + { + if (getter != null) + { + return getter.ReturnType; + } + if (setter != null) + { + if (setter.IsSubscript) + { + return ((SwiftTupleType)setter.Parameters).Contents[0]; + } + else + { + return setter.Parameters; + } + } + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 0, "neither getter nor setter provided"); + } + + TypeSpec GetPropertyType(FunctionDeclaration getter, FunctionDeclaration setter) + { + if (getter != null) + { + return getter.ReturnTypeSpec; + } + if (setter != null) + { + // same for subscript and prop + return setter.ParameterLists[1][0].TypeSpec; + } + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 1, "neither getter nor setter provided"); + } + + public CSMethod CompileMethod(FunctionDeclaration func, CSUsingPackages packs, string libraryPath, + string mangledName, string functionName, bool isPinvoke, bool isFinal, bool isStatic) + { + isStatic = isStatic || func.IsExtension; + var extraProtoArgs = new CSGenericTypeDeclarationCollection(); + var extraProtoConstraints = new CSGenericConstraintCollection(); + var args = typeMap.MapParameterList(func, func.ParameterLists.Last(), isPinvoke, false, extraProtoArgs, extraProtoConstraints, packs); + if (isPinvoke && func.ParameterLists.Count > 1) + { + var metaTypeBundle = new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, false, EntityType.None); + NetParam p = new NetParam("metaClass", metaTypeBundle); + args.Add(p); + } + + NetTypeBundle returnType = null; + if (func.ReturnTypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) + { + returnType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList); + } + else + { + returnType = typeMap.MapType(func, func.ReturnTypeSpec, isPinvoke, true); + } + + string funcName = functionName ?? typeMap.SanitizeIdentifier(func.Name); + + if (isPinvoke && !mangledToCSharp.ContainsKey(mangledName)) + mangledToCSharp.Add(mangledName, funcName); + + args.ForEach(a => AddUsingBlock(packs, a.Type)); + + if (returnType != null && !(func.IsTypeSpecGeneric(func.ReturnTypeSpec))) + AddUsingBlock(packs, returnType); + + CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType(packs); + + var csParams = new CSParameterList(); + foreach (var arg in args) + { + var csType = arg.Type.ToCSType(packs); + // if (arg.Type.Throws) + // csType = DecorateTypeWithThrows (csType, packs); + csParams.Add(new CSParameter(csType, new CSIdentifier(arg.Name), + arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)); + + } + + if (isPinvoke) + { + // AddExtraGenericArguments (func, csParams, packs); + var pinvoke = CSMethod.InternalPInvoke(csReturnType, funcName, libraryPath, + mangledName.Substring(1), csParams); + if (csReturnType is CSSimpleType simple && simple.Name == "bool") + { + CSAttribute.ReturnMarshalAsI1.AttachBefore(pinvoke); + } + return pinvoke; + } + else + { + CSMethod retval = null; + if (func.IsConstructor) + { + retval = CSMethod.PublicConstructor(funcName, csParams, new CSCodeBlock()); + } + else + { + if (isFinal) + retval = new CSMethod(CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.None, csReturnType, new CSIdentifier(funcName), + csParams, new CSCodeBlock()); + else + retval = new CSMethod(CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.Virtual, csReturnType, new CSIdentifier(funcName), + csParams, new CSCodeBlock()); + } + if (extraProtoArgs.Count > 0) + { + retval.GenericParameters.AddRange(extraProtoArgs); + retval.GenericConstraints.AddRange(extraProtoConstraints); + } + return retval; + } + } + + public static bool GenericArgumentIsReferencedByGenericClassInParameterList(SwiftBaseFunctionType func, GenericArgument arg) + { + foreach (SwiftType st in func.EachParameter) + { + if (st is SwiftUnboundGenericType) + { + var sut = (SwiftUnboundGenericType)st; + if (!sut.DependentType.IsClass) + continue; + // there appears to be a bug in the swift compiler that doesn't accept certain + // generic patterns that will ensure that sut.Arguments won't ever have more than 1 + // element in it in cases that we care about, but what the heck - do the general case. + foreach (GenericArgument gen in sut.Arguments) + { + if (gen.Depth == arg.Depth && gen.Index == arg.Index) + return true; + } + } + } + return false; + } + + public static bool GenericDeclarationIsReferencedByGenericClassInParameterList(FunctionDeclaration func, GenericDeclaration genDecl, TypeMapper mapper) + { + foreach (ParameterItem pi in func.ParameterLists.Last()) + { + if (pi.TypeSpec is NamedTypeSpec) + { + // this inner section should probably be recursive, but I was unable to + // even test if SomeClass> is valid because the swift compiler + // wouldn't take it. + var ns = (NamedTypeSpec)pi.TypeSpec; + if (ns.ContainsGenericParameters) + { + Entity en = mapper.GetEntityForTypeSpec(ns); + if (en != null && en.EntityType == EntityType.Class) + { + foreach (TypeSpec genTS in ns.GenericParameters) + { + var nsGen = genTS as NamedTypeSpec; + if (nsGen != null) + { + if (genDecl.Name == nsGen.Name) + return true; + } + } + } + } + } + } + return false; + } + + public string CSMethodForMangledName(string mangledName) + { + return mangledToCSharp[SwiftRuntimeLibrary.Exceptions.ThrowOnNull(mangledName, "mangledName")]; + } + + static void AddUsingBlock(CSUsingPackages packs, NetTypeBundle type) + { + if (type.IsVoid || String.IsNullOrEmpty(type.NameSpace)) + return; + packs.AddIfNotPresent(type.NameSpace); + } + + + int TotalProtocolConstraints(GenericArgument gen) + { + int count = 0; + foreach (var constraint in gen.Constraints) + { + var ct = constraint as SwiftClassType; + if (ct == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 11, $"Expected a SwiftClassType for constraint, but got {constraint.GetType().Name}."); + if (ct.EntityKind == MemberNesting.Protocol) + count++; + } + return count; + } + int TotalProtocolConstraints(GenericDeclaration gen) + { + int count = 0; + foreach (BaseConstraint constraint in gen.Constraints) + { + var inh = constraint as InheritanceConstraint; + if (inh == null) + continue; + // throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 12, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); + var en = typeMap.GetEntityForTypeSpec(inh.InheritsTypeSpec); + if (en.EntityType == EntityType.Protocol) + count++; + } + return count; + } + + bool IsObjCStruct(NetParam ntb, SwiftType parmType) + { + if (ntb.Type.Entity != EntityType.Struct) + return false; + + // if the Entity is EntityType.Struct, it's guaranteed to be a SwiftClassType + var structType = parmType as SwiftClassType; + var entity = typeMap.GetEntityForSwiftClassName(structType.ClassName.ToFullyQualifiedName(true)); + if (entity == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 5, $"Unable to get the entity for struct type {structType.ClassName.ToFullyQualifiedName(true)}"); + return entity.Type.IsObjC; + } + + bool IsObjCStruct(TypeSpec typeSpec) + { + if (!(typeSpec is NamedTypeSpec)) + return false; + var entity = typeMap.GetEntityForTypeSpec(typeSpec); + if (entity == null) + throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 6, $"Unable to get the entity for type {typeSpec.ToString()}"); + return entity.IsObjCStruct; + } + + void RemapSwiftClosureRepresensation(List args) + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type.FullName == "SwiftRuntimeLibrary.SwiftClosureRepresentation") + { + var bundle = new NetTypeBundle("SwiftRuntimeLibrary", "BlindSwiftClosureRepresentation", false, args[i].Type.IsReference, EntityType.Closure); + args[i] = new NetParam(args[i].Name, bundle); + } + } + } + + public static bool TypeSpecCanThrow(TypeSpec t, bool isPinvoke) + { + if (t == null) + return false; + return !isPinvoke && t is ClosureTypeSpec cl && cl.Throws; + } + } } diff --git a/src/SwiftReflector/TypeMapping/Entity.cs b/src/SwiftReflector/TypeMapping/Entity.cs index 8b0db5fa074b..e345a52574a4 100644 --- a/src/SwiftReflector/TypeMapping/Entity.cs +++ b/src/SwiftReflector/TypeMapping/Entity.cs @@ -6,76 +6,90 @@ using SwiftReflector.IOUtils; using System.Xml.Linq; -namespace SwiftReflector.TypeMapping { - public class Entity : IXElementConvertible { - public Entity () - { - } +namespace SwiftReflector.TypeMapping +{ + public class Entity : IXElementConvertible + { + public Entity() + { + } - public string SharpNamespace { get; set; } - public string SharpTypeName { get; set; } - public EntityType EntityType { get; set; } - public string ProtocolProxyModule { get; set; } - public bool IsDiscretionaryConstraint { get; set; } + public string SharpNamespace { get; set; } + public string SharpTypeName { get; set; } + public EntityType EntityType { get; set; } + public string ProtocolProxyModule { get; set; } + public bool IsDiscretionaryConstraint { get; set; } - public TypeDeclaration Type { get; set; } + public TypeDeclaration Type { get; set; } - public DotNetName GetFullType () - { - return new DotNetName (SharpNamespace, SharpTypeName); - } + public DotNetName GetFullType() + { + return new DotNetName(SharpNamespace, SharpTypeName); + } - public bool IsStructOrEnum { - get { - return EntityType == EntityType.Struct || EntityType == EntityType.Enum || - EntityType == EntityType.TrivialEnum; - } - } + public bool IsStructOrEnum + { + get + { + return EntityType == EntityType.Struct || EntityType == EntityType.Enum || + EntityType == EntityType.TrivialEnum; + } + } - public bool IsStructClassOrEnum { - get { - return IsStructOrEnum || EntityType == EntityType.Class; - } - } + public bool IsStructClassOrEnum + { + get + { + return IsStructOrEnum || EntityType == EntityType.Class; + } + } - public bool IsObjCClass { - get { - return EntityType == EntityType.Class && (Type != null && Type.IsObjC); - } - } + public bool IsObjCClass + { + get + { + return EntityType == EntityType.Class && (Type != null && Type.IsObjC); + } + } - public bool IsObjCStruct { - get { - return EntityType == EntityType.Struct && (Type != null && Type.IsObjC); - } - } + public bool IsObjCStruct + { + get + { + return EntityType == EntityType.Struct && (Type != null && Type.IsObjC); + } + } - public bool IsObjCEnum { - get { - return EntityType == EntityType.Enum && (Type != null && Type.IsObjC); - } - } + public bool IsObjCEnum + { + get + { + return EntityType == EntityType.Enum && (Type != null && Type.IsObjC); + } + } - public bool IsObjCProtocol { - get { - return EntityType == EntityType.Protocol && (Type != null && Type.IsObjC); - } - } + public bool IsObjCProtocol + { + get + { + return EntityType == EntityType.Protocol && (Type != null && Type.IsObjC); + } + } - #region IXElementConvertible implementation + #region IXElementConvertible implementation - public XElement ToXElement () - { - return new XElement ("entity", - new XAttribute ("sharpNameSpace", SharpNamespace), - new XAttribute ("sharpTypeName", SharpTypeName), - new XAttribute ("entityType", EntityType), - new XAttribute ("protocolProxyModule", ProtocolProxyModule ?? ""), - new XAttribute ("discretionaryConstraint", IsDiscretionaryConstraint ? "true" : "false"), - Type.ToXElement ()); - } + public XElement ToXElement() + { + return new XElement("entity", + new XAttribute("sharpNameSpace", SharpNamespace), + new XAttribute("sharpTypeName", SharpTypeName), + new XAttribute("entityType", EntityType), + new XAttribute("protocolProxyModule", ProtocolProxyModule ?? ""), + new XAttribute("discretionaryConstraint", IsDiscretionaryConstraint ? "true" : "false"), + Type.ToXElement()); + } - #endregion - } + #endregion + } } diff --git a/src/SwiftReflector/TypeMapping/ModuleDatabase.cs b/src/SwiftReflector/TypeMapping/ModuleDatabase.cs index bf16577c26e9..4f3f54c68aad 100644 --- a/src/SwiftReflector/TypeMapping/ModuleDatabase.cs +++ b/src/SwiftReflector/TypeMapping/ModuleDatabase.cs @@ -5,15 +5,17 @@ using System.Collections.Generic; using SwiftReflector.SwiftXmlReflection; -namespace SwiftReflector.TypeMapping { - public class ModuleDatabase : Dictionary{ - public ModuleDatabase () - { - Operators = new List (); - TypeAliases = new List (); - } +namespace SwiftReflector.TypeMapping +{ + public class ModuleDatabase : Dictionary + { + public ModuleDatabase() + { + Operators = new List(); + TypeAliases = new List(); + } - public List Operators { get; private set; } - public List TypeAliases { get; private set; } - } + public List Operators { get; private set; } + public List TypeAliases { get; private set; } + } } diff --git a/src/SwiftReflector/TypeMapping/NetParam.cs b/src/SwiftReflector/TypeMapping/NetParam.cs index 7b3dc2e3285b..ecb7108dbd91 100644 --- a/src/SwiftReflector/TypeMapping/NetParam.cs +++ b/src/SwiftReflector/TypeMapping/NetParam.cs @@ -3,16 +3,18 @@ using SwiftRuntimeLibrary; -namespace SwiftReflector.TypeMapping { - public class NetParam { - public NetParam (string name, NetTypeBundle bundle) - { - Name = Exceptions.ThrowOnNull (name, "name"); - Type = bundle; - } - public string Name { get; private set; } - public NetTypeBundle Type { get; private set; } - } +namespace SwiftReflector.TypeMapping +{ + public class NetParam + { + public NetParam(string name, NetTypeBundle bundle) + { + Name = Exceptions.ThrowOnNull(name, "name"); + Type = bundle; + } + public string Name { get; private set; } + public NetTypeBundle Type { get; private set; } + } } diff --git a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs index 5578639f45b3..b1ca1c124732 100644 --- a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs +++ b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs @@ -9,211 +9,228 @@ using SwiftReflector.SwiftXmlReflection; using SwiftRuntimeLibrary; -namespace SwiftReflector.TypeMapping { - public class NetTypeBundle { - const string kNoType = "!!NO_TYPE!!"; - List genericTypes = new List (); - - public NetTypeBundle (string nameSpace, string entityName, bool isScalar, bool isReference, EntityType entity, - bool swiftThrows = false) - { - GenericIndex = -1; - IsVoid = entityName == kNoType; - Type = entityName; - NameSpace = nameSpace; - - FullName = String.IsNullOrEmpty (nameSpace) ? entityName : nameSpace + "." + entityName; - IsScalar = isScalar; - IsReference = isReference; - Entity = entity; - Throws = swiftThrows; - } - - public NetTypeBundle (List tupleElements, bool isReference) - { - GenericIndex = -1; - string netTypeName = ToTupleName (tupleElements); - FullName = "System." + netTypeName; - Type = netTypeName; - NameSpace = "System"; - - IsScalar = false; - IsReference = isReference; - Entity = EntityType.Tuple; - TupleTypes.AddRange (Exceptions.ThrowOnNull (tupleElements, "tupleElements")); - } - - public NetTypeBundle (string nameSpace, string entityName, EntityType entity, bool isReference, IEnumerable genericTypes, - bool swiftThrows = false) - : this (nameSpace, entityName, false, isReference, entity) - { - GenericIndex = -1; - this.genericTypes.AddRange (genericTypes); - if (this.genericTypes.Count == 0) - throw new ArgumentOutOfRangeException (nameof (genericTypes), "Generic NetBundle constructor needs actual generic types."); - Throws = swiftThrows; - } - - public NetTypeBundle (int depth, int index) - { - if (depth < 0) - throw new ArgumentOutOfRangeException (nameof (depth)); - if (index < 0) - throw new ArgumentOutOfRangeException (nameof (index)); - GenericDepth = depth; - GenericIndex = index; - } - - public NetTypeBundle (ProtocolDeclaration proto, AssociatedTypeDeclaration assoc, bool isReference) - { - GenericIndex = -1; - AssociatedTypeProtocol = proto; - AssociatedType = assoc; - // Type = OverrideBuilder.GenericAssociatedTypeName (assoc); - FullName = Type; - NameSpace = String.Empty; - IsReference = isReference; - } - - public NetTypeBundle (string selfRepresentation, bool isReference) - { - GenericIndex = -1; - Type = FullName = Exceptions.ThrowOnNull (selfRepresentation, nameof (selfRepresentation)); - NameSpace = String.Empty; - IsReference = isReference; - IsSelf = true; - } - - static NetTypeBundle ntbVoid = new NetTypeBundle ("", kNoType, false, false, EntityType.None); - - public static NetTypeBundle Void { get { return ntbVoid; } } - - static NetTypeBundle ntbIntPtr = new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - public static NetTypeBundle IntPtr { - get { - return ntbIntPtr; - } - } - - public bool IsSelf { get; private set; } - public bool IsVoid { get; private set; } - public string Type { get; private set; } - public string NameSpace { get; private set; } - public string FullName { get; private set; } - public bool IsScalar { get; private set; } - public bool IsReference { get; private set; } - public EntityType Entity { get; private set; } - public List TupleTypes { get { return genericTypes; } } - public NetTypeBundle OptionalType { get { return genericTypes [0]; } } - public List GenericTypes { get { return genericTypes; } } - public int GenericDepth { get; private set; } - public int GenericIndex { get; private set; } - public bool IsGenericReference { get { return GenericIndex >= 0; } } - public ProtocolDeclaration AssociatedTypeProtocol { get; private set; } - public AssociatedTypeDeclaration AssociatedType { get; private set; } - public bool IsAssociatedType { get { return AssociatedTypeProtocol != null; } } - public bool Throws { get; private set; } - public bool ContainsGenericParts { - get { - return genericTypes.Count > 0; - } - } - public List GenericConstraints { - get { - return IsGenericReference ? GenericTypes : null; - } - } - - public override string ToString () - { - return FullName; - } - - public override bool Equals (object obj) - { - NetTypeBundle other = obj as NetTypeBundle; - if (other == null) - return false; - return FullName == other.FullName; - } - - public override int GetHashCode () - { - return FullName.GetHashCode (); - } - - static string ToTupleName (IEnumerable types) - { - StringBuilder sb = new StringBuilder (); - bool first = true; - sb.Append ("Tuple<"); - foreach (NetTypeBundle t in types) { - if (!first) { - sb.Append (", "); - } - first = false; - sb.Append (t.FullName); - } - return sb.Append (">").ToString (); - } - - static string ToOptionalName (NetTypeBundle optType) - { - StringBuilder sb = new StringBuilder (); - sb.Append ("SwiftOptional<").Append (optType.FullName).Append (">"); - return sb.ToString (); - } - - - static IEnumerable ToCSSimpleType (IEnumerable ntbs, CSUsingPackages use) - { - return ntbs.Select (ntb => ToCSSimpleType (ntb, use)); - } - - public static CSType ToCSSimpleType(NetTypeBundle ntb, CSUsingPackages use) - { - if (!String.IsNullOrEmpty (ntb.NameSpace)) - use.AddIfNotPresent (ntb.NameSpace); - return ntb.Entity == EntityType.Tuple ? ToCSTuple (ntb.TupleTypes, use) : ntb.ToCSType (use); - } - - public static CSSimpleType ToCSOptional (NetTypeBundle optType, CSUsingPackages use) - { - // use.AddIfNotPresent (typeof (SwiftOptional<>)); - // return new CSSimpleType ("SwiftOptional", false, optType.ToCSType (use)); - throw new Exception(); - } - - public static CSSimpleType ToCSTuple (IList innerTypes, CSUsingPackages use) - { - if (innerTypes.Count <= 7) { - return new CSSimpleType ("Tuple", false, ToCSSimpleType (innerTypes, use).ToArray ()); - } else { - IEnumerable head = ToCSSimpleType (innerTypes.Take (7), use); - CSType tail = ToCSTuple (innerTypes.Skip (7).ToList (), use); - return new CSSimpleType ("Tuple", false, Enumerable.Concat (head, Enumerable.Repeat (tail, 1)).ToArray ()); - } - } - - public CSType ToCSType (CSUsingPackages use) - { - if (!String.IsNullOrEmpty (NameSpace)) - use.AddIfNotPresent (NameSpace); - if (IsGenericReference) { - CSGenericReferenceType genref = new CSGenericReferenceType (GenericDepth, GenericIndex); - if (this.GenericConstraints.Count > 0) { - genref.InterfaceConstraints.AddRange (this.GenericConstraints.Select (ntb => ntb.ToCSType (use))); - } - return genref; - } else if (IsAssociatedType || IsSelf) { - return new CSSimpleType (Type, false); - } - - return Entity == EntityType.Tuple ? ToCSTuple (TupleTypes, use) : - new CSSimpleType (Type, false, GenericTypes.Select (ntb => ntb.ToCSType (use)).ToArray ()); - } - - - } +namespace SwiftReflector.TypeMapping +{ + public class NetTypeBundle + { + const string kNoType = "!!NO_TYPE!!"; + List genericTypes = new List(); + + public NetTypeBundle(string nameSpace, string entityName, bool isScalar, bool isReference, EntityType entity, + bool swiftThrows = false) + { + GenericIndex = -1; + IsVoid = entityName == kNoType; + Type = entityName; + NameSpace = nameSpace; + + FullName = String.IsNullOrEmpty(nameSpace) ? entityName : nameSpace + "." + entityName; + IsScalar = isScalar; + IsReference = isReference; + Entity = entity; + Throws = swiftThrows; + } + + public NetTypeBundle(List tupleElements, bool isReference) + { + GenericIndex = -1; + string netTypeName = ToTupleName(tupleElements); + FullName = "System." + netTypeName; + Type = netTypeName; + NameSpace = "System"; + + IsScalar = false; + IsReference = isReference; + Entity = EntityType.Tuple; + TupleTypes.AddRange(Exceptions.ThrowOnNull(tupleElements, "tupleElements")); + } + + public NetTypeBundle(string nameSpace, string entityName, EntityType entity, bool isReference, IEnumerable genericTypes, + bool swiftThrows = false) + : this(nameSpace, entityName, false, isReference, entity) + { + GenericIndex = -1; + this.genericTypes.AddRange(genericTypes); + if (this.genericTypes.Count == 0) + throw new ArgumentOutOfRangeException(nameof(genericTypes), "Generic NetBundle constructor needs actual generic types."); + Throws = swiftThrows; + } + + public NetTypeBundle(int depth, int index) + { + if (depth < 0) + throw new ArgumentOutOfRangeException(nameof(depth)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + GenericDepth = depth; + GenericIndex = index; + } + + public NetTypeBundle(ProtocolDeclaration proto, AssociatedTypeDeclaration assoc, bool isReference) + { + GenericIndex = -1; + AssociatedTypeProtocol = proto; + AssociatedType = assoc; + // Type = OverrideBuilder.GenericAssociatedTypeName (assoc); + FullName = Type; + NameSpace = String.Empty; + IsReference = isReference; + } + + public NetTypeBundle(string selfRepresentation, bool isReference) + { + GenericIndex = -1; + Type = FullName = Exceptions.ThrowOnNull(selfRepresentation, nameof(selfRepresentation)); + NameSpace = String.Empty; + IsReference = isReference; + IsSelf = true; + } + + static NetTypeBundle ntbVoid = new NetTypeBundle("", kNoType, false, false, EntityType.None); + + public static NetTypeBundle Void { get { return ntbVoid; } } + + static NetTypeBundle ntbIntPtr = new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + public static NetTypeBundle IntPtr + { + get + { + return ntbIntPtr; + } + } + + public bool IsSelf { get; private set; } + public bool IsVoid { get; private set; } + public string Type { get; private set; } + public string NameSpace { get; private set; } + public string FullName { get; private set; } + public bool IsScalar { get; private set; } + public bool IsReference { get; private set; } + public EntityType Entity { get; private set; } + public List TupleTypes { get { return genericTypes; } } + public NetTypeBundle OptionalType { get { return genericTypes[0]; } } + public List GenericTypes { get { return genericTypes; } } + public int GenericDepth { get; private set; } + public int GenericIndex { get; private set; } + public bool IsGenericReference { get { return GenericIndex >= 0; } } + public ProtocolDeclaration AssociatedTypeProtocol { get; private set; } + public AssociatedTypeDeclaration AssociatedType { get; private set; } + public bool IsAssociatedType { get { return AssociatedTypeProtocol != null; } } + public bool Throws { get; private set; } + public bool ContainsGenericParts + { + get + { + return genericTypes.Count > 0; + } + } + public List GenericConstraints + { + get + { + return IsGenericReference ? GenericTypes : null; + } + } + + public override string ToString() + { + return FullName; + } + + public override bool Equals(object obj) + { + NetTypeBundle other = obj as NetTypeBundle; + if (other == null) + return false; + return FullName == other.FullName; + } + + public override int GetHashCode() + { + return FullName.GetHashCode(); + } + + static string ToTupleName(IEnumerable types) + { + StringBuilder sb = new StringBuilder(); + bool first = true; + sb.Append("Tuple<"); + foreach (NetTypeBundle t in types) + { + if (!first) + { + sb.Append(", "); + } + first = false; + sb.Append(t.FullName); + } + return sb.Append(">").ToString(); + } + + static string ToOptionalName(NetTypeBundle optType) + { + StringBuilder sb = new StringBuilder(); + sb.Append("SwiftOptional<").Append(optType.FullName).Append(">"); + return sb.ToString(); + } + + + static IEnumerable ToCSSimpleType(IEnumerable ntbs, CSUsingPackages use) + { + return ntbs.Select(ntb => ToCSSimpleType(ntb, use)); + } + + public static CSType ToCSSimpleType(NetTypeBundle ntb, CSUsingPackages use) + { + if (!String.IsNullOrEmpty(ntb.NameSpace)) + use.AddIfNotPresent(ntb.NameSpace); + return ntb.Entity == EntityType.Tuple ? ToCSTuple(ntb.TupleTypes, use) : ntb.ToCSType(use); + } + + public static CSSimpleType ToCSOptional(NetTypeBundle optType, CSUsingPackages use) + { + // use.AddIfNotPresent (typeof (SwiftOptional<>)); + // return new CSSimpleType ("SwiftOptional", false, optType.ToCSType (use)); + throw new Exception(); + } + + public static CSSimpleType ToCSTuple(IList innerTypes, CSUsingPackages use) + { + if (innerTypes.Count <= 7) + { + return new CSSimpleType("Tuple", false, ToCSSimpleType(innerTypes, use).ToArray()); + } + else + { + IEnumerable head = ToCSSimpleType(innerTypes.Take(7), use); + CSType tail = ToCSTuple(innerTypes.Skip(7).ToList(), use); + return new CSSimpleType("Tuple", false, Enumerable.Concat(head, Enumerable.Repeat(tail, 1)).ToArray()); + } + } + + public CSType ToCSType(CSUsingPackages use) + { + if (!String.IsNullOrEmpty(NameSpace)) + use.AddIfNotPresent(NameSpace); + if (IsGenericReference) + { + CSGenericReferenceType genref = new CSGenericReferenceType(GenericDepth, GenericIndex); + if (this.GenericConstraints.Count > 0) + { + genref.InterfaceConstraints.AddRange(this.GenericConstraints.Select(ntb => ntb.ToCSType(use))); + } + return genref; + } + else if (IsAssociatedType || IsSelf) + { + return new CSSimpleType(Type, false); + } + + return Entity == EntityType.Tuple ? ToCSTuple(TupleTypes, use) : + new CSSimpleType(Type, false, GenericTypes.Select(ntb => ntb.ToCSType(use)).ToArray()); + } + + + } } diff --git a/src/SwiftReflector/TypeMapping/TypeDatabase.cs b/src/SwiftReflector/TypeMapping/TypeDatabase.cs index 4f4bc24e021d..b06d8f4da621 100644 --- a/src/SwiftReflector/TypeMapping/TypeDatabase.cs +++ b/src/SwiftReflector/TypeMapping/TypeDatabase.cs @@ -10,462 +10,506 @@ using SwiftReflector.ExceptionTools; using SwiftRuntimeLibrary; -namespace SwiftReflector.TypeMapping { - public class DotNetName - { - public readonly string Namespace; - public readonly string TypeName; - - public DotNetName (string @namespace, string typeName) - { - Namespace = @namespace; - TypeName = typeName; - } - - public override string ToString () - { - return $"{Namespace}.{TypeName}"; - } - - public override bool Equals (object obj) - { - var other = obj as DotNetName; - return other != null && Namespace == other.Namespace && TypeName == other.TypeName; - } - - public override int GetHashCode () - { - return Namespace.GetHashCode () ^ TypeName.GetHashCode (); - } - } - - public class TypeDatabase { - const double kCurrentVersion = 1.0; - const double kMinVersion = 1.0; - Dictionary netNamesToSwiftNames = new Dictionary (); - Dictionary swiftNamesToNetNames = new Dictionary (); - - Dictionary modules = new Dictionary (); - - public TypeDatabase () - { - } - - - public DotNetName DotNetNameForSwiftName (string swiftName) - { - DotNetName netName = null; - swiftNamesToNetNames.TryGetValue (Exceptions.ThrowOnNull (swiftName, "swiftName"), out netName); - return netName; // may be null - } - - public DotNetName DotNetNameForSwiftName (SwiftClassName swiftName) - { - return DotNetNameForSwiftName (Exceptions.ThrowOnNull (swiftName, "swiftName").ToFullyQualifiedName (true)); - } - - public string SwiftNameForDotNetName (DotNetName netName) - { - string swiftName = null; - netNamesToSwiftNames.TryGetValue (Exceptions.ThrowOnNull (netName, "netName"), out swiftName); - return swiftName; - } - - public Entity EntityForDotNetName (DotNetName netClassName) - { - return EntityForSwiftName (netNamesToSwiftNames [netClassName]); - } - - public Entity EntityForSwiftName (SwiftClassName swiftName) - { - return EntityForSwiftName (swiftName.ToFullyQualifiedName (true)); - } - - public Entity EntityForSwiftName (string swiftName) - { - var modName = swiftName.ModuleFromName (); - if (modName == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 1, $"Swift name '{swiftName}' needs to have a module."); - - var module = EntityCollection (modName); - if (module == null) - return null; - - Entity e = null; - module.TryGetValue (swiftName, out e); - return e; - } - - public Entity TryGetEntityForSwiftName (string swiftName) - { - try { - return EntityForSwiftName (swiftName); - } - catch { - return null; - } - } - - public int Count { - get { - return modules.Select (m => m.Value.Count).Sum (); - } - } - - public bool Contains (string swiftClassName) - { - return EntityForSwiftName (swiftClassName) != null; - } - - public bool Contains (SwiftClassName swiftClassName) - { - return Contains (swiftClassName.ToFullyQualifiedName (true)); - } - - public bool Contains (DotNetName name) - { - return netNamesToSwiftNames.ContainsKey (name); - } - - public IEnumerable ModuleNames { get { return modules.Keys; } } - - public void Update (Entity e) - { - var old = EntityForSwiftName (e.Type.ToFullyQualifiedName (true)); - if (old == null) { - Add (e); - } else { - old.EntityType = e.EntityType; - old.SharpNamespace = e.SharpNamespace; - old.SharpTypeName = e.SharpTypeName; - old.Type = e.Type; - } - } - - public void Add (Entity e) - { - if (e.Type != null && !e.Type.IsUnrooted) - throw new ArgumentException ("Entity.Type needs to be unrooted.", "e"); - var errors = new ErrorHandling (); - AddEntity (e, errors); - if (errors.AnyErrors) - throw new AggregateException (errors.Errors.Select ((v) => v.Exception)); - } - - ModuleDatabase EntityCollection (string moduleName) - { - ModuleDatabase module = null; - modules.TryGetValue (Exceptions.ThrowOnNull (moduleName, nameof(moduleName)), out module); - return module; - } - - public IEnumerable EntitiesForModule (string moduleName) - { - var module = EntityCollection (moduleName); - if (module != null) - return module.Values; - return Enumerable.Empty (); - } - - public IEnumerable OperatorsForModule (string moduleName) - { - var module = EntityCollection (moduleName); - if (module != null) - return module.Operators; - return Enumerable.Empty (); - } - - public IEnumerable TypeAliasesForModule (string moduleName) - { - var module = EntityCollection (moduleName); - if (module != null) - return module.TypeAliases; - return Enumerable.Empty (); - } - - public void Write (string file, IEnumerable modules) - { - using (FileStream stm = new FileStream (Exceptions.ThrowOnNull (file, nameof(file)), FileMode.Create)) { - Write (stm, modules); - } - } - - public void Write (Stream stm, IEnumerable modules) - { - Write (stm, modules.Select (s => EntitiesForModule (s)).SelectMany (x => x).Select (entity => entity.ToXElement ())); - } - - IEnumerable GatherXElements (IEnumerable modules) - { - foreach (var modName in modules) { - foreach (var entity in EntitiesForModule (modName)) { - yield return entity.ToXElement (); - } - foreach (var op in OperatorsForModule (modName)) { - yield return op.ToXElement (); - } - foreach (var alias in TypeAliasesForModule (modName)) { - yield return alias.ToXElement (); - } - } - } - - public void Write (string file, string module) - { - using (FileStream stm = new FileStream (Exceptions.ThrowOnNull (file, "file"), FileMode.Create)) { - Write (stm, module); - } - } - - public void Write (Stream stm, string module) - { - Write (stm, EntitiesForModule (module).Select (entity => entity.ToXElement ())); - } - - void Write (Stream stm, IEnumerable entities) - { - var entityList = new XElement ("entities", entities); - var db = new XElement ("xamtypedatabase", - new XAttribute ("version", 1.0), - entityList); - var doc = new XDocument ( - new XDeclaration ("1.0", "utf-8", "yes"), - db); - doc.Save (stm); - } - - public bool Merge (TypeDatabase other, ErrorHandling errors) - { - var initialErrorCount = errors.ErrorCount; - foreach (var mod in other.modules.Values) { - foreach (var entity in mod.Values) { - AddEntity (entity, errors); - } - foreach (var op in mod.Operators) { - AddOperator (op); - } - } - return initialErrorCount != errors.ErrorCount; - } - - - public ErrorHandling Read (List files) - { - var errors = new ErrorHandling(); - foreach (string file in files) { - errors.Add (Read (file)); - } - return errors; - } - - public ErrorHandling Read (string file) - { - var errors = new ErrorHandling (); - Stream stm = null; - try { - stm = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read); - errors.Add (Read (stm)); - } catch (Exception e) { - errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 59, e, "Failed opening file {0}: {1}", file, e.Message)); - } finally { - if (stm != null) - stm.Close (); - } - return errors; - } - - public ErrorHandling Read (Stream stm) - { - var errors = new ErrorHandling (); - try { - var doc = XDocument.Load (stm); - var xamtypedatabase = doc.Element ("xamtypedatabase"); - if (xamtypedatabase == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 2, "Type database is missing required key 'xamtypedatabase'"); - var version = xamtypedatabase.DoubleAttribute ("version", -1.0); - if (version < kMinVersion) - if (version > kCurrentVersion) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 3, $"Type database version, {version}, is greater than the current version, {kCurrentVersion}."); - ReadVersion1_0 (xamtypedatabase, errors); - } catch (Exception e) { - errors.Add (ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 60, e, "Failure reading type definition XML: " + e.Message)); - } - return errors; - } - - void ReadVersion1_0 (XElement typeDbRoot, ErrorHandling errors) - { - var localModules = new Dictionary (); - - var entityLists = typeDbRoot.Descendants ("entities"); - - foreach (var entityList in entityLists) { - var entities = from entity in entityList.Elements ("entity") - select EntityFromXElement (entity, localModules, errors); - - foreach (Entity e in entities) { - if (e == null) - continue; - AddEntity (e, errors); - } - - var ops = from op in entityList.Elements ("operator") - select OperatorDeclaration.FromXElement (op, null); - - foreach (var op in ops) { - AddOperator (op); - } - - var aliases = from alias in entityList.Elements ("typealias") - select TypeAliasDeclaration.FromXElement (null, alias); - - foreach (var alias in aliases) { - AddTypeAlias (alias); - } - } - } - - public ModuleDatabase ModuleDatabaseForModuleName (string moduleName) - { - ModuleDatabase db; - if (!modules.TryGetValue (moduleName, out db)) { - db = new ModuleDatabase (); - modules.Add (moduleName, db); - } - return db; - } - - public void AddOperator (OperatorDeclaration op, string moduleName = null) - { - moduleName = moduleName ?? op.ModuleName; - ModuleDatabase db = ModuleDatabaseForModuleName (moduleName); - db.Operators.Add (op); - } - - public IEnumerable FindOperators (IEnumerable moduleNames) - { - foreach (var moduleName in moduleNames) { - ModuleDatabase db = null; - if (!modules.TryGetValue (moduleName, out db)) - continue; - foreach (var op in db.Operators) - yield return op; - } - yield break; - } - - public void AddTypeAlias (TypeAliasDeclaration alias, string moduleName = null) - { - moduleName = moduleName ?? alias.ModuleName; - ModuleDatabase db = ModuleDatabaseForModuleName (moduleName); - db.TypeAliases.Add (alias); - } - - void AddEntity (Entity e, ErrorHandling errors) - { - var swiftName = e.Type.ToFullyQualifiedName (true); - var sharpName = e.GetFullType (); - if (netNamesToSwiftNames.ContainsKey (sharpName)) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 4, $"Already have a C# definition for {e.EntityType} {sharpName}"))); - return; - } - if (swiftNamesToNetNames.ContainsKey (swiftName)) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 5, $"Already have a Swift definition for {e.EntityType} {swiftName}"))); - return; - } - - netNamesToSwiftNames.Add (sharpName, swiftName); - swiftNamesToNetNames.Add (swiftName, sharpName); - - var moduleName = e.Type.Module.Name; - AddEntityToModuleCollection (moduleName, e); - } - - void AddEntityToModuleCollection (string moduleName, Entity e) - { - ModuleDatabase entities = null; - if (!modules.TryGetValue (moduleName, out entities)) { - entities = new ModuleDatabase (); - modules.Add (moduleName, entities); - } - entities.Add (e.Type.ToFullyQualifiedName (true), e); - } - - Entity EntityFromXElement (XElement entityElem, Dictionary theModules, ErrorHandling errors) - { - var typeDeclElement = entityElem.Element ("typedeclaration"); - if (typeDeclElement == null) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 6, "Entity elements must contain a child element."))); - return null; - } - var moduleName = (string)typeDeclElement.Attribute ("module"); - if (string.IsNullOrEmpty (moduleName)) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 7, "Entity elements must contain a module name."))); - return null; - } - var module = MakeModuleForName (moduleName, theModules); - var folder = new TypeAliasFolder (module.TypeAliases); - var decl = TypeDeclaration.FromXElement (folder, typeDeclElement, module, null) as TypeDeclaration; - if (decl == null) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 8, "Incorrect type declaration in entity."))); - return null; - } - var e = new Entity { - SharpNamespace = (string)entityElem.Attribute ("sharpNameSpace"), - SharpTypeName = (string)entityElem.Attribute ("sharpTypeName"), - EntityType = ToEntityType ((string)entityElem.Attribute ("entityType")), - ProtocolProxyModule = (string)entityElem.Attribute ("protocolProxyModule"), - IsDiscretionaryConstraint = IsDiscetionaryConstraint (entityElem), - Type = decl - }; - if (e.SharpNamespace == null) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 12, "Missing sharpNameSpace in entity."))); - return null; - } - if (e.SharpTypeName == null) { - errors.Add (new ReflectorError (ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 13, "Missing sharpTypeName in entity."))); - return null; - } - return e; - } - - static EntityType ToEntityType (string s) - { - switch (Exceptions.ThrowOnNull (s, "s").ToLower ()) { - case "scalar": - return EntityType.Scalar; - case "class": - return EntityType.Class; - case "struct": - return EntityType.Struct; - case "enum": - return EntityType.Enum; - case "trivialenum": - return EntityType.TrivialEnum; - case "protocol": - return EntityType.Protocol; - default: - case "none": - return EntityType.None; - } - } - - static bool IsDiscetionaryConstraint (XElement entityElem) - { - var discretionary = (string)entityElem.Attribute ("discretionaryConstraint") ?? "false"; - return discretionary.ToLower () == "true"; - } - - ModuleDeclaration MakeModuleForName (string name, Dictionary modules) - { - ModuleDeclaration module = null; - if (!modules.TryGetValue (name, out module)) { - module = new ModuleDeclaration (); - module.Name = name; - modules.Add (name, module); - } - return module; - } - } +namespace SwiftReflector.TypeMapping +{ + public class DotNetName + { + public readonly string Namespace; + public readonly string TypeName; + + public DotNetName(string @namespace, string typeName) + { + Namespace = @namespace; + TypeName = typeName; + } + + public override string ToString() + { + return $"{Namespace}.{TypeName}"; + } + + public override bool Equals(object obj) + { + var other = obj as DotNetName; + return other != null && Namespace == other.Namespace && TypeName == other.TypeName; + } + + public override int GetHashCode() + { + return Namespace.GetHashCode() ^ TypeName.GetHashCode(); + } + } + + public class TypeDatabase + { + const double kCurrentVersion = 1.0; + const double kMinVersion = 1.0; + Dictionary netNamesToSwiftNames = new Dictionary(); + Dictionary swiftNamesToNetNames = new Dictionary(); + + Dictionary modules = new Dictionary(); + + public TypeDatabase() + { + } + + + public DotNetName DotNetNameForSwiftName(string swiftName) + { + DotNetName netName = null; + swiftNamesToNetNames.TryGetValue(Exceptions.ThrowOnNull(swiftName, "swiftName"), out netName); + return netName; // may be null + } + + public DotNetName DotNetNameForSwiftName(SwiftClassName swiftName) + { + return DotNetNameForSwiftName(Exceptions.ThrowOnNull(swiftName, "swiftName").ToFullyQualifiedName(true)); + } + + public string SwiftNameForDotNetName(DotNetName netName) + { + string swiftName = null; + netNamesToSwiftNames.TryGetValue(Exceptions.ThrowOnNull(netName, "netName"), out swiftName); + return swiftName; + } + + public Entity EntityForDotNetName(DotNetName netClassName) + { + return EntityForSwiftName(netNamesToSwiftNames[netClassName]); + } + + public Entity EntityForSwiftName(SwiftClassName swiftName) + { + return EntityForSwiftName(swiftName.ToFullyQualifiedName(true)); + } + + public Entity EntityForSwiftName(string swiftName) + { + var modName = swiftName.ModuleFromName(); + if (modName == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 1, $"Swift name '{swiftName}' needs to have a module."); + + var module = EntityCollection(modName); + if (module == null) + return null; + + Entity e = null; + module.TryGetValue(swiftName, out e); + return e; + } + + public Entity TryGetEntityForSwiftName(string swiftName) + { + try + { + return EntityForSwiftName(swiftName); + } + catch + { + return null; + } + } + + public int Count + { + get + { + return modules.Select(m => m.Value.Count).Sum(); + } + } + + public bool Contains(string swiftClassName) + { + return EntityForSwiftName(swiftClassName) != null; + } + + public bool Contains(SwiftClassName swiftClassName) + { + return Contains(swiftClassName.ToFullyQualifiedName(true)); + } + + public bool Contains(DotNetName name) + { + return netNamesToSwiftNames.ContainsKey(name); + } + + public IEnumerable ModuleNames { get { return modules.Keys; } } + + public void Update(Entity e) + { + var old = EntityForSwiftName(e.Type.ToFullyQualifiedName(true)); + if (old == null) + { + Add(e); + } + else + { + old.EntityType = e.EntityType; + old.SharpNamespace = e.SharpNamespace; + old.SharpTypeName = e.SharpTypeName; + old.Type = e.Type; + } + } + + public void Add(Entity e) + { + if (e.Type != null && !e.Type.IsUnrooted) + throw new ArgumentException("Entity.Type needs to be unrooted.", "e"); + var errors = new ErrorHandling(); + AddEntity(e, errors); + if (errors.AnyErrors) + throw new AggregateException(errors.Errors.Select((v) => v.Exception)); + } + + ModuleDatabase EntityCollection(string moduleName) + { + ModuleDatabase module = null; + modules.TryGetValue(Exceptions.ThrowOnNull(moduleName, nameof(moduleName)), out module); + return module; + } + + public IEnumerable EntitiesForModule(string moduleName) + { + var module = EntityCollection(moduleName); + if (module != null) + return module.Values; + return Enumerable.Empty(); + } + + public IEnumerable OperatorsForModule(string moduleName) + { + var module = EntityCollection(moduleName); + if (module != null) + return module.Operators; + return Enumerable.Empty(); + } + + public IEnumerable TypeAliasesForModule(string moduleName) + { + var module = EntityCollection(moduleName); + if (module != null) + return module.TypeAliases; + return Enumerable.Empty(); + } + + public void Write(string file, IEnumerable modules) + { + using (FileStream stm = new FileStream(Exceptions.ThrowOnNull(file, nameof(file)), FileMode.Create)) + { + Write(stm, modules); + } + } + + public void Write(Stream stm, IEnumerable modules) + { + Write(stm, modules.Select(s => EntitiesForModule(s)).SelectMany(x => x).Select(entity => entity.ToXElement())); + } + + IEnumerable GatherXElements(IEnumerable modules) + { + foreach (var modName in modules) + { + foreach (var entity in EntitiesForModule(modName)) + { + yield return entity.ToXElement(); + } + foreach (var op in OperatorsForModule(modName)) + { + yield return op.ToXElement(); + } + foreach (var alias in TypeAliasesForModule(modName)) + { + yield return alias.ToXElement(); + } + } + } + + public void Write(string file, string module) + { + using (FileStream stm = new FileStream(Exceptions.ThrowOnNull(file, "file"), FileMode.Create)) + { + Write(stm, module); + } + } + + public void Write(Stream stm, string module) + { + Write(stm, EntitiesForModule(module).Select(entity => entity.ToXElement())); + } + + void Write(Stream stm, IEnumerable entities) + { + var entityList = new XElement("entities", entities); + var db = new XElement("xamtypedatabase", + new XAttribute("version", 1.0), + entityList); + var doc = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + db); + doc.Save(stm); + } + + public bool Merge(TypeDatabase other, ErrorHandling errors) + { + var initialErrorCount = errors.ErrorCount; + foreach (var mod in other.modules.Values) + { + foreach (var entity in mod.Values) + { + AddEntity(entity, errors); + } + foreach (var op in mod.Operators) + { + AddOperator(op); + } + } + return initialErrorCount != errors.ErrorCount; + } + + + public ErrorHandling Read(List files) + { + var errors = new ErrorHandling(); + foreach (string file in files) + { + errors.Add(Read(file)); + } + return errors; + } + + public ErrorHandling Read(string file) + { + var errors = new ErrorHandling(); + Stream stm = null; + try + { + stm = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + errors.Add(Read(stm)); + } + catch (Exception e) + { + errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 59, e, "Failed opening file {0}: {1}", file, e.Message)); + } + finally + { + if (stm != null) + stm.Close(); + } + return errors; + } + + public ErrorHandling Read(Stream stm) + { + var errors = new ErrorHandling(); + try + { + var doc = XDocument.Load(stm); + var xamtypedatabase = doc.Element("xamtypedatabase"); + if (xamtypedatabase == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 2, "Type database is missing required key 'xamtypedatabase'"); + var version = xamtypedatabase.DoubleAttribute("version", -1.0); + if (version < kMinVersion) + if (version > kCurrentVersion) + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 3, $"Type database version, {version}, is greater than the current version, {kCurrentVersion}."); + ReadVersion1_0(xamtypedatabase, errors); + } + catch (Exception e) + { + errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 60, e, "Failure reading type definition XML: " + e.Message)); + } + return errors; + } + + void ReadVersion1_0(XElement typeDbRoot, ErrorHandling errors) + { + var localModules = new Dictionary(); + + var entityLists = typeDbRoot.Descendants("entities"); + + foreach (var entityList in entityLists) + { + var entities = from entity in entityList.Elements("entity") + select EntityFromXElement(entity, localModules, errors); + + foreach (Entity e in entities) + { + if (e == null) + continue; + AddEntity(e, errors); + } + + var ops = from op in entityList.Elements("operator") + select OperatorDeclaration.FromXElement(op, null); + + foreach (var op in ops) + { + AddOperator(op); + } + + var aliases = from alias in entityList.Elements("typealias") + select TypeAliasDeclaration.FromXElement(null, alias); + + foreach (var alias in aliases) + { + AddTypeAlias(alias); + } + } + } + + public ModuleDatabase ModuleDatabaseForModuleName(string moduleName) + { + ModuleDatabase db; + if (!modules.TryGetValue(moduleName, out db)) + { + db = new ModuleDatabase(); + modules.Add(moduleName, db); + } + return db; + } + + public void AddOperator(OperatorDeclaration op, string moduleName = null) + { + moduleName = moduleName ?? op.ModuleName; + ModuleDatabase db = ModuleDatabaseForModuleName(moduleName); + db.Operators.Add(op); + } + + public IEnumerable FindOperators(IEnumerable moduleNames) + { + foreach (var moduleName in moduleNames) + { + ModuleDatabase db = null; + if (!modules.TryGetValue(moduleName, out db)) + continue; + foreach (var op in db.Operators) + yield return op; + } + yield break; + } + + public void AddTypeAlias(TypeAliasDeclaration alias, string moduleName = null) + { + moduleName = moduleName ?? alias.ModuleName; + ModuleDatabase db = ModuleDatabaseForModuleName(moduleName); + db.TypeAliases.Add(alias); + } + + void AddEntity(Entity e, ErrorHandling errors) + { + var swiftName = e.Type.ToFullyQualifiedName(true); + var sharpName = e.GetFullType(); + if (netNamesToSwiftNames.ContainsKey(sharpName)) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 4, $"Already have a C# definition for {e.EntityType} {sharpName}"))); + return; + } + if (swiftNamesToNetNames.ContainsKey(swiftName)) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 5, $"Already have a Swift definition for {e.EntityType} {swiftName}"))); + return; + } + + netNamesToSwiftNames.Add(sharpName, swiftName); + swiftNamesToNetNames.Add(swiftName, sharpName); + + var moduleName = e.Type.Module.Name; + AddEntityToModuleCollection(moduleName, e); + } + + void AddEntityToModuleCollection(string moduleName, Entity e) + { + ModuleDatabase entities = null; + if (!modules.TryGetValue(moduleName, out entities)) + { + entities = new ModuleDatabase(); + modules.Add(moduleName, entities); + } + entities.Add(e.Type.ToFullyQualifiedName(true), e); + } + + Entity EntityFromXElement(XElement entityElem, Dictionary theModules, ErrorHandling errors) + { + var typeDeclElement = entityElem.Element("typedeclaration"); + if (typeDeclElement == null) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 6, "Entity elements must contain a child element."))); + return null; + } + var moduleName = (string)typeDeclElement.Attribute("module"); + if (string.IsNullOrEmpty(moduleName)) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 7, "Entity elements must contain a module name."))); + return null; + } + var module = MakeModuleForName(moduleName, theModules); + var folder = new TypeAliasFolder(module.TypeAliases); + var decl = TypeDeclaration.FromXElement(folder, typeDeclElement, module, null) as TypeDeclaration; + if (decl == null) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 8, "Incorrect type declaration in entity."))); + return null; + } + var e = new Entity + { + SharpNamespace = (string)entityElem.Attribute("sharpNameSpace"), + SharpTypeName = (string)entityElem.Attribute("sharpTypeName"), + EntityType = ToEntityType((string)entityElem.Attribute("entityType")), + ProtocolProxyModule = (string)entityElem.Attribute("protocolProxyModule"), + IsDiscretionaryConstraint = IsDiscetionaryConstraint(entityElem), + Type = decl + }; + if (e.SharpNamespace == null) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 12, "Missing sharpNameSpace in entity."))); + return null; + } + if (e.SharpTypeName == null) + { + errors.Add(new ReflectorError(ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 13, "Missing sharpTypeName in entity."))); + return null; + } + return e; + } + + static EntityType ToEntityType(string s) + { + switch (Exceptions.ThrowOnNull(s, "s").ToLower()) + { + case "scalar": + return EntityType.Scalar; + case "class": + return EntityType.Class; + case "struct": + return EntityType.Struct; + case "enum": + return EntityType.Enum; + case "trivialenum": + return EntityType.TrivialEnum; + case "protocol": + return EntityType.Protocol; + default: + case "none": + return EntityType.None; + } + } + + static bool IsDiscetionaryConstraint(XElement entityElem) + { + var discretionary = (string)entityElem.Attribute("discretionaryConstraint") ?? "false"; + return discretionary.ToLower() == "true"; + } + + ModuleDeclaration MakeModuleForName(string name, Dictionary modules) + { + ModuleDeclaration module = null; + if (!modules.TryGetValue(name, out module)) + { + module = new ModuleDeclaration(); + module.Name = name; + modules.Add(name, module); + } + return module; + } + } } diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/TypeMapping/TypeMapper.cs index ea2ad9d4840e..93ff0946706f 100644 --- a/src/SwiftReflector/TypeMapping/TypeMapper.cs +++ b/src/SwiftReflector/TypeMapping/TypeMapper.cs @@ -13,1103 +13,1268 @@ using SyntaxDynamo.CSLang; using SwiftRuntimeLibrary; -namespace SwiftReflector.TypeMapping { - public class TypeMapper { - public TypeDatabase TypeDatabase { get; private set; } - UnicodeMapper unicodeMapper; - HashSet loadedFiles = new HashSet (); - - public TypeMapper (List typeDatabasePaths, UnicodeMapper unicodeMapper) - { - TypeDatabase = new TypeDatabase (); - this.unicodeMapper = unicodeMapper; - } - - public void AddTypeDatabase (string fileName) - { - if (loadedFiles.Contains (fileName)) - return; - loadedFiles.Add (fileName); - var errors = TypeDatabase.Read (fileName); - if (errors.AnyErrors) - throw new AggregateException (errors.Errors.Select ((v) => v.Exception)); - } - - DotNetName PreRegisterEntityName (string swiftClassName, EntityType entityKind) - { - - var en = TypeDatabase.EntityForSwiftName (swiftClassName); - if (en != null) - return en.GetFullType (); - - - var netClassName = MakeDotNetClassName (swiftClassName, entityKind == EntityType.Protocol); - - en = new Entity { - SharpNamespace = netClassName.Namespace, - SharpTypeName = netClassName.TypeName, - Type = new ShamDeclaration (swiftClassName, entityKind), - EntityType = entityKind - }; - TypeDatabase.Add (en); - return netClassName; - } - - public bool IsRegistered (SwiftClassName cl) - { - return TypeDatabase.Contains (cl); - } - - public bool IsRegistered (string fullyQualifiedName) - { - return TypeDatabase.Contains (fullyQualifiedName); - } - - public DotNetName PreRegisterEntityName (SwiftClassName cl) - { - var swiftClassName = cl.ToFullyQualifiedName (); - var entity = EntityType.None; - // FIXME - if (cl.IsClass) - entity = EntityType.Class; - else if (cl.IsStruct) - entity = EntityType.Struct; - else if (cl.IsEnum) - entity = EntityType.Enum; - else { - throw new NotImplementedException (); - } - return PreRegisterEntityName (swiftClassName, entity); - } - - public DotNetName GetDotNetNameForSwiftClassName (SwiftClassName cl) - { - return TypeDatabase.EntityForSwiftName (cl).GetFullType (); - } - - public DotNetName GetDotNetNameForTypeSpec (TypeSpec spec) - { - var named = spec as NamedTypeSpec; - if (named == null) - return null; - return GetDotNetNameForSwiftClassName (named.Name); - } - - public DotNetName GetDotNetNameForSwiftClassName (string fullyQualifiedName) - { - var entity = TypeDatabase.EntityForSwiftName (fullyQualifiedName); - if (entity == null) - return null; - return entity.GetFullType (); - } - - public EntityType GetEntityTypeForSwiftClassName (string fullyQualifiedName) - { - var ent = TypeDatabase.EntityForSwiftName (fullyQualifiedName); - return ent != null ? ent.EntityType : EntityType.None; - } - - public EntityType GetEntityTypeForDotNetName (DotNetName netClassName) - { - var ent = TypeDatabase.EntityForDotNetName (netClassName); - return ent != null ? ent.EntityType : EntityType.None; - } - - public Entity GetEntityForSwiftClassName (string fullyQualifiedName) - { - return TypeDatabase.EntityForSwiftName (fullyQualifiedName); - } - - public Entity TryGetEntityForSwiftClassName (string fullyQualifiedName) - { - return TypeDatabase.TryGetEntityForSwiftName (fullyQualifiedName); - } - - public Entity GetEntityForTypeSpec (TypeSpec spec) - { - if (spec == null) - return null; - var ns = spec as NamedTypeSpec; - if (ns == null || spec.IsDynamicSelf) - return null; - return GetEntityForSwiftClassName (ns.Name); - } - - public EntityType GetEntityTypeForTypeSpec (TypeSpec spec) - { - if (spec == null) - return EntityType.None; - - if (spec is NamedTypeSpec) { - if (spec.IsDynamicSelf) - return EntityType.DynamicSelf; - var ent = GetEntityForTypeSpec (spec); - return ent != null ? ent.EntityType : EntityType.None; - } - if (spec is TupleTypeSpec) { - return EntityType.Tuple; - } - if (spec is ClosureTypeSpec) { - return EntityType.Closure; - } - if (spec is ProtocolListTypeSpec) { - return EntityType.ProtocolList; - } - throw new ArgumentOutOfRangeException (spec.GetType ().Name); - } - - public Entity GetEntityForDotNetName (DotNetName netName) - { - return TypeDatabase.EntityForDotNetName (netName); - } - - public DotNetName RegisterClass (TypeDeclaration t) - { - t = t.MakeUnrooted (); - var isProtocol = false; - // FIXME - var entity = EntityType.None; - // don't reorder - until I change this, ProtocolDeclaration extends from ClassDeclaration - if (t is ProtocolDeclaration) { - entity = EntityType.Protocol; - isProtocol = true; - } else if (t is ClassDeclaration) { - entity = EntityType.Class; - } else if (t is StructDeclaration) { - entity = EntityType.Struct; - } else { - EnumDeclaration eDecl = t as EnumDeclaration; - entity = (eDecl.IsTrivial || (eDecl.IsIntegral && eDecl.IsHomogenous && eDecl.Inheritance.Count == 0)) ? EntityType.TrivialEnum : EntityType.Enum; - } - var sharpName = MakeDotNetClassName (t.ToFullyQualifiedName (true), isProtocol); - - var en = new Entity { - SharpNamespace = sharpName.Namespace, - SharpTypeName = sharpName.TypeName, - Type = t, - EntityType = entity - }; - - TypeDatabase.Update (en); - return sharpName; - } - - public IEnumerable RegisterClasses (IEnumerable decl) - { - var allReg = new List (); - foreach (TypeDeclaration cl in decl) { - DotNetName reg = RegisterClass (cl); - allReg.Add (reg); - } - return allReg; - } - - DotNetName MakeDotNetClassName (string fullyQualifiedName, bool isProtocol) - { - var parts = fullyQualifiedName.Split ('.'); - var sb = new StringBuilder (); - var namesp = MapModuleToNamespace (parts [0]); - for (int i = 1; i < parts.Length; i++) { - if (i > 1) - sb.Append ('.'); - if (isProtocol && i == parts.Length - 1) - sb.Append ('I'); - sb.Append (SanitizeIdentifier (parts [i])); - } - return new DotNetName (namesp, sb.ToString ()); - } - - string MakeDotNetClassName (SwiftClassName name) - { - var sb = new StringBuilder (); - var namesp = MapModuleToNamespace (name.Module); - sb.Append (namesp); - foreach (SwiftName sn in name.NestingNames) { - sb.Append ('.'); - sb.Append (SanitizeIdentifier (sn.Name)); - } - return sb.ToString (); - } - - public string MapModuleToNamespace (SwiftName name) - { - string finalName = null; - finalName = UserModuleMap (name); - if (finalName == null) { - finalName = SanitizeIdentifier (name.Name); - } - return finalName; - } - - public string MapModuleToNamespace (string name) - { - string finalName = null; - finalName = UserModuleMap (name); - if (finalName == null) { - finalName = SanitizeIdentifier (name); - } - return finalName; - } - - - string UserModuleMap (SwiftName name) - { - return null; - } - - string UserModuleMap (string name) - { - return null; - } - - static UnicodeCategory [] validStarts = { - UnicodeCategory.UppercaseLetter, - UnicodeCategory.LowercaseLetter, - UnicodeCategory.TitlecaseLetter, - UnicodeCategory.ModifierLetter, - UnicodeCategory.OtherLetter, - UnicodeCategory.LetterNumber - }; - - static bool ValidIdentifierStart (UnicodeCategory cat) - { - return validStarts.Contains (cat); - } - - static UnicodeCategory [] validContent = { - UnicodeCategory.DecimalDigitNumber, - UnicodeCategory.ConnectorPunctuation, - UnicodeCategory.Format - }; - - static bool ValidIdentifierContent (UnicodeCategory cat) - { - return ValidIdentifierStart (cat) || validContent.Contains (cat); - } - - static bool IsValidIdentifier (int position, UnicodeCategory cat) - { - if (position == 0) - return ValidIdentifierStart (cat); - else - return ValidIdentifierContent (cat); - } - - static bool IsHighUnicode (string s) - { - // Steve says: this is arbitrary, but it solves an issue - // with mcs and csc not liking certain Ll and Lu class - // unicode characters (for now). - // Open issue: https://github.com/dotnet/roslyn/issues/27986 - var encoding = Encoding.UTF32; - var bytes = encoding.GetBytes (s); - var utf32Value = BitConverter.ToUInt32 (bytes, 0); - return utf32Value > 0xffff; - } - - public string SanitizeIdentifier (string name) - { - var sb = new StringBuilder (); - - var characterEnum = StringInfo.GetTextElementEnumerator (name); - while (characterEnum.MoveNext ()) { - string c = characterEnum.GetTextElement (); - int i = characterEnum.ElementIndex; - - var cat = CharUnicodeInfo.GetUnicodeCategory (name, i); - - if (IsValidIdentifier (i, cat) && !IsHighUnicode(c)) - sb.Append (i == 0 && cat == UnicodeCategory.LowercaseLetter ? c.ToUpper() : c); - else - sb.Append (unicodeMapper.MapToUnicodeName (c)); - } - - if (CSKeywords.IsKeyword (sb.ToString ())) - sb.Append ('_'); - return sb.ToString (); - } - - static string ComeUpWithAName (string given, string typeName, int index) - { - if (String.IsNullOrEmpty (given)) { - return String.Format ("{0}{1}", Char.ToLower (typeName [0]), index); - } else { - return given; - } - } - - static NetParam ToNamedParam (ParameterItem st, NetTypeBundle bundle, int index) - { - string targetName = ComeUpWithAName (st.NameIsRequired ? st.PublicName : st.PrivateName, bundle.Type, index); - return new NetParam (targetName, bundle); - } - - static bool IsUnique (NetParam p, List pl, int startPoint) - { - for (int i = startPoint; i < pl.Count; i++) { - if (p.Name == pl [i].Name) - return false; - } - return true; - } - - static NetParam Uniquify (NetParam p, List pl, int startPoint) - { - while (!IsUnique (p, pl, startPoint) || CSKeywords.IsKeyword (p.Name)) { - p = new NetParam (p.Name + '0', p.Type); - } - return p; - } - - static List SanitizeParamNames (List parms) - { - List outlist = new List (); - bool changed = false; - do { - changed = false; - outlist = new List (); - for (int i = 0; i < parms.Count; i++) { - NetParam q = Uniquify (parms [i], parms, i + 1); - changed = q.Name != parms [i].Name; - outlist.Add (q); - } - if (changed) - parms = outlist; - } while (changed); - return outlist; - } - - public List GetLineage (SwiftUncurriedFunctionType uft) - { - var lineage = new List (); - if (uft != null) { - var theClass = uft.UncurriedParameter as SwiftClassType; - if (theClass == null) { - var meta = uft.UncurriedParameter as SwiftMetaClassType; - if (meta == null) - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 17, $"Expected a SwiftClassType or a SwiftMetaClassType as the uncurried parameter in a function, but got {uft.UncurriedParameter.GetType ().Name}."); - theClass = meta.Class; - } - var sb = new StringBuilder ().Append (theClass.ClassName.Module.Name); - foreach (SwiftName name in theClass.ClassName.NestingNames) { - sb.Append ('.').Append (name.Name); - lineage.Add (sb.ToString ()); - } - } - return lineage; - } - - internal object GetEntityForTypeSpec (object inheritsTypeSpec) - { - throw new NotImplementedException (); - } - - - NetTypeBundle RecastToReference (BaseDeclaration typeContext, NetTypeBundle netBundle, TypeSpec theElem, bool structsAndEnumsAreAlwaysRefs) - { - if (typeContext.IsTypeSpecGenericReference (theElem) || typeContext.IsProtocolWithAssociatedTypesFullPath (theElem as NamedTypeSpec, this)) - return netBundle; - if (theElem is ClosureTypeSpec) - return netBundle; - if (theElem is ProtocolListTypeSpec) - return new NetTypeBundle (netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); - var entity = GetEntityForTypeSpec (theElem); - if (entity != null && (entity.IsObjCStruct || entity.IsObjCEnum) && netBundle.IsReference) - return netBundle; - if (theElem.IsInOut && netBundle.Entity != EntityType.Struct) - return netBundle; - - var objcStructType = ObjCStructOrEnumReferenceType (typeContext, theElem as NamedTypeSpec); - if (objcStructType != null) { - return MapType (typeContext, objcStructType, true); - } - var isStructOrEnum = netBundle.Entity == EntityType.Struct || netBundle.Entity == EntityType.Enum; - if (isStructOrEnum) { - if (MustForcePassByReference (typeContext, theElem) || netBundle.Entity == EntityType.Enum || structsAndEnumsAreAlwaysRefs) { - return new NetTypeBundle ("System", "IntPtr", netBundle.IsScalar, false, netBundle.Entity); - } - } else if (entity != null && entity.EntityType == EntityType.Protocol && !entity.IsObjCProtocol) { - return new NetTypeBundle (netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); - } - return netBundle; - } - - - NetParam MapParameterItem (BaseDeclaration context, ParameterItem parameter, int index, bool isPinvoke, bool structsAndEnumsAreAlwaysRefs) - { - var theType = parameter.TypeSpec; //parameter.IsInOut && !parameter.TypeSpec.IsInOut ? parameter.TypeSpec.WithInOutSet () : parameter.TypeSpec; - var t = MapType (context, theType, isPinvoke); - if (isPinvoke) { - t = RecastToReference (context, t, theType, structsAndEnumsAreAlwaysRefs); - } - return ToNamedParam (parameter, t, index); - } - - public List MapParameterList (BaseDeclaration context, List st, bool isPinvoke, - bool structsAndEnumsAreAlwaysRefs, CSGenericTypeDeclarationCollection extraProtocolTypes, - CSGenericConstraintCollection extraProtocolContstraints, CSUsingPackages use) - { - var parms = new List (); - for (int i=0; i < st.Count; i++) { - if (st[i].TypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) { - var genprotoName = new CSIdentifier ($"TProto{i}"); - extraProtocolTypes.Add (new CSGenericTypeDeclaration (genprotoName)); - extraProtocolContstraints.Add (new CSGenericConstraint (genprotoName, ToConstraintIDs (context, plitem.Protocols.Keys, isPinvoke))); - var netBundle = new NetTypeBundle ("", genprotoName.Name, false, st [i].IsInOut, EntityType.ProtocolList); - - parms.Add (ToNamedParam (st [i], netBundle, i)); - } else { - var entity = !context.IsTypeSpecGeneric (st [i].TypeSpec) ? GetEntityForTypeSpec (st [i].TypeSpec) : null; - if (entity != null && entity.EntityType == EntityType.Protocol && !isPinvoke) { - var proto = entity.Type as ProtocolDeclaration; - // if (proto.HasDynamicSelf) { - // extraProtocolTypes.Add (new CSGenericTypeDeclaration (BindingsCompiler.kGenericSelf)); - // var csProtoBundle = MapType (context, st [i].TypeSpec, isPinvoke); - // var csType = csProtoBundle.ToCSType (use); - // extraProtocolContstraints.Add (new CSGenericConstraint (BindingsCompiler.kGenericSelf, new CSIdentifier (csType.ToString ()))); - // } - } - - parms.Add (MapParameterItem (context, st [i], i, isPinvoke, structsAndEnumsAreAlwaysRefs)); - } - } - return SanitizeParamNames (parms); - } - - public IEnumerable ToConstraintIDs(BaseDeclaration context, IEnumerable types, bool isPinvoke) - { - foreach (var ns in types) { - var cstype = MapType (context, ns, isPinvoke); - yield return new CSIdentifier (cstype.ToString ()); - } - } - - public static bool IsCompoundProtocolListType (SwiftType st) - { - return st is SwiftProtocolListType pt && pt.Protocols.Count > 1; - } - - public static bool IsCompoundProtocolListType (TypeSpec sp) - { - return sp is ProtocolListTypeSpec pl && pl.Protocols.Count > 1; - } - - public NetTypeBundle MapType (SwiftType st, bool isPinvoke, bool isReturnValue = false) - { - if (IsCompoundProtocolListType (st) && !isPinvoke) - throw new NotImplementedException ("Check for a protocol list type first because you need to promote the method to a generic"); - switch (st.Type) { - case CoreCompoundType.Scalar: - return ToScalar ((SwiftBuiltInType)st); - case CoreCompoundType.Tuple: - return ToTuple ((SwiftTupleType)st, isPinvoke); - case CoreCompoundType.MetaClass: - return ToMetaClass ((SwiftMetaClassType)st); - case CoreCompoundType.Class: - if (st.IsStruct) - return ToStruct ((SwiftClassType)st, isPinvoke); - else if (st.IsClass) - return ToClass ((SwiftClassType)st, isPinvoke); - else if (st.IsEnum) - return ToEnum ((SwiftClassType)st, isPinvoke, isReturnValue); - else if (st.IsProtocol) - return ToProtocol ((SwiftClassType)st, isPinvoke); - else - throw new NotImplementedException (); - case CoreCompoundType.ProtocolList: - return ToProtocol ((SwiftProtocolListType)st, isPinvoke); - case CoreCompoundType.BoundGeneric: - return ToBoundGeneric ((SwiftBoundGenericType)st, isPinvoke); - case CoreCompoundType.GenericReference: - return ToGenericReference ((SwiftGenericArgReferenceType)st, isPinvoke); - case CoreCompoundType.Function: - return ToClosure ((SwiftBaseFunctionType)st, isPinvoke, isReturnValue); - default: - throw new NotImplementedException (); - } - } - - public NetTypeBundle MapType (BaseDeclaration context, TypeSpec spec, bool isPinvoke, bool isReturnValue = false, - Tuple selfDepthIndex = null) - { - if (IsCompoundProtocolListType (spec) && !isPinvoke) - throw new NotImplementedException ("Check for a protocol list type first because you need to promote the method to a generic"); - switch (spec.Kind) { - case TypeSpecKind.Named: - var named = (NamedTypeSpec)spec; - if (IsScalar (named.Name)) { - return ToScalar (named.Name, spec.IsInOut); - } - if (context.IsProtocolWithAssociatedTypesFullPath (named, this)) { - if (isPinvoke) { - return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - } else { - var assocType = context.AssociatedTypeDeclarationFromGenericWithFullPath (named, this); - var owningProtocol = context.OwningProtocolFromGenericWithFullPath (named, this); - return new NetTypeBundle (owningProtocol, assocType, false); - } - } else if (context.IsEqualityConstrainedByAssociatedType (named, this)) { - if (isPinvoke) { - return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - } else { - var assocType = context.AssociatedTypeDeclarationFromConstrainedGeneric (named, this); - var owningProtocol = context.OwningProtocolFromConstrainedGeneric (named, this); - return new NetTypeBundle (owningProtocol, assocType, false); - } - } else if (context.IsTypeSpecGeneric (spec) && (!spec.ContainsGenericParameters || isPinvoke)) { - if (context.IsTypeSpecGenericMetatypeReference (spec)) { - return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, spec.IsInOut, EntityType.None); - } else { - if (isPinvoke) { - var isPAT = context.GetConstrainedProtocolWithAssociatedType (named, this) != null; - var isInOut = isPAT ? false : named.IsInOut; - return new NetTypeBundle ("System", "IntPtr", false, isInOut, EntityType.None); - } else { - var depthIndex = context.GetGenericDepthAndIndex (spec); - return new NetTypeBundle (depthIndex.Item1, depthIndex.Item2); - } - } - } else if (context.IsTypeSpecAssociatedType (named)) { - if (isPinvoke) { - return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); - } else { - if (named.ContainsGenericParameters) { - var en = TypeDatabase.EntityForSwiftName (named.Name); - var retval = new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); - foreach (var gen in named.GenericParameters) { - var genNtb = MapType (context, gen, isPinvoke, isReturnValue); - retval.GenericTypes.Add (genNtb); - } - return retval; - } else { - var assocType = context.AssociatedTypeDeclarationFromNamedTypeSpec (named); - return new NetTypeBundle (context.AsProtocolOrParentAsProtocol (), assocType, named.IsInOut); - } - } - } - // else if (named.Name == "Self") { - // if (isPinvoke) { - // return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); - // } else { - // return new NetTypeBundle (BindingsCompiler.kGenericSelfName, named.IsInOut); - // } - // } - else { - Entity en = TypeDatabase.EntityForSwiftName (named.Name); - if (en != null) { - if (isPinvoke) { - switch (en.EntityType) { - case EntityType.Class: - case EntityType.Enum: - case EntityType.Tuple: - if (en.IsObjCEnum) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); - case EntityType.TrivialEnum: - return ToTrivialEnumType (en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, spec.IsInOut); - case EntityType.Protocol: - if (en.IsObjCProtocol) { - return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); - } else { - if (spec is ProtocolListTypeSpec protocolList) { - var container = $"SwiftExistentialContainer{protocolList.Protocols.Count}"; - return new NetTypeBundle ("SwiftRuntimeLibrary", container, false, true, EntityType.None); - } else { - return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, true, - EntityType.None); - } - } - case EntityType.Struct: - var protocolListRef = GetBoundProtocolListType (named); - if (protocolListRef != null) { - var container = $"SwiftExistentialContainer{protocolListRef.Protocols.Count}"; - return new NetTypeBundle ("SwiftRuntimeLibrary", container, false, true, EntityType.None); - - } - en = MapToObjCStructOrEnumReference (context, named) ?? en; - if (en.IsObjCStruct || en.IsObjCEnum) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - en = MapToScalarReference (context, named) ?? en; - if (en.EntityType == EntityType.Scalar) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } else { - return new NetTypeBundle ("System", "IntPtr", false, spec.IsInOut, EntityType.None); - } - case EntityType.Scalar: - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); - default: - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 21, "Can't happen - shouldn't ever get to this case in type mapping."); - } - } else { - var retval = new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); - if (en.EntityType == EntityType.Protocol && en.Type is ProtocolDeclaration proto) { - // if (proto.HasDynamicSelf) { - // if (selfDepthIndex != null) { - // retval.GenericTypes.Add (new NetTypeBundle (selfDepthIndex.Item1, selfDepthIndex.Item2)); - // } else { - // retval.GenericTypes.Add (new NetTypeBundle (BindingsCompiler.kGenericSelfName, spec.IsInOut)); - // } - // } - foreach (var assoc in proto.AssociatedTypes) { - var genMap = new NetTypeBundle (proto, assoc, spec.IsInOut); - retval.GenericTypes.Add (genMap); - } - } else { - foreach (var gen in spec.GenericParameters) { - retval.GenericTypes.Add (MapType (context, gen, isPinvoke)); - } - } - return retval; - } - } else { - if (isPinvoke) { - var namedSpec = spec as NamedTypeSpec; - if (namedSpec != null) { - if (TypeMapper.IsSwiftPointerType (namedSpec.Name)) { - return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - } - } - } - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 0, $"Unable to find C# reference for swift class '{spec.ToString ()}'."); - } - } - case TypeSpecKind.Tuple: - var tuple = (TupleTypeSpec)spec; - if (tuple.Elements.Count == 0) - return NetTypeBundle.Void; - var tupTypes = tuple.Elements.Select (ts => MapType (context, ts, isPinvoke)).ToList (); - return new NetTypeBundle (tupTypes, tuple.IsInOut); - case TypeSpecKind.Closure: - if (isPinvoke) { - return new NetTypeBundle ("SwiftRuntimeLibrary", isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", false, false, EntityType.Closure); - } else { - ClosureTypeSpec ft = spec as ClosureTypeSpec; - var throws = !isPinvoke && ft.Throws; - var arguments = ft.EachArgument().Select (parm => MapType (context, parm, false)).ToList (); - - string delegateName = "Action"; - if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) { - var returnBundle = MapType (context, ft.ReturnType, false, true); - arguments.Add (returnBundle); - delegateName = "Func"; - } - - if (arguments.Count == 0) - return new NetTypeBundle ("System", delegateName, false, false, EntityType.Closure, swiftThrows: throws); - else - return new NetTypeBundle ("System", delegateName, EntityType.Closure, false, arguments, swiftThrows: throws); - } - case TypeSpecKind.ProtocolList: - var pl = (ProtocolListTypeSpec)spec; - return new NetTypeBundle ("SwiftRuntimeLibrary", $"SwiftExistentialContainer{pl.Protocols.Count}", - false, true, EntityType.None); - - default: - throw new NotImplementedException (); - } - } - - bool IsProtocolListTypeReference (BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundProtocolListType (spec); - - return boundType != null; - } - - Entity MapToScalarReference (BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundPointerType (spec); - if (boundType == null) - return null; - if (context.IsTypeSpecGenericReference (boundType)) - return null; - if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) - return null; - var entity = TypeDatabase.EntityForSwiftName (boundType.Name); - return entity.EntityType == EntityType.Scalar || SwiftType.IsStructScalar (boundType.Name) ? entity : null; - } - - Entity MapToObjCStructOrEnumReference (BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundPointerType (spec); - if (boundType == null) - return null; - if (context.IsTypeSpecGenericReference (boundType)) - return null; - if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) - return null; - var entity = TypeDatabase.EntityForSwiftName (boundType.Name); - return entity.IsObjCStruct || entity.IsObjCEnum ? entity : null; - } - - TypeSpec ObjCStructOrEnumReferenceType (BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundPointerType (spec); - if (boundType == null) - return null; - if (context.IsTypeSpecGenericReference (boundType)) - return null; - if (context.IsProtocolWithAssociatedTypesFullPath (boundType, this)) - return null; - var entity = TypeDatabase.EntityForSwiftName (boundType.Name); - return entity.IsObjCStruct || entity.IsObjCEnum ? boundType : null; - } - - static NamedTypeSpec GetBoundPointerType (NamedTypeSpec spec) - { - if (spec == null) - return null; - if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") - return null; - var boundType = spec.GenericParameters [0] as NamedTypeSpec; - return boundType; - } - - static ProtocolListTypeSpec GetBoundProtocolListType (NamedTypeSpec spec) - { - if (spec == null) - return null; - if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") - return null; - return spec.GenericParameters [0] as ProtocolListTypeSpec; - } - - NetTypeBundle ToTuple (SwiftTupleType tt, bool isPinvoke) - { - if (tt.IsEmpty) - return NetTypeBundle.Void; - if (tt.Contents.Count == 1) { - return MapType (tt.Contents [0], isPinvoke); - } - var lt = tt.Contents.Select (t => MapType (t, isPinvoke)).ToList (); - return new NetTypeBundle (lt, tt.IsReference); - } - - NetTypeBundle ToScalar (SwiftBuiltInType bit) - { - switch (bit.BuiltInType) { - case CoreBuiltInType.Bool: - return ToScalar ("Swift.Bool", bit.IsReference); - case CoreBuiltInType.Double: - return ToScalar ("Swift.Double", bit.IsReference); - case CoreBuiltInType.Float: - return ToScalar ("Swift.Float", bit.IsReference); - case CoreBuiltInType.Int: - return new NetTypeBundle ("System", "nint", true, bit.IsReference, EntityType.Scalar); - case CoreBuiltInType.UInt: - return new NetTypeBundle ("System", "nuint", true, bit.IsReference, EntityType.Scalar); - default: - throw new ArgumentOutOfRangeException (nameof(bit)); - } - } - - static string [] scalarNames = new string [] { - "Swift.Bool", - "Swift.Double", - "Swift.Float", - "Swift.Int", - "Swift.UInt", - "Swift.Int8", - "Swift.UInt8", - "Swift.Int16", - "Swift.UInt16", - "Swift.Int32", - "Swift.UInt32", - "Swift.Int64", - "Swift.UInt64" - }; - - static int ScalarIndex (string builtIn) - { - return Array.IndexOf (scalarNames, builtIn); - } - - public static bool IsScalar (string builtIn) - { - return ScalarIndex (Exceptions.ThrowOnNull (builtIn, "builtIn")) >= 0; - } - - public static bool IsScalar (TypeSpec spec) - { - var ns = spec as NamedTypeSpec; - if (ns == null) - return false; - return ScalarIndex (ns.Name) >= 0; - } - - NetTypeBundle ToScalar (string builtIn, bool isReference) - { - int index = ScalarIndex (builtIn); - if (index >= 0) { - var en = TypeDatabase.EntityForSwiftName (builtIn); - if (en != null) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); - } - } - throw new ArgumentOutOfRangeException (nameof(builtIn)); - } - - NetTypeBundle ToMetaClass (SwiftMetaClassType mt) - { - return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftMetatype", false, mt.IsReference, EntityType.None); - } - - NetTypeBundle ToClass (SwiftClassType ct, bool isPinvoke) - { - if (isPinvoke) { - return new NetTypeBundle ("System", "IntPtr", false, ct.IsReference, EntityType.None); - } else { - var en = TypeDatabase.EntityForSwiftName (ct.ClassName); - if (en != null) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, ct.IsReference, en.EntityType); - } else { - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 9, $"Unable to find swift class '{ct.ClassName.ToFullyQualifiedName ()}'."); - } - } - } - - NetTypeBundle ToProtocol (SwiftProtocolListType lt, bool isPinvoke) - { - if (lt.Protocols.Count > 1) { - return ToProtocols (lt, isPinvoke); - } - return ToProtocol (lt.Protocols [0], isPinvoke); - } - - NetTypeBundle ToProtocols (SwiftProtocolListType lt, bool isPinvoke) - { - if (!isPinvoke) - throw new NotImplementedException ("If you're not doing a PInvoke, this has to be handled specially"); - return new NetTypeBundle ("SwiftRuntimeLibrary", $"SwiftExistentialContainer{lt.Protocols.Count}", false, true, EntityType.ProtocolList); - } - - NetTypeBundle ToProtocol (SwiftClassType proto, bool isPinvoke) - { - var en = GetEntityForSwiftClassName (proto.ClassName.ToFullyQualifiedName (true)); - if (!en.Type.IsObjC) { - if (isPinvoke) { - return new NetTypeBundle ("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, isPinvoke || proto.IsReference, - EntityType.None); - } - return ToClass (proto, false); - } else { - return ToClass (proto, isPinvoke); - } - } - - NetTypeBundle ToGenericReference (SwiftGenericArgReferenceType st, bool isPinvoke) - { - if (isPinvoke) { - return NetTypeBundle.IntPtr; - } else { - return new NetTypeBundle (st.Depth, st.Index); - } - } - - NetTypeBundle ToClosure (SwiftBaseFunctionType ft, bool isPinvoke, bool isReturnValue) - { - if (isPinvoke) { - return new NetTypeBundle ("SwiftRuntimeLibrary", - isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", - false, false, EntityType.Closure); - } else { - var arguments = ft.EachParameter.Select (parm => MapType (parm, false)).ToList (); - - string delegateName = "Action"; - if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) { - var returnBundle = MapType (ft.ReturnType, false, true); - arguments.Add (returnBundle); - delegateName = "Func"; - } - - if (arguments.Count == 0) - return new NetTypeBundle ("System", delegateName, false, false, EntityType.Closure); - else - return new NetTypeBundle ("System", delegateName, EntityType.Closure, false, arguments); - } - } - - NetTypeBundle ToBoundGeneric (SwiftBoundGenericType gt, bool isPinvoke) - { - var ct = gt.BaseType as SwiftClassType; - if (ct != null && IsSwiftPointerType (ct.ClassName.ToFullyQualifiedName (true))) { - if (gt.BoundTypes [0] is SwiftClassType boundType) { - var entity = GetEntityForSwiftClassName (boundType.ClassName.ToFullyQualifiedName (true)); - if (entity != null && entity.IsObjCStruct) - return MapType (boundType, isPinvoke); - } - return new NetTypeBundle ("System", "IntPtr", false, gt.IsReference, EntityType.None); - } - - if (isPinvoke) { - return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - } - - var baseType = MapType (ct, false); - var genericTypes = gt.BoundTypes.Select (bt => MapType (bt, false)); - return new NetTypeBundle (baseType.NameSpace, baseType.Type, baseType.Entity, baseType.IsReference, genericTypes); - } - - NetTypeBundle ToStruct (SwiftClassType st, bool isPinvoke) - { - var en = TypeDatabase.EntityForSwiftName (st.ClassName); - if (en != null) { - if (isPinvoke && !SwiftType.IsStructScalar (st)) { - if (en.Type.IsObjC) { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } else { - return NetTypeBundle.IntPtr; - } - } else { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); - } - } else { - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 10, $"Unable to find swift struct '{st.ClassName.ToFullyQualifiedName ()}'."); - } - } - - NetTypeBundle ToEnum (SwiftClassType st, bool isPinvoke, bool isReturnValue) - { - var en = TypeDatabase.EntityForSwiftName (st.ClassName); - if (en == null) { - throw ErrorHelper.CreateError (ReflectorError.kTypeMapBase + 11, $"Unable to find swift enum '{st.ClassName.ToFullyQualifiedName ()}'"); - } - if (en.EntityType == EntityType.TrivialEnum) { - return ToTrivialEnumType (en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, st.IsReference); - } else { - if (isPinvoke) { - return NetTypeBundle.IntPtr; - } else { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); - } - } - } - - public bool TargetPlatformIs64Bit { get; private set; } - - public int MachinePointerSize { get { return TargetPlatformIs64Bit ? 8 : 4; } } - - - bool MustForcePassByReference (Entity en) - { - if (en == null) - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 4, "Null entity."); - // can't big structs, non-blitable structs, or plain enums - if (en.EntityType == EntityType.Scalar) - return false; - return en.IsStructOrEnum || (en.EntityType == EntityType.Protocol && !en.IsObjCProtocol); - } - - public bool MustForcePassByReference (TypeDeclaration decl) - { - var en = TypeDatabase.EntityForSwiftName (decl.ToFullyQualifiedName ()); - if (en == null) - return false; - return MustForcePassByReference (en); - } - - public bool MustForcePassByReference (SwiftType st) - { - if (st is SwiftUnboundGenericType) - return true; - if (st is SwiftGenericArgReferenceType) - return true; - if (st is SwiftBaseFunctionType) - return false; - var protList = st as SwiftProtocolListType; - if (protList != null) { - if (protList.Protocols.Count > 1) - return true; - return MustForcePassByReference (protList.Protocols [0]); - } - var classType = st as SwiftClassType; - if (classType == null) { - SwiftTupleType tuple = st as SwiftTupleType; - if (tuple != null) { - return tuple.Contents.Count > 0; - } - SwiftBuiltInType bit = st as SwiftBuiltInType; - if (bit != null) { - return false; - } - SwiftBoundGenericType bgt = st as SwiftBoundGenericType; - if (bgt == null) - throw new NotImplementedException (); - classType = bgt.BaseType as SwiftClassType; - } - - var en = TypeDatabase.EntityForSwiftName (classType.ClassName); - if (en == null) { - if (!classType.IsClass) { - var module = classType.ClassName.Module.Name; - return !(classType.IsEnum && (module == "__C" || module == "__ObjC")); - } - return false; - } - return MustForcePassByReference (en); - } - - public bool MustForcePassByReference (BaseDeclaration context, TypeSpec sp) - { - if (sp.IsEmptyTuple) - return false; - if (sp is TupleTypeSpec tuple) - return tuple.Elements.Count > 1; - if (sp is ClosureTypeSpec) - return false; - if (sp is ProtocolListTypeSpec protolist) { - if (protolist.Protocols.Count > 1) - return true; - return MustForcePassByReference (context, protolist.Protocols.ElementAt (0).Key); - } - if (context.IsTypeSpecGeneric (sp) && context.IsTypeSpecGenericReference (sp)) - return true; - if (context.IsProtocolWithAssociatedTypesFullPath (sp as NamedTypeSpec, this)) - return true; - if (sp.IsDynamicSelf) - return true; - var en = GetEntityForTypeSpec (sp); - if (en == null) - return false; - if (sp.IsUnboundGeneric (context, this)) - return en.EntityType != EntityType.Class; - return MustForcePassByReference (en); - } - - public static bool IsSwiftPointerType (string fullTypeName) - { - return fullTypeName == "Swift.UnsafePointer" || fullTypeName == "Swift.UnsafeMutablePointer" - || fullTypeName == "Swift.UnsafeRawPointer" || fullTypeName == "Swift.UnsafeMutableRawPointer"; - } - - static NetTypeBundle ToTrivialEnumType (Entity en, EnumDeclaration decl, bool isPinvoke, bool isReturnValue, bool isReference) - { - if (decl.HasRawType) { - if (decl.RawTypeName == "Swift.Int" || decl.RawTypeName == "Swift.UInt") { - return new NetTypeBundle ("System", decl.RawTypeName == "Swift.Int" ? "nint" : "nuint", false, false, EntityType.None); - } else { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); - } - } else { - if (isPinvoke) { - if (isReturnValue) { - var enType = en.Type as EnumDeclaration; - if (enType.IsTrivial && !enType.HasRawType) { - if (enType.Elements.Count < 256) - return new NetTypeBundle ("System", "byte", false, false, EntityType.None); - else if (enType.Elements.Count < 65536) { - return new NetTypeBundle ("System", "ushort", false, false, EntityType.None); - } - } - } - return new NetTypeBundle ("System", "IntPtr", false, false, EntityType.None); - } else { - return new NetTypeBundle (en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); - } - } - } - } +namespace SwiftReflector.TypeMapping +{ + public class TypeMapper + { + public TypeDatabase TypeDatabase { get; private set; } + UnicodeMapper unicodeMapper; + HashSet loadedFiles = new HashSet(); + + public TypeMapper(List typeDatabasePaths, UnicodeMapper unicodeMapper) + { + TypeDatabase = new TypeDatabase(); + this.unicodeMapper = unicodeMapper; + } + + public void AddTypeDatabase(string fileName) + { + if (loadedFiles.Contains(fileName)) + return; + loadedFiles.Add(fileName); + var errors = TypeDatabase.Read(fileName); + if (errors.AnyErrors) + throw new AggregateException(errors.Errors.Select((v) => v.Exception)); + } + + DotNetName PreRegisterEntityName(string swiftClassName, EntityType entityKind) + { + + var en = TypeDatabase.EntityForSwiftName(swiftClassName); + if (en != null) + return en.GetFullType(); + + + var netClassName = MakeDotNetClassName(swiftClassName, entityKind == EntityType.Protocol); + + en = new Entity + { + SharpNamespace = netClassName.Namespace, + SharpTypeName = netClassName.TypeName, + Type = new ShamDeclaration(swiftClassName, entityKind), + EntityType = entityKind + }; + TypeDatabase.Add(en); + return netClassName; + } + + public bool IsRegistered(SwiftClassName cl) + { + return TypeDatabase.Contains(cl); + } + + public bool IsRegistered(string fullyQualifiedName) + { + return TypeDatabase.Contains(fullyQualifiedName); + } + + public DotNetName PreRegisterEntityName(SwiftClassName cl) + { + var swiftClassName = cl.ToFullyQualifiedName(); + var entity = EntityType.None; + // FIXME + if (cl.IsClass) + entity = EntityType.Class; + else if (cl.IsStruct) + entity = EntityType.Struct; + else if (cl.IsEnum) + entity = EntityType.Enum; + else + { + throw new NotImplementedException(); + } + return PreRegisterEntityName(swiftClassName, entity); + } + + public DotNetName GetDotNetNameForSwiftClassName(SwiftClassName cl) + { + return TypeDatabase.EntityForSwiftName(cl).GetFullType(); + } + + public DotNetName GetDotNetNameForTypeSpec(TypeSpec spec) + { + var named = spec as NamedTypeSpec; + if (named == null) + return null; + return GetDotNetNameForSwiftClassName(named.Name); + } + + public DotNetName GetDotNetNameForSwiftClassName(string fullyQualifiedName) + { + var entity = TypeDatabase.EntityForSwiftName(fullyQualifiedName); + if (entity == null) + return null; + return entity.GetFullType(); + } + + public EntityType GetEntityTypeForSwiftClassName(string fullyQualifiedName) + { + var ent = TypeDatabase.EntityForSwiftName(fullyQualifiedName); + return ent != null ? ent.EntityType : EntityType.None; + } + + public EntityType GetEntityTypeForDotNetName(DotNetName netClassName) + { + var ent = TypeDatabase.EntityForDotNetName(netClassName); + return ent != null ? ent.EntityType : EntityType.None; + } + + public Entity GetEntityForSwiftClassName(string fullyQualifiedName) + { + return TypeDatabase.EntityForSwiftName(fullyQualifiedName); + } + + public Entity TryGetEntityForSwiftClassName(string fullyQualifiedName) + { + return TypeDatabase.TryGetEntityForSwiftName(fullyQualifiedName); + } + + public Entity GetEntityForTypeSpec(TypeSpec spec) + { + if (spec == null) + return null; + var ns = spec as NamedTypeSpec; + if (ns == null || spec.IsDynamicSelf) + return null; + return GetEntityForSwiftClassName(ns.Name); + } + + public EntityType GetEntityTypeForTypeSpec(TypeSpec spec) + { + if (spec == null) + return EntityType.None; + + if (spec is NamedTypeSpec) + { + if (spec.IsDynamicSelf) + return EntityType.DynamicSelf; + var ent = GetEntityForTypeSpec(spec); + return ent != null ? ent.EntityType : EntityType.None; + } + if (spec is TupleTypeSpec) + { + return EntityType.Tuple; + } + if (spec is ClosureTypeSpec) + { + return EntityType.Closure; + } + if (spec is ProtocolListTypeSpec) + { + return EntityType.ProtocolList; + } + throw new ArgumentOutOfRangeException(spec.GetType().Name); + } + + public Entity GetEntityForDotNetName(DotNetName netName) + { + return TypeDatabase.EntityForDotNetName(netName); + } + + public DotNetName RegisterClass(TypeDeclaration t) + { + t = t.MakeUnrooted(); + var isProtocol = false; + // FIXME + var entity = EntityType.None; + // don't reorder - until I change this, ProtocolDeclaration extends from ClassDeclaration + if (t is ProtocolDeclaration) + { + entity = EntityType.Protocol; + isProtocol = true; + } + else if (t is ClassDeclaration) + { + entity = EntityType.Class; + } + else if (t is StructDeclaration) + { + entity = EntityType.Struct; + } + else + { + EnumDeclaration eDecl = t as EnumDeclaration; + entity = (eDecl.IsTrivial || (eDecl.IsIntegral && eDecl.IsHomogenous && eDecl.Inheritance.Count == 0)) ? EntityType.TrivialEnum : EntityType.Enum; + } + var sharpName = MakeDotNetClassName(t.ToFullyQualifiedName(true), isProtocol); + + var en = new Entity + { + SharpNamespace = sharpName.Namespace, + SharpTypeName = sharpName.TypeName, + Type = t, + EntityType = entity + }; + + TypeDatabase.Update(en); + return sharpName; + } + + public IEnumerable RegisterClasses(IEnumerable decl) + { + var allReg = new List(); + foreach (TypeDeclaration cl in decl) + { + DotNetName reg = RegisterClass(cl); + allReg.Add(reg); + } + return allReg; + } + + DotNetName MakeDotNetClassName(string fullyQualifiedName, bool isProtocol) + { + var parts = fullyQualifiedName.Split('.'); + var sb = new StringBuilder(); + var namesp = MapModuleToNamespace(parts[0]); + for (int i = 1; i < parts.Length; i++) + { + if (i > 1) + sb.Append('.'); + if (isProtocol && i == parts.Length - 1) + sb.Append('I'); + sb.Append(SanitizeIdentifier(parts[i])); + } + return new DotNetName(namesp, sb.ToString()); + } + + string MakeDotNetClassName(SwiftClassName name) + { + var sb = new StringBuilder(); + var namesp = MapModuleToNamespace(name.Module); + sb.Append(namesp); + foreach (SwiftName sn in name.NestingNames) + { + sb.Append('.'); + sb.Append(SanitizeIdentifier(sn.Name)); + } + return sb.ToString(); + } + + public string MapModuleToNamespace(SwiftName name) + { + string finalName = null; + finalName = UserModuleMap(name); + if (finalName == null) + { + finalName = SanitizeIdentifier(name.Name); + } + return finalName; + } + + public string MapModuleToNamespace(string name) + { + string finalName = null; + finalName = UserModuleMap(name); + if (finalName == null) + { + finalName = SanitizeIdentifier(name); + } + return finalName; + } + + + string UserModuleMap(SwiftName name) + { + return null; + } + + string UserModuleMap(string name) + { + return null; + } + + static UnicodeCategory[] validStarts = { + UnicodeCategory.UppercaseLetter, + UnicodeCategory.LowercaseLetter, + UnicodeCategory.TitlecaseLetter, + UnicodeCategory.ModifierLetter, + UnicodeCategory.OtherLetter, + UnicodeCategory.LetterNumber + }; + + static bool ValidIdentifierStart(UnicodeCategory cat) + { + return validStarts.Contains(cat); + } + + static UnicodeCategory[] validContent = { + UnicodeCategory.DecimalDigitNumber, + UnicodeCategory.ConnectorPunctuation, + UnicodeCategory.Format + }; + + static bool ValidIdentifierContent(UnicodeCategory cat) + { + return ValidIdentifierStart(cat) || validContent.Contains(cat); + } + + static bool IsValidIdentifier(int position, UnicodeCategory cat) + { + if (position == 0) + return ValidIdentifierStart(cat); + else + return ValidIdentifierContent(cat); + } + + static bool IsHighUnicode(string s) + { + // Steve says: this is arbitrary, but it solves an issue + // with mcs and csc not liking certain Ll and Lu class + // unicode characters (for now). + // Open issue: https://github.com/dotnet/roslyn/issues/27986 + var encoding = Encoding.UTF32; + var bytes = encoding.GetBytes(s); + var utf32Value = BitConverter.ToUInt32(bytes, 0); + return utf32Value > 0xffff; + } + + public string SanitizeIdentifier(string name) + { + var sb = new StringBuilder(); + + var characterEnum = StringInfo.GetTextElementEnumerator(name); + while (characterEnum.MoveNext()) + { + string c = characterEnum.GetTextElement(); + int i = characterEnum.ElementIndex; + + var cat = CharUnicodeInfo.GetUnicodeCategory(name, i); + + if (IsValidIdentifier(i, cat) && !IsHighUnicode(c)) + sb.Append(i == 0 && cat == UnicodeCategory.LowercaseLetter ? c.ToUpper() : c); + else + sb.Append(unicodeMapper.MapToUnicodeName(c)); + } + + if (CSKeywords.IsKeyword(sb.ToString())) + sb.Append('_'); + return sb.ToString(); + } + + static string ComeUpWithAName(string given, string typeName, int index) + { + if (String.IsNullOrEmpty(given)) + { + return String.Format("{0}{1}", Char.ToLower(typeName[0]), index); + } + else + { + return given; + } + } + + static NetParam ToNamedParam(ParameterItem st, NetTypeBundle bundle, int index) + { + string targetName = ComeUpWithAName(st.NameIsRequired ? st.PublicName : st.PrivateName, bundle.Type, index); + return new NetParam(targetName, bundle); + } + + static bool IsUnique(NetParam p, List pl, int startPoint) + { + for (int i = startPoint; i < pl.Count; i++) + { + if (p.Name == pl[i].Name) + return false; + } + return true; + } + + static NetParam Uniquify(NetParam p, List pl, int startPoint) + { + while (!IsUnique(p, pl, startPoint) || CSKeywords.IsKeyword(p.Name)) + { + p = new NetParam(p.Name + '0', p.Type); + } + return p; + } + + static List SanitizeParamNames(List parms) + { + List outlist = new List(); + bool changed = false; + do + { + changed = false; + outlist = new List(); + for (int i = 0; i < parms.Count; i++) + { + NetParam q = Uniquify(parms[i], parms, i + 1); + changed = q.Name != parms[i].Name; + outlist.Add(q); + } + if (changed) + parms = outlist; + } while (changed); + return outlist; + } + + public List GetLineage(SwiftUncurriedFunctionType uft) + { + var lineage = new List(); + if (uft != null) + { + var theClass = uft.UncurriedParameter as SwiftClassType; + if (theClass == null) + { + var meta = uft.UncurriedParameter as SwiftMetaClassType; + if (meta == null) + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 17, $"Expected a SwiftClassType or a SwiftMetaClassType as the uncurried parameter in a function, but got {uft.UncurriedParameter.GetType().Name}."); + theClass = meta.Class; + } + var sb = new StringBuilder().Append(theClass.ClassName.Module.Name); + foreach (SwiftName name in theClass.ClassName.NestingNames) + { + sb.Append('.').Append(name.Name); + lineage.Add(sb.ToString()); + } + } + return lineage; + } + + internal object GetEntityForTypeSpec(object inheritsTypeSpec) + { + throw new NotImplementedException(); + } + + + NetTypeBundle RecastToReference(BaseDeclaration typeContext, NetTypeBundle netBundle, TypeSpec theElem, bool structsAndEnumsAreAlwaysRefs) + { + if (typeContext.IsTypeSpecGenericReference(theElem) || typeContext.IsProtocolWithAssociatedTypesFullPath(theElem as NamedTypeSpec, this)) + return netBundle; + if (theElem is ClosureTypeSpec) + return netBundle; + if (theElem is ProtocolListTypeSpec) + return new NetTypeBundle(netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); + var entity = GetEntityForTypeSpec(theElem); + if (entity != null && (entity.IsObjCStruct || entity.IsObjCEnum) && netBundle.IsReference) + return netBundle; + if (theElem.IsInOut && netBundle.Entity != EntityType.Struct) + return netBundle; + + var objcStructType = ObjCStructOrEnumReferenceType(typeContext, theElem as NamedTypeSpec); + if (objcStructType != null) + { + return MapType(typeContext, objcStructType, true); + } + var isStructOrEnum = netBundle.Entity == EntityType.Struct || netBundle.Entity == EntityType.Enum; + if (isStructOrEnum) + { + if (MustForcePassByReference(typeContext, theElem) || netBundle.Entity == EntityType.Enum || structsAndEnumsAreAlwaysRefs) + { + return new NetTypeBundle("System", "IntPtr", netBundle.IsScalar, false, netBundle.Entity); + } + } + else if (entity != null && entity.EntityType == EntityType.Protocol && !entity.IsObjCProtocol) + { + return new NetTypeBundle(netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); + } + return netBundle; + } + + + NetParam MapParameterItem(BaseDeclaration context, ParameterItem parameter, int index, bool isPinvoke, bool structsAndEnumsAreAlwaysRefs) + { + var theType = parameter.TypeSpec; //parameter.IsInOut && !parameter.TypeSpec.IsInOut ? parameter.TypeSpec.WithInOutSet () : parameter.TypeSpec; + var t = MapType(context, theType, isPinvoke); + if (isPinvoke) + { + t = RecastToReference(context, t, theType, structsAndEnumsAreAlwaysRefs); + } + return ToNamedParam(parameter, t, index); + } + + public List MapParameterList(BaseDeclaration context, List st, bool isPinvoke, + bool structsAndEnumsAreAlwaysRefs, CSGenericTypeDeclarationCollection extraProtocolTypes, + CSGenericConstraintCollection extraProtocolContstraints, CSUsingPackages use) + { + var parms = new List(); + for (int i = 0; i < st.Count; i++) + { + if (st[i].TypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) + { + var genprotoName = new CSIdentifier($"TProto{i}"); + extraProtocolTypes.Add(new CSGenericTypeDeclaration(genprotoName)); + extraProtocolContstraints.Add(new CSGenericConstraint(genprotoName, ToConstraintIDs(context, plitem.Protocols.Keys, isPinvoke))); + var netBundle = new NetTypeBundle("", genprotoName.Name, false, st[i].IsInOut, EntityType.ProtocolList); + + parms.Add(ToNamedParam(st[i], netBundle, i)); + } + else + { + var entity = !context.IsTypeSpecGeneric(st[i].TypeSpec) ? GetEntityForTypeSpec(st[i].TypeSpec) : null; + if (entity != null && entity.EntityType == EntityType.Protocol && !isPinvoke) + { + var proto = entity.Type as ProtocolDeclaration; + // if (proto.HasDynamicSelf) { + // extraProtocolTypes.Add (new CSGenericTypeDeclaration (BindingsCompiler.kGenericSelf)); + // var csProtoBundle = MapType (context, st [i].TypeSpec, isPinvoke); + // var csType = csProtoBundle.ToCSType (use); + // extraProtocolContstraints.Add (new CSGenericConstraint (BindingsCompiler.kGenericSelf, new CSIdentifier (csType.ToString ()))); + // } + } + + parms.Add(MapParameterItem(context, st[i], i, isPinvoke, structsAndEnumsAreAlwaysRefs)); + } + } + return SanitizeParamNames(parms); + } + + public IEnumerable ToConstraintIDs(BaseDeclaration context, IEnumerable types, bool isPinvoke) + { + foreach (var ns in types) + { + var cstype = MapType(context, ns, isPinvoke); + yield return new CSIdentifier(cstype.ToString()); + } + } + + public static bool IsCompoundProtocolListType(SwiftType st) + { + return st is SwiftProtocolListType pt && pt.Protocols.Count > 1; + } + + public static bool IsCompoundProtocolListType(TypeSpec sp) + { + return sp is ProtocolListTypeSpec pl && pl.Protocols.Count > 1; + } + + public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = false) + { + if (IsCompoundProtocolListType(st) && !isPinvoke) + throw new NotImplementedException("Check for a protocol list type first because you need to promote the method to a generic"); + switch (st.Type) + { + case CoreCompoundType.Scalar: + return ToScalar((SwiftBuiltInType)st); + case CoreCompoundType.Tuple: + return ToTuple((SwiftTupleType)st, isPinvoke); + case CoreCompoundType.MetaClass: + return ToMetaClass((SwiftMetaClassType)st); + case CoreCompoundType.Class: + if (st.IsStruct) + return ToStruct((SwiftClassType)st, isPinvoke); + else if (st.IsClass) + return ToClass((SwiftClassType)st, isPinvoke); + else if (st.IsEnum) + return ToEnum((SwiftClassType)st, isPinvoke, isReturnValue); + else if (st.IsProtocol) + return ToProtocol((SwiftClassType)st, isPinvoke); + else + throw new NotImplementedException(); + case CoreCompoundType.ProtocolList: + return ToProtocol((SwiftProtocolListType)st, isPinvoke); + case CoreCompoundType.BoundGeneric: + return ToBoundGeneric((SwiftBoundGenericType)st, isPinvoke); + case CoreCompoundType.GenericReference: + return ToGenericReference((SwiftGenericArgReferenceType)st, isPinvoke); + case CoreCompoundType.Function: + return ToClosure((SwiftBaseFunctionType)st, isPinvoke, isReturnValue); + default: + throw new NotImplementedException(); + } + } + + public NetTypeBundle MapType(BaseDeclaration context, TypeSpec spec, bool isPinvoke, bool isReturnValue = false, + Tuple selfDepthIndex = null) + { + if (IsCompoundProtocolListType(spec) && !isPinvoke) + throw new NotImplementedException("Check for a protocol list type first because you need to promote the method to a generic"); + switch (spec.Kind) + { + case TypeSpecKind.Named: + var named = (NamedTypeSpec)spec; + if (IsScalar(named.Name)) + { + return ToScalar(named.Name, spec.IsInOut); + } + if (context.IsProtocolWithAssociatedTypesFullPath(named, this)) + { + if (isPinvoke) + { + return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + } + else + { + var assocType = context.AssociatedTypeDeclarationFromGenericWithFullPath(named, this); + var owningProtocol = context.OwningProtocolFromGenericWithFullPath(named, this); + return new NetTypeBundle(owningProtocol, assocType, false); + } + } + else if (context.IsEqualityConstrainedByAssociatedType(named, this)) + { + if (isPinvoke) + { + return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + } + else + { + var assocType = context.AssociatedTypeDeclarationFromConstrainedGeneric(named, this); + var owningProtocol = context.OwningProtocolFromConstrainedGeneric(named, this); + return new NetTypeBundle(owningProtocol, assocType, false); + } + } + else if (context.IsTypeSpecGeneric(spec) && (!spec.ContainsGenericParameters || isPinvoke)) + { + if (context.IsTypeSpecGenericMetatypeReference(spec)) + { + return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, spec.IsInOut, EntityType.None); + } + else + { + if (isPinvoke) + { + var isPAT = context.GetConstrainedProtocolWithAssociatedType(named, this) != null; + var isInOut = isPAT ? false : named.IsInOut; + return new NetTypeBundle("System", "IntPtr", false, isInOut, EntityType.None); + } + else + { + var depthIndex = context.GetGenericDepthAndIndex(spec); + return new NetTypeBundle(depthIndex.Item1, depthIndex.Item2); + } + } + } + else if (context.IsTypeSpecAssociatedType(named)) + { + if (isPinvoke) + { + return new NetTypeBundle("System", "IntPtr", false, named.IsInOut, EntityType.None); + } + else + { + if (named.ContainsGenericParameters) + { + var en = TypeDatabase.EntityForSwiftName(named.Name); + var retval = new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + foreach (var gen in named.GenericParameters) + { + var genNtb = MapType(context, gen, isPinvoke, isReturnValue); + retval.GenericTypes.Add(genNtb); + } + return retval; + } + else + { + var assocType = context.AssociatedTypeDeclarationFromNamedTypeSpec(named); + return new NetTypeBundle(context.AsProtocolOrParentAsProtocol(), assocType, named.IsInOut); + } + } + } + // else if (named.Name == "Self") { + // if (isPinvoke) { + // return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); + // } else { + // return new NetTypeBundle (BindingsCompiler.kGenericSelfName, named.IsInOut); + // } + // } + else + { + Entity en = TypeDatabase.EntityForSwiftName(named.Name); + if (en != null) + { + if (isPinvoke) + { + switch (en.EntityType) + { + case EntityType.Class: + case EntityType.Enum: + case EntityType.Tuple: + if (en.IsObjCEnum) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); + case EntityType.TrivialEnum: + return ToTrivialEnumType(en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, spec.IsInOut); + case EntityType.Protocol: + if (en.IsObjCProtocol) + { + return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); + } + else + { + if (spec is ProtocolListTypeSpec protocolList) + { + var container = $"SwiftExistentialContainer{protocolList.Protocols.Count}"; + return new NetTypeBundle("SwiftRuntimeLibrary", container, false, true, EntityType.None); + } + else + { + return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, true, + EntityType.None); + } + } + case EntityType.Struct: + var protocolListRef = GetBoundProtocolListType(named); + if (protocolListRef != null) + { + var container = $"SwiftExistentialContainer{protocolListRef.Protocols.Count}"; + return new NetTypeBundle("SwiftRuntimeLibrary", container, false, true, EntityType.None); + + } + en = MapToObjCStructOrEnumReference(context, named) ?? en; + if (en.IsObjCStruct || en.IsObjCEnum) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + en = MapToScalarReference(context, named) ?? en; + if (en.EntityType == EntityType.Scalar) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + else + { + return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); + } + case EntityType.Scalar: + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + default: + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 21, "Can't happen - shouldn't ever get to this case in type mapping."); + } + } + else + { + var retval = new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); + if (en.EntityType == EntityType.Protocol && en.Type is ProtocolDeclaration proto) + { + // if (proto.HasDynamicSelf) { + // if (selfDepthIndex != null) { + // retval.GenericTypes.Add (new NetTypeBundle (selfDepthIndex.Item1, selfDepthIndex.Item2)); + // } else { + // retval.GenericTypes.Add (new NetTypeBundle (BindingsCompiler.kGenericSelfName, spec.IsInOut)); + // } + // } + foreach (var assoc in proto.AssociatedTypes) + { + var genMap = new NetTypeBundle(proto, assoc, spec.IsInOut); + retval.GenericTypes.Add(genMap); + } + } + else + { + foreach (var gen in spec.GenericParameters) + { + retval.GenericTypes.Add(MapType(context, gen, isPinvoke)); + } + } + return retval; + } + } + else + { + if (isPinvoke) + { + var namedSpec = spec as NamedTypeSpec; + if (namedSpec != null) + { + if (TypeMapper.IsSwiftPointerType(namedSpec.Name)) + { + return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + } + } + } + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 0, $"Unable to find C# reference for swift class '{spec.ToString()}'."); + } + } + case TypeSpecKind.Tuple: + var tuple = (TupleTypeSpec)spec; + if (tuple.Elements.Count == 0) + return NetTypeBundle.Void; + var tupTypes = tuple.Elements.Select(ts => MapType(context, ts, isPinvoke)).ToList(); + return new NetTypeBundle(tupTypes, tuple.IsInOut); + case TypeSpecKind.Closure: + if (isPinvoke) + { + return new NetTypeBundle("SwiftRuntimeLibrary", isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", false, false, EntityType.Closure); + } + else + { + ClosureTypeSpec ft = spec as ClosureTypeSpec; + var throws = !isPinvoke && ft.Throws; + var arguments = ft.EachArgument().Select(parm => MapType(context, parm, false)).ToList(); + + string delegateName = "Action"; + if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) + { + var returnBundle = MapType(context, ft.ReturnType, false, true); + arguments.Add(returnBundle); + delegateName = "Func"; + } + + if (arguments.Count == 0) + return new NetTypeBundle("System", delegateName, false, false, EntityType.Closure, swiftThrows: throws); + else + return new NetTypeBundle("System", delegateName, EntityType.Closure, false, arguments, swiftThrows: throws); + } + case TypeSpecKind.ProtocolList: + var pl = (ProtocolListTypeSpec)spec; + return new NetTypeBundle("SwiftRuntimeLibrary", $"SwiftExistentialContainer{pl.Protocols.Count}", + false, true, EntityType.None); + + default: + throw new NotImplementedException(); + } + } + + bool IsProtocolListTypeReference(BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundProtocolListType(spec); + + return boundType != null; + } + + Entity MapToScalarReference(BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType(spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference(boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath(boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName(boundType.Name); + return entity.EntityType == EntityType.Scalar || SwiftType.IsStructScalar(boundType.Name) ? entity : null; + } + + Entity MapToObjCStructOrEnumReference(BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType(spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference(boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath(boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName(boundType.Name); + return entity.IsObjCStruct || entity.IsObjCEnum ? entity : null; + } + + TypeSpec ObjCStructOrEnumReferenceType(BaseDeclaration context, NamedTypeSpec spec) + { + var boundType = GetBoundPointerType(spec); + if (boundType == null) + return null; + if (context.IsTypeSpecGenericReference(boundType)) + return null; + if (context.IsProtocolWithAssociatedTypesFullPath(boundType, this)) + return null; + var entity = TypeDatabase.EntityForSwiftName(boundType.Name); + return entity.IsObjCStruct || entity.IsObjCEnum ? boundType : null; + } + + static NamedTypeSpec GetBoundPointerType(NamedTypeSpec spec) + { + if (spec == null) + return null; + if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") + return null; + var boundType = spec.GenericParameters[0] as NamedTypeSpec; + return boundType; + } + + static ProtocolListTypeSpec GetBoundProtocolListType(NamedTypeSpec spec) + { + if (spec == null) + return null; + if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") + return null; + return spec.GenericParameters[0] as ProtocolListTypeSpec; + } + + NetTypeBundle ToTuple(SwiftTupleType tt, bool isPinvoke) + { + if (tt.IsEmpty) + return NetTypeBundle.Void; + if (tt.Contents.Count == 1) + { + return MapType(tt.Contents[0], isPinvoke); + } + var lt = tt.Contents.Select(t => MapType(t, isPinvoke)).ToList(); + return new NetTypeBundle(lt, tt.IsReference); + } + + NetTypeBundle ToScalar(SwiftBuiltInType bit) + { + switch (bit.BuiltInType) + { + case CoreBuiltInType.Bool: + return ToScalar("Swift.Bool", bit.IsReference); + case CoreBuiltInType.Double: + return ToScalar("Swift.Double", bit.IsReference); + case CoreBuiltInType.Float: + return ToScalar("Swift.Float", bit.IsReference); + case CoreBuiltInType.Int: + return new NetTypeBundle("System", "nint", true, bit.IsReference, EntityType.Scalar); + case CoreBuiltInType.UInt: + return new NetTypeBundle("System", "nuint", true, bit.IsReference, EntityType.Scalar); + default: + throw new ArgumentOutOfRangeException(nameof(bit)); + } + } + + static string[] scalarNames = new string[] { + "Swift.Bool", + "Swift.Double", + "Swift.Float", + "Swift.Int", + "Swift.UInt", + "Swift.Int8", + "Swift.UInt8", + "Swift.Int16", + "Swift.UInt16", + "Swift.Int32", + "Swift.UInt32", + "Swift.Int64", + "Swift.UInt64" + }; + + static int ScalarIndex(string builtIn) + { + return Array.IndexOf(scalarNames, builtIn); + } + + public static bool IsScalar(string builtIn) + { + return ScalarIndex(Exceptions.ThrowOnNull(builtIn, "builtIn")) >= 0; + } + + public static bool IsScalar(TypeSpec spec) + { + var ns = spec as NamedTypeSpec; + if (ns == null) + return false; + return ScalarIndex(ns.Name) >= 0; + } + + NetTypeBundle ToScalar(string builtIn, bool isReference) + { + int index = ScalarIndex(builtIn); + if (index >= 0) + { + var en = TypeDatabase.EntityForSwiftName(builtIn); + if (en != null) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } + throw new ArgumentOutOfRangeException(nameof(builtIn)); + } + + NetTypeBundle ToMetaClass(SwiftMetaClassType mt) + { + return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, mt.IsReference, EntityType.None); + } + + NetTypeBundle ToClass(SwiftClassType ct, bool isPinvoke) + { + if (isPinvoke) + { + return new NetTypeBundle("System", "IntPtr", false, ct.IsReference, EntityType.None); + } + else + { + var en = TypeDatabase.EntityForSwiftName(ct.ClassName); + if (en != null) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, ct.IsReference, en.EntityType); + } + else + { + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 9, $"Unable to find swift class '{ct.ClassName.ToFullyQualifiedName()}'."); + } + } + } + + NetTypeBundle ToProtocol(SwiftProtocolListType lt, bool isPinvoke) + { + if (lt.Protocols.Count > 1) + { + return ToProtocols(lt, isPinvoke); + } + return ToProtocol(lt.Protocols[0], isPinvoke); + } + + NetTypeBundle ToProtocols(SwiftProtocolListType lt, bool isPinvoke) + { + if (!isPinvoke) + throw new NotImplementedException("If you're not doing a PInvoke, this has to be handled specially"); + return new NetTypeBundle("SwiftRuntimeLibrary", $"SwiftExistentialContainer{lt.Protocols.Count}", false, true, EntityType.ProtocolList); + } + + NetTypeBundle ToProtocol(SwiftClassType proto, bool isPinvoke) + { + var en = GetEntityForSwiftClassName(proto.ClassName.ToFullyQualifiedName(true)); + if (!en.Type.IsObjC) + { + if (isPinvoke) + { + return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, isPinvoke || proto.IsReference, + EntityType.None); + } + return ToClass(proto, false); + } + else + { + return ToClass(proto, isPinvoke); + } + } + + NetTypeBundle ToGenericReference(SwiftGenericArgReferenceType st, bool isPinvoke) + { + if (isPinvoke) + { + return NetTypeBundle.IntPtr; + } + else + { + return new NetTypeBundle(st.Depth, st.Index); + } + } + + NetTypeBundle ToClosure(SwiftBaseFunctionType ft, bool isPinvoke, bool isReturnValue) + { + if (isPinvoke) + { + return new NetTypeBundle("SwiftRuntimeLibrary", + isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", + false, false, EntityType.Closure); + } + else + { + var arguments = ft.EachParameter.Select(parm => MapType(parm, false)).ToList(); + + string delegateName = "Action"; + if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) + { + var returnBundle = MapType(ft.ReturnType, false, true); + arguments.Add(returnBundle); + delegateName = "Func"; + } + + if (arguments.Count == 0) + return new NetTypeBundle("System", delegateName, false, false, EntityType.Closure); + else + return new NetTypeBundle("System", delegateName, EntityType.Closure, false, arguments); + } + } + + NetTypeBundle ToBoundGeneric(SwiftBoundGenericType gt, bool isPinvoke) + { + var ct = gt.BaseType as SwiftClassType; + if (ct != null && IsSwiftPointerType(ct.ClassName.ToFullyQualifiedName(true))) + { + if (gt.BoundTypes[0] is SwiftClassType boundType) + { + var entity = GetEntityForSwiftClassName(boundType.ClassName.ToFullyQualifiedName(true)); + if (entity != null && entity.IsObjCStruct) + return MapType(boundType, isPinvoke); + } + return new NetTypeBundle("System", "IntPtr", false, gt.IsReference, EntityType.None); + } + + if (isPinvoke) + { + return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + } + + var baseType = MapType(ct, false); + var genericTypes = gt.BoundTypes.Select(bt => MapType(bt, false)); + return new NetTypeBundle(baseType.NameSpace, baseType.Type, baseType.Entity, baseType.IsReference, genericTypes); + } + + NetTypeBundle ToStruct(SwiftClassType st, bool isPinvoke) + { + var en = TypeDatabase.EntityForSwiftName(st.ClassName); + if (en != null) + { + if (isPinvoke && !SwiftType.IsStructScalar(st)) + { + if (en.Type.IsObjC) + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); + } + else + { + return NetTypeBundle.IntPtr; + } + } + else + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); + } + } + else + { + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 10, $"Unable to find swift struct '{st.ClassName.ToFullyQualifiedName()}'."); + } + } + + NetTypeBundle ToEnum(SwiftClassType st, bool isPinvoke, bool isReturnValue) + { + var en = TypeDatabase.EntityForSwiftName(st.ClassName); + if (en == null) + { + throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 11, $"Unable to find swift enum '{st.ClassName.ToFullyQualifiedName()}'"); + } + if (en.EntityType == EntityType.TrivialEnum) + { + return ToTrivialEnumType(en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, st.IsReference); + } + else + { + if (isPinvoke) + { + return NetTypeBundle.IntPtr; + } + else + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); + } + } + } + + public bool TargetPlatformIs64Bit { get; private set; } + + public int MachinePointerSize { get { return TargetPlatformIs64Bit ? 8 : 4; } } + + + bool MustForcePassByReference(Entity en) + { + if (en == null) + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 4, "Null entity."); + // can't big structs, non-blitable structs, or plain enums + if (en.EntityType == EntityType.Scalar) + return false; + return en.IsStructOrEnum || (en.EntityType == EntityType.Protocol && !en.IsObjCProtocol); + } + + public bool MustForcePassByReference(TypeDeclaration decl) + { + var en = TypeDatabase.EntityForSwiftName(decl.ToFullyQualifiedName()); + if (en == null) + return false; + return MustForcePassByReference(en); + } + + public bool MustForcePassByReference(SwiftType st) + { + if (st is SwiftUnboundGenericType) + return true; + if (st is SwiftGenericArgReferenceType) + return true; + if (st is SwiftBaseFunctionType) + return false; + var protList = st as SwiftProtocolListType; + if (protList != null) + { + if (protList.Protocols.Count > 1) + return true; + return MustForcePassByReference(protList.Protocols[0]); + } + var classType = st as SwiftClassType; + if (classType == null) + { + SwiftTupleType tuple = st as SwiftTupleType; + if (tuple != null) + { + return tuple.Contents.Count > 0; + } + SwiftBuiltInType bit = st as SwiftBuiltInType; + if (bit != null) + { + return false; + } + SwiftBoundGenericType bgt = st as SwiftBoundGenericType; + if (bgt == null) + throw new NotImplementedException(); + classType = bgt.BaseType as SwiftClassType; + } + + var en = TypeDatabase.EntityForSwiftName(classType.ClassName); + if (en == null) + { + if (!classType.IsClass) + { + var module = classType.ClassName.Module.Name; + return !(classType.IsEnum && (module == "__C" || module == "__ObjC")); + } + return false; + } + return MustForcePassByReference(en); + } + + public bool MustForcePassByReference(BaseDeclaration context, TypeSpec sp) + { + if (sp.IsEmptyTuple) + return false; + if (sp is TupleTypeSpec tuple) + return tuple.Elements.Count > 1; + if (sp is ClosureTypeSpec) + return false; + if (sp is ProtocolListTypeSpec protolist) + { + if (protolist.Protocols.Count > 1) + return true; + return MustForcePassByReference(context, protolist.Protocols.ElementAt(0).Key); + } + if (context.IsTypeSpecGeneric(sp) && context.IsTypeSpecGenericReference(sp)) + return true; + if (context.IsProtocolWithAssociatedTypesFullPath(sp as NamedTypeSpec, this)) + return true; + if (sp.IsDynamicSelf) + return true; + var en = GetEntityForTypeSpec(sp); + if (en == null) + return false; + if (sp.IsUnboundGeneric(context, this)) + return en.EntityType != EntityType.Class; + return MustForcePassByReference(en); + } + + public static bool IsSwiftPointerType(string fullTypeName) + { + return fullTypeName == "Swift.UnsafePointer" || fullTypeName == "Swift.UnsafeMutablePointer" + || fullTypeName == "Swift.UnsafeRawPointer" || fullTypeName == "Swift.UnsafeMutableRawPointer"; + } + + static NetTypeBundle ToTrivialEnumType(Entity en, EnumDeclaration decl, bool isPinvoke, bool isReturnValue, bool isReference) + { + if (decl.HasRawType) + { + if (decl.RawTypeName == "Swift.Int" || decl.RawTypeName == "Swift.UInt") + { + return new NetTypeBundle("System", decl.RawTypeName == "Swift.Int" ? "nint" : "nuint", false, false, EntityType.None); + } + else + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } + else + { + if (isPinvoke) + { + if (isReturnValue) + { + var enType = en.Type as EnumDeclaration; + if (enType.IsTrivial && !enType.HasRawType) + { + if (enType.Elements.Count < 256) + return new NetTypeBundle("System", "byte", false, false, EntityType.None); + else if (enType.Elements.Count < 65536) + { + return new NetTypeBundle("System", "ushort", false, false, EntityType.None); + } + } + } + return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); + } + else + { + return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); + } + } + } + } } diff --git a/src/SwiftReflector/UnicodeMapper.cs b/src/SwiftReflector/UnicodeMapper.cs index 8e249ff34e6f..67405cf2b435 100644 --- a/src/SwiftReflector/UnicodeMapper.cs +++ b/src/SwiftReflector/UnicodeMapper.cs @@ -8,114 +8,117 @@ using System.Text; using System.Xml.Linq; -namespace SwiftReflector { - public sealed class UnicodeMapper { +namespace SwiftReflector +{ + public sealed class UnicodeMapper + { - static Dictionary DefaultMapping = new Dictionary { - { "\x03b1", "Alpha" }, - { "\x03b2", "Beta" }, - { "\x03b3", "Gamma" }, - { "\x03b4", "Delta" }, - { "\x03b5", "Epsilon" }, - { "𝑒", "LittleEpsilon"}, - { "Π", "BigPi"}, - { "\x03c0", "Pi" }, - { "𝝉", "Tau"}, - { "\x03c4", "Tau" }, - { "\x00ac", "Not" }, - { "\x2227", "And" }, - { "\x2228", "Or" }, - { "\x22bb", "Xor" }, - { "\x2295", "CirclePlus" }, - { "\x21ae", "NotLeftRightArrow" }, - { "\x2262", "NotIdentical" }, - { "\x22bc", "Nand" }, - { "\x2191", "UpArrow" }, - { "\x22bd", "Nor" }, - { "\x2193", "DownArrow" }, - { "\x22a6", "Assertion" }, - { "\x00f7", "Division" }, - { "\x00d7", "Multiplication" }, - { "\x221a", "SquareRoot" }, - { "\x221b", "CubeRoot" }, - { "\x00b1", "PlusOrMinus" }, - { "\x2213", "MinusOrPlus" }, - { "\x2224", "DoesNotDivide" }, - { "\x2208", "ElementOf" }, - { "\x220c", "NotElementOf" }, - { "\x2229", "Intersection" }, - { "\x222a", "Union" }, - { "\x2286", "Subset" }, - { "\x2282", "ProperSubset" }, - { "\x2284", "NotSubset" }, - { "\x2287", "Superset" }, - { "\x2283", "ProperSuperset" }, - { "\x2285", "NotSuperset" }, - { "\x2264", "LessThanOrEqualTo" }, - { "\x2265", "GreaterThanOrEqualTo" }, - { "\x226c", "Between" }, - { "\x2248", "Approximates" }, - { "\x2218", "Ring" }, - }; + static Dictionary DefaultMapping = new Dictionary { + { "\x03b1", "Alpha" }, + { "\x03b2", "Beta" }, + { "\x03b3", "Gamma" }, + { "\x03b4", "Delta" }, + { "\x03b5", "Epsilon" }, + { "𝑒", "LittleEpsilon"}, + { "Π", "BigPi"}, + { "\x03c0", "Pi" }, + { "𝝉", "Tau"}, + { "\x03c4", "Tau" }, + { "\x00ac", "Not" }, + { "\x2227", "And" }, + { "\x2228", "Or" }, + { "\x22bb", "Xor" }, + { "\x2295", "CirclePlus" }, + { "\x21ae", "NotLeftRightArrow" }, + { "\x2262", "NotIdentical" }, + { "\x22bc", "Nand" }, + { "\x2191", "UpArrow" }, + { "\x22bd", "Nor" }, + { "\x2193", "DownArrow" }, + { "\x22a6", "Assertion" }, + { "\x00f7", "Division" }, + { "\x00d7", "Multiplication" }, + { "\x221a", "SquareRoot" }, + { "\x221b", "CubeRoot" }, + { "\x00b1", "PlusOrMinus" }, + { "\x2213", "MinusOrPlus" }, + { "\x2224", "DoesNotDivide" }, + { "\x2208", "ElementOf" }, + { "\x220c", "NotElementOf" }, + { "\x2229", "Intersection" }, + { "\x222a", "Union" }, + { "\x2286", "Subset" }, + { "\x2282", "ProperSubset" }, + { "\x2284", "NotSubset" }, + { "\x2287", "Superset" }, + { "\x2283", "ProperSuperset" }, + { "\x2285", "NotSuperset" }, + { "\x2264", "LessThanOrEqualTo" }, + { "\x2265", "GreaterThanOrEqualTo" }, + { "\x226c", "Between" }, + { "\x2248", "Approximates" }, + { "\x2218", "Ring" }, + }; - public static UnicodeMapper Default = new UnicodeMapper (); + public static UnicodeMapper Default = new UnicodeMapper(); - Dictionary mapping; + Dictionary mapping; - public UnicodeMapper () - { - mapping = DefaultMapping; - } + public UnicodeMapper() + { + mapping = DefaultMapping; + } - // While this takes a string, it should be one 'character', possibly made up of multiple - // parts, like 🍎 - public string MapToUnicodeName (string s) - { - if (new StringInfo (s).LengthInTextElements != 1) - throw new ArgumentOutOfRangeException (nameof (s)); + // While this takes a string, it should be one 'character', possibly made up of multiple + // parts, like 🍎 + public string MapToUnicodeName(string s) + { + if (new StringInfo(s).LengthInTextElements != 1) + throw new ArgumentOutOfRangeException(nameof(s)); - if (mapping.TryGetValue (s, out var result)) - return result; + if (mapping.TryGetValue(s, out var result)) + return result; - StringBuilder stringBuilder = new StringBuilder ().Append ("U"); + StringBuilder stringBuilder = new StringBuilder().Append("U"); - var encoding = Encoding.UTF32; - var bytes = encoding.GetBytes (s); - var utf32Value = BitConverter.ToUInt32 (bytes, 0); - if (utf32Value > 0xffff) - stringBuilder.Append ($"{utf32Value:X8}"); - else - stringBuilder.Append ($"{utf32Value:X4}"); + var encoding = Encoding.UTF32; + var bytes = encoding.GetBytes(s); + var utf32Value = BitConverter.ToUInt32(bytes, 0); + if (utf32Value > 0xffff) + stringBuilder.Append($"{utf32Value:X8}"); + else + stringBuilder.Append($"{utf32Value:X4}"); - return stringBuilder.ToString (); - } + return stringBuilder.ToString(); + } - public void AddMappingsFromFile (string fileName) - { - AddMappingsFromXML (File.ReadAllText (fileName)); - } + public void AddMappingsFromFile(string fileName) + { + AddMappingsFromXML(File.ReadAllText(fileName)); + } - public void AddMappingsFromXML (string mappingXML) - { - if (mapping == DefaultMapping) { - // Clone the default mapping, since we don't want to modify it. - mapping = new Dictionary (mapping); - } - foreach (var m in ReadMappings (mappingXML)) - mapping [m.Item1] = m.Item2; - } + public void AddMappingsFromXML(string mappingXML) + { + if (mapping == DefaultMapping) + { + // Clone the default mapping, since we don't want to modify it. + mapping = new Dictionary(mapping); + } + foreach (var m in ReadMappings(mappingXML)) + mapping[m.Item1] = m.Item2; + } - static IEnumerable> ReadMappings (string mappingXML) - { - XDocument xmlDocument = XDocument.Parse (mappingXML); - foreach (var mapping in xmlDocument.Descendants ("map")) - { - string from = mapping.Attribute (XName.Get ("from"))?.Value; - string to = mapping.Attribute (XName.Get ("to"))?.Value; + static IEnumerable> ReadMappings(string mappingXML) + { + XDocument xmlDocument = XDocument.Parse(mappingXML); + foreach (var mapping in xmlDocument.Descendants("map")) + { + string from = mapping.Attribute(XName.Get("from"))?.Value; + string to = mapping.Attribute(XName.Get("to"))?.Value; - if (from != null && to != null) - yield return new Tuple (from, to); - } - } - } + if (from != null && to != null) + yield return new Tuple(from, to); + } + } + } } diff --git a/src/SwiftReflector/ValueWitnessTable.cs b/src/SwiftReflector/ValueWitnessTable.cs index 217889d0c005..dccefbf82441 100644 --- a/src/SwiftReflector/ValueWitnessTable.cs +++ b/src/SwiftReflector/ValueWitnessTable.cs @@ -6,123 +6,126 @@ using SwiftReflector.ExceptionTools; using SwiftReflector.Demangling; -namespace SwiftReflector { - public class ValueWitnessTable { - // #define FOR_ALL_FUNCTION_VALUE_WITNESSES(MACRO) \ - // MACRO(destroyBuffer) \ - // MACRO(initializeBufferWithCopyOfBuffer) \ - // MACRO(projectBuffer) \ - // MACRO(deallocateBuffer) \ - // MACRO(destroy) \ - // MACRO(initializeBufferWithCopy) \ - // MACRO(initializeWithCopy) \ - // MACRO(assignWithCopy) \ - // MACRO(initializeBufferWithTake) \ - // MACRO(initializeWithTake) \ - // MACRO(assignWithTake) \ - // MACRO(allocateBuffer) \ - // MACRO(initializeBufferWithTakeOfBuffer) \ - // MACRO(destroyArray) \ - // MACRO(initializeArrayWithCopy) \ - // MACRO(initializeArrayWithTakeFrontToBack) \ - // MACRO(initializeArrayWithTakeBackToFront) - public long DestroyBufferOffset { get; private set; } - public long InitializeBufferWithCopyOfBufferOffset { get; private set; } - public long ProjectBufferOffset { get; private set; } - public long DeallocateBufferOffset { get; private set; } - public long DestroyOffset { get; private set; } - public long InitializeBufferWithCopyOffset { get; private set; } - public long InitializeWithCopyOffset { get; private set; } - public long AssignWithCopyOffset { get; private set; } - public long InitializeBufferWithTakeOffset { get; private set; } - public long InitializeWithTakeOffset { get; private set; } - public long AssignWithTakeOffset { get; private set; } - public long AllocateBufferOffset { get; private set; } - public long InitializeBufferWithTakeOfBufferOffset { get; private set; } - public long DestroyArrayOffset { get; private set; } - public long InitializeArrayWithCopyOffset { get; private set; } - public long InitializeArrayWithTakeFrontToBackOffset { get; private set; } - public long InitializeArrayWithTakeBackToFrontOffset { get; private set; } - public long Size { get; private set; } - public ushort Flags { get; private set; } - public ushort Log2Stride { get; private set; } - public long Stride { get; private set; } - public string MangledName { get; private set; } +namespace SwiftReflector +{ + public class ValueWitnessTable + { + // #define FOR_ALL_FUNCTION_VALUE_WITNESSES(MACRO) \ + // MACRO(destroyBuffer) \ + // MACRO(initializeBufferWithCopyOfBuffer) \ + // MACRO(projectBuffer) \ + // MACRO(deallocateBuffer) \ + // MACRO(destroy) \ + // MACRO(initializeBufferWithCopy) \ + // MACRO(initializeWithCopy) \ + // MACRO(assignWithCopy) \ + // MACRO(initializeBufferWithTake) \ + // MACRO(initializeWithTake) \ + // MACRO(assignWithTake) \ + // MACRO(allocateBuffer) \ + // MACRO(initializeBufferWithTakeOfBuffer) \ + // MACRO(destroyArray) \ + // MACRO(initializeArrayWithCopy) \ + // MACRO(initializeArrayWithTakeFrontToBack) \ + // MACRO(initializeArrayWithTakeBackToFront) + public long DestroyBufferOffset { get; private set; } + public long InitializeBufferWithCopyOfBufferOffset { get; private set; } + public long ProjectBufferOffset { get; private set; } + public long DeallocateBufferOffset { get; private set; } + public long DestroyOffset { get; private set; } + public long InitializeBufferWithCopyOffset { get; private set; } + public long InitializeWithCopyOffset { get; private set; } + public long AssignWithCopyOffset { get; private set; } + public long InitializeBufferWithTakeOffset { get; private set; } + public long InitializeWithTakeOffset { get; private set; } + public long AssignWithTakeOffset { get; private set; } + public long AllocateBufferOffset { get; private set; } + public long InitializeBufferWithTakeOfBufferOffset { get; private set; } + public long DestroyArrayOffset { get; private set; } + public long InitializeArrayWithCopyOffset { get; private set; } + public long InitializeArrayWithTakeFrontToBackOffset { get; private set; } + public long InitializeArrayWithTakeBackToFrontOffset { get; private set; } + public long Size { get; private set; } + public ushort Flags { get; private set; } + public ushort Log2Stride { get; private set; } + public long Stride { get; private set; } + public string MangledName { get; private set; } - ValueWitnessTable () - { - } + ValueWitnessTable() + { + } - public static ValueWitnessTable FromStream (Stream stm, TLFunction tlf, int sizeofMachinePointer) - { - if (sizeofMachinePointer != 4 && sizeofMachinePointer != 8) { - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 14, $"Expected a maching pointer size of either 4 or 8, but got {sizeofMachinePointer}"); - } - var wit = tlf.Signature as SwiftWitnessTableType; - if (wit == null || wit.WitnessType != WitnessType.Value) - throw ErrorHelper.CreateError (ReflectorError.kCantHappenBase + 15, $"Expected a SwiftWitnessTable, but got {tlf.Signature.GetType ().Name}."); - var reader = new BinaryReader (stm); - reader.BaseStream.Seek ((long)tlf.Offset, SeekOrigin.Begin); + public static ValueWitnessTable FromStream(Stream stm, TLFunction tlf, int sizeofMachinePointer) + { + if (sizeofMachinePointer != 4 && sizeofMachinePointer != 8) + { + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 14, $"Expected a maching pointer size of either 4 or 8, but got {sizeofMachinePointer}"); + } + var wit = tlf.Signature as SwiftWitnessTableType; + if (wit == null || wit.WitnessType != WitnessType.Value) + throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 15, $"Expected a SwiftWitnessTable, but got {tlf.Signature.GetType().Name}."); + var reader = new BinaryReader(stm); + reader.BaseStream.Seek((long)tlf.Offset, SeekOrigin.Begin); - var table = new ValueWitnessTable (); - table.MangledName = tlf.MangledName; - if (sizeofMachinePointer == 4) - table.Read32 (reader); - else - table.Read64 (reader); - return table; - } + var table = new ValueWitnessTable(); + table.MangledName = tlf.MangledName; + if (sizeofMachinePointer == 4) + table.Read32(reader); + else + table.Read64(reader); + return table; + } - void Read32 (BinaryReader reader) - { - DestroyBufferOffset = reader.ReadInt32 (); - InitializeBufferWithCopyOfBufferOffset = reader.ReadInt32 (); - ProjectBufferOffset = reader.ReadInt32 (); - DeallocateBufferOffset = reader.ReadInt32 (); - DestroyOffset = reader.ReadInt32 (); - InitializeBufferWithCopyOffset = reader.ReadInt32 (); - InitializeWithCopyOffset = reader.ReadInt32 (); - AssignWithCopyOffset = reader.ReadInt32 (); - InitializeBufferWithTakeOffset = reader.ReadInt32 (); - InitializeWithTakeOffset = reader.ReadInt32 (); - AssignWithTakeOffset = reader.ReadInt32 (); - AllocateBufferOffset = reader.ReadInt32 (); - InitializeBufferWithTakeOfBufferOffset = reader.ReadInt32 (); - DestroyArrayOffset = reader.ReadInt32 (); - InitializeArrayWithCopyOffset = reader.ReadInt32 (); - InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt32 (); - InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt32 (); - Size = reader.ReadInt32 (); - Flags = reader.ReadUInt16 (); - Log2Stride = reader.ReadUInt16 (); - Stride = reader.ReadInt32 (); - } + void Read32(BinaryReader reader) + { + DestroyBufferOffset = reader.ReadInt32(); + InitializeBufferWithCopyOfBufferOffset = reader.ReadInt32(); + ProjectBufferOffset = reader.ReadInt32(); + DeallocateBufferOffset = reader.ReadInt32(); + DestroyOffset = reader.ReadInt32(); + InitializeBufferWithCopyOffset = reader.ReadInt32(); + InitializeWithCopyOffset = reader.ReadInt32(); + AssignWithCopyOffset = reader.ReadInt32(); + InitializeBufferWithTakeOffset = reader.ReadInt32(); + InitializeWithTakeOffset = reader.ReadInt32(); + AssignWithTakeOffset = reader.ReadInt32(); + AllocateBufferOffset = reader.ReadInt32(); + InitializeBufferWithTakeOfBufferOffset = reader.ReadInt32(); + DestroyArrayOffset = reader.ReadInt32(); + InitializeArrayWithCopyOffset = reader.ReadInt32(); + InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt32(); + InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt32(); + Size = reader.ReadInt32(); + Flags = reader.ReadUInt16(); + Log2Stride = reader.ReadUInt16(); + Stride = reader.ReadInt32(); + } - void Read64 (BinaryReader reader) - { - DestroyBufferOffset = reader.ReadInt64 (); - InitializeBufferWithCopyOfBufferOffset = reader.ReadInt64 (); - ProjectBufferOffset = reader.ReadInt64 (); - DeallocateBufferOffset = reader.ReadInt64 (); - DestroyOffset = reader.ReadInt64 (); - InitializeBufferWithCopyOffset = reader.ReadInt64 (); - InitializeWithCopyOffset = reader.ReadInt64 (); - AssignWithCopyOffset = reader.ReadInt64 (); - InitializeBufferWithTakeOffset = reader.ReadInt64 (); - InitializeWithTakeOffset = reader.ReadInt64 (); - AssignWithTakeOffset = reader.ReadInt64 (); - AllocateBufferOffset = reader.ReadInt64 (); - InitializeBufferWithTakeOfBufferOffset = reader.ReadInt64 (); - DestroyArrayOffset = reader.ReadInt64 (); - InitializeArrayWithCopyOffset = reader.ReadInt64 (); - InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt64 (); - InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt64 (); - Size = reader.ReadInt64 (); - reader.ReadInt32 (); - Flags = reader.ReadUInt16 (); - Log2Stride = reader.ReadUInt16 (); - Stride = reader.ReadInt64 (); - } - } + void Read64(BinaryReader reader) + { + DestroyBufferOffset = reader.ReadInt64(); + InitializeBufferWithCopyOfBufferOffset = reader.ReadInt64(); + ProjectBufferOffset = reader.ReadInt64(); + DeallocateBufferOffset = reader.ReadInt64(); + DestroyOffset = reader.ReadInt64(); + InitializeBufferWithCopyOffset = reader.ReadInt64(); + InitializeWithCopyOffset = reader.ReadInt64(); + AssignWithCopyOffset = reader.ReadInt64(); + InitializeBufferWithTakeOffset = reader.ReadInt64(); + InitializeWithTakeOffset = reader.ReadInt64(); + AssignWithTakeOffset = reader.ReadInt64(); + AllocateBufferOffset = reader.ReadInt64(); + InitializeBufferWithTakeOfBufferOffset = reader.ReadInt64(); + DestroyArrayOffset = reader.ReadInt64(); + InitializeArrayWithCopyOffset = reader.ReadInt64(); + InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt64(); + InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt64(); + Size = reader.ReadInt64(); + reader.ReadInt32(); + Flags = reader.ReadUInt16(); + Log2Stride = reader.ReadUInt16(); + Stride = reader.ReadInt64(); + } + } } diff --git a/src/SwiftReflector/XmlToTLFunctionMapper.cs b/src/SwiftReflector/XmlToTLFunctionMapper.cs index 38fbaa71ef1d..2913c617787c 100644 --- a/src/SwiftReflector/XmlToTLFunctionMapper.cs +++ b/src/SwiftReflector/XmlToTLFunctionMapper.cs @@ -9,481 +9,540 @@ using SwiftReflector.Demangling; using SwiftReflector.TypeMapping; -namespace SwiftReflector { - public class XmlToTLFunctionMapper { - public static TLFunction ToProtocolFactory (string swiftProxyFactoryName, ModuleDeclaration modDecl, ModuleContents contents, TypeMapper typeMap) - { - var swiftProxyFunctionDecl = modDecl.TopLevelFunctions.Where (fn => fn.Name == swiftProxyFactoryName).FirstOrDefault (); - if (swiftProxyFunctionDecl == null) - return null; - return ToTLFunction (swiftProxyFunctionDecl, contents, typeMap); - } - - public static TLFunction ToTLFunction (FunctionDeclaration decl, ModuleContents contents, TypeMapper typeMap) - { - string nameToSearch = GetNameToSearchOn (decl); - var funcs = FuncsToSearch (contents, decl, nameToSearch); - return MatchFunctionDecl (decl, funcs, typeMap); - } - - public static TLFunction ToTLFunction (FunctionDeclaration decl, ModuleInventory mi, TypeMapper typeMap) - { - var scn = ToSwiftClassName (decl); - var contents = mi.Values.FirstOrDefault (mc => mc.Name.Equals (scn.Module)); - if (contents == null) - return null; - return ToTLFunction (decl, contents, typeMap); - } - - public static TLFunction ToTLFunction (FunctionDeclaration decl, ClassContents classContents, TypeMapper typeMap) - { - string name = decl.IsProperty ? decl.PropertyName : decl.Name; - var funcsToSearch = FuncsToSearch (classContents, decl, name);//decl.ParameterLists.Count == 2 ? classContents.Methods.MethodsWithName (decl.Name) - //: classContents.StaticFunctions.MethodsWithName (decl.Name); - return MatchFunctionDecl (decl, funcsToSearch, typeMap); - } - - static List FuncsToSearch (ModuleContents contents, FunctionDeclaration decl, string name) - { - - List funcs = null; - if (decl.Parent == null) { // top level - if (decl.IsProperty) { - funcs = contents.Functions.MethodsWithName (name).Where (tlf => tlf.Signature is SwiftPropertyType).ToList (); - } else { - funcs = contents.Functions.MethodsWithName (name).Where (tlf => !(tlf.Signature is SwiftPropertyType)).ToList (); - } - } else { - var cn = ToSwiftClassName (decl); - var theClass = LocateClassContents (contents, cn); - funcs = FuncsToSearch (theClass, decl, name); - } - return funcs; - } - - static List FuncsToSearch (ClassContents theClass, FunctionDeclaration decl, string name) - { - List funcs = null; - - if (theClass == null) { - funcs = new List (); - } else { - if (decl.IsProperty) { - funcs = new List (); - if (decl.IsSubscript) { - funcs.AddRange (theClass.Subscripts); - } else { - foreach (var pc in theClass.AllPropertiesWithName(name)) { - var propType = pc.TLFGetter.Signature as SwiftPropertyType; - if (propType == null) // should never happen, but... - continue; - if (propType.IsStatic != decl.IsStatic) - continue; - if (decl.IsGetter) - funcs.Add (pc.TLFGetter); - else if (decl.IsSetter && pc.TLFSetter != null) - funcs.Add (pc.TLFSetter); - else if (decl.IsMaterializer && pc.TLFMaterializer != null) - funcs.Add (pc.TLFMaterializer); - } - } - } else if (decl.IsConstructor) { - funcs = theClass.Constructors.AllocatingConstructors (); - } else if (decl.IsDestructor) { - funcs = theClass.Destructors.DeallocatingDestructors (); - } else { - if (decl.IsStatic) - funcs = theClass.StaticFunctions.MethodsWithName (name); - else - funcs = theClass.Methods.MethodsWithName (name); - } - } - return funcs; - } - - static string GetNameToSearchOn (FunctionDeclaration decl) - { - if (!decl.IsProperty) - return decl.Name; - if (decl.IsGetter) - return decl.Name.Substring (FunctionDeclaration.kPropertyGetterPrefix.Length); - else if (decl.IsSetter) - return decl.Name.Substring (FunctionDeclaration.kPropertySetterPrefix.Length); - else if (decl.IsMaterializer) - return decl.Name.Substring (FunctionDeclaration.kPropertyMaterializerPrefix.Length); - else - throw new ArgumentOutOfRangeException ("decl", "Expected getter or setter but got something else?"); - } - - public static ClassContents LocateClassContents (ModuleContents contents, SwiftClassName cn) - { - return contents.Classes.Values.FirstOrDefault (cc => cc.Name.Equals (cn)); - } - - public static ClassContents LocateClassContents (ModuleInventory modInventory, SwiftClassName className) - { - var contents = modInventory.Values.FirstOrDefault (mod => mod.Name.Equals (className.Module)); - if (contents == null) - return null; - return LocateClassContents (contents, className); - } - - public static ProtocolContents LocateProtocolContents (ModuleContents contents, SwiftClassName cn) - { - return contents.Protocols.Values.FirstOrDefault (cc => cc.Name.Equals (cn)); - } - - public static ProtocolContents LocateProtocolContents (ModuleInventory modInventory, SwiftClassName className) - { - var contents = modInventory.Values.FirstOrDefault (mod => mod.Name.Equals (className.Module)); - if (contents == null) - return null; - return LocateProtocolContents (contents, className); - } - - - - public static SwiftClassName ToSwiftClassName (BaseDeclaration bdl, string suffix = null) - { - var nesting = new List (); - var names = new List (); - var walker = bdl; - do { - if (IsNestable (walker)) { - nesting.Insert (0, ToMemberNesting (walker)); - names.Insert (0, new SwiftName (walker.Name + (walker == bdl && suffix != null ? suffix : ""), false)); - } - walker = walker.Parent; - } while (walker != null); - return new SwiftClassName (new SwiftName (bdl.Module.Name, false), nesting, names); - } - - static bool IsNestable (BaseDeclaration bdl) - { - return bdl is ClassDeclaration || bdl is StructDeclaration - || bdl is EnumDeclaration - ; - } - - static MemberNesting ToMemberNesting (BaseDeclaration decl) - { - // Don't reorder - a ProtocolDeclaration is a ClassDeclaration (for now) - if (decl is ProtocolDeclaration) { - return MemberNesting.Protocol; - } - if (decl is ClassDeclaration) { - return MemberNesting.Class; - } - if (decl is StructDeclaration) { - return MemberNesting.Struct; - } - if (decl is EnumDeclaration) { - return MemberNesting.Enum; - } - throw new ArgumentOutOfRangeException ("decl", String.Format ("unknown class entity type {0}", decl.GetType ().Name)); - } - - static TLFunction MatchFunctionDecl (FunctionDeclaration decl, List funcs, TypeMapper typeMap) - { - if (decl.Parent == null) - funcs = funcs.Where (fn => fn.IsTopLevelFunction).ToList (); - else - funcs = funcs.Where (fn => !fn.IsTopLevelFunction).ToList (); - - foreach (var func in funcs) { - if (SignaturesMatch (decl, func, typeMap)) - return func; - } - return null; - } - - - static bool SignaturesMatch (FunctionDeclaration decl, TLFunction func, TypeMapper typeMap) - { - if (decl.IsConstructor && !(func.Signature is SwiftConstructorType) || - (!decl.IsConstructor && func.Signature is SwiftConstructorType)) - return false; - List significantParameterList = decl.ParameterLists.Last (); - if (decl.ParameterLists.Count > 1 && !decl.IsStatic) { - var ucf = func.Signature as SwiftUncurriedFunctionType; - if (ucf == null) - return false; - - var uncurriedParameter = ucf.UncurriedParameter; - var uncurriedTuple = uncurriedParameter as SwiftTupleType; - - // the !decl.IsConstructor is because the uncurried parameter in a constructor comes out - // "funny" in XmlReflection and won't match - if ((decl.Parent == null || !(decl.Parent is StructDeclaration)) && !decl.IsConstructor) { - if (decl.ParameterLists [0].Count == 1) { - if (!TypeMatches (decl, decl.ParameterLists [0] [0], uncurriedParameter, false, typeMap)) - return false; - } else if (decl.ParameterLists [0].Count == 0) { - if (uncurriedTuple == null || !uncurriedTuple.IsEmpty) - return false; - } else { - if (uncurriedTuple == null || !TypeMatches (decl, decl.ParameterLists [0], uncurriedTuple, typeMap)) - return false; - } - } - } - - // return is implied in constructor - we're good on that, thanks - bool dontMatchReturn = decl.IsConstructor; - - if (func.Signature.ParameterCount == significantParameterList.Count) { - if (func.Signature.ParameterCount == 0) - return dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); - if (func.Signature.ParameterCount == 1) { - var tuple = func.Signature.Parameters as SwiftTupleType; - var argsMatch = TypeMatches (decl, significantParameterList [0], tuple != null ? tuple.Contents [0] : func.Signature.Parameters, decl.IsSetter, typeMap); - var returnMatches = (dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); - return argsMatch && returnMatches; - } else { - var argsMatch = TypeMatches (decl, significantParameterList, func.Signature.Parameters as SwiftTupleType, typeMap); - var returnMatches = dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); - return argsMatch && returnMatches; - } - } else { - // oh, hooray. Swift does a reduction in the tuple-ness of arguments. - // if I declare a function, func a(a:(Bool, Bool)) { } - // This should get turned into: - // __TF6Module1aFTTSbSb__T_ - // Instead, swift turns it into: - // __TF6Module1aFTSbSb_T_ - // In other words, if the only argument to the function is a tuple, unwrap it. - if (significantParameterList.Count == 1 && significantParameterList [0].TypeSpec is TupleTypeSpec) { - return TypeMatches (decl, significantParameterList [0], func.Signature.Parameters, false, typeMap) - && (dontMatchReturn || TypeMatches (decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); - } - } - return false; - } - - - static bool TypeMatches (FunctionDeclaration decl, List parms, SwiftTupleType tuple, TypeMapper typeMap) - { - if (tuple == null || parms.Count != tuple.Contents.Count) - return false; - for (int i = 0; i < parms.Count; i++) { - if (!TypeMatches (decl, parms [i], tuple.Contents [i], decl.IsSubscript, typeMap)) - return false; - } - return true; - } - - static bool TypeMatches (FunctionDeclaration decl, ParameterItem pi, SwiftType st, bool ignoreName, TypeMapper typeMap) - { - // some SwiftType parameters have no names, such as operators - if (!ignoreName && pi.PublicName != "self" && st.Name != null && pi.PublicName != st.Name.Name) - return false; - if (pi.IsVariadic != st.IsVariadic) - return false; - return TypeMatches (decl, pi.TypeSpec, st, typeMap); - } - - static bool TypeMatches (FunctionDeclaration decl, TypeSpec ts, SwiftType st, TypeMapper typeMap) - { - switch (ts.Kind) { - case TypeSpecKind.Named: - return TypeMatches (decl, ts as NamedTypeSpec, st, typeMap); - case TypeSpecKind.Closure: - return TypeMatches (decl, ts as ClosureTypeSpec, st, typeMap); - case TypeSpecKind.Tuple: - return TypeMatches (decl, ts as TupleTypeSpec, st, typeMap); - case TypeSpecKind.ProtocolList: - return TypeMatches (decl, ts as ProtocolListTypeSpec, st, typeMap); - default: - throw new ArgumentOutOfRangeException (nameof (ts)); - } - } - - static bool TypeMatches (FunctionDeclaration decl, ClosureTypeSpec cs, SwiftType st, TypeMapper typeMap) - { - SwiftBaseFunctionType bft = st as SwiftBaseFunctionType; - return TypeMatches (decl, cs.Arguments, bft.Parameters, typeMap) && - TypeMatches (decl, cs.ReturnType, bft.ReturnType, typeMap); - } - - static bool TypeMatches (FunctionDeclaration decl, TupleTypeSpec ts, SwiftType st, TypeMapper typeMap) - { - var tuple = st as SwiftTupleType; - if (tuple == null || tuple.Contents.Count != ts.Elements.Count) - return false; - for (int i = 0; i < ts.Elements.Count; i++) { - if (!TypeMatches (decl, ts.Elements [i], tuple.Contents [i], typeMap)) - return false; - } - return true; - } - - static bool TypeMatches (FunctionDeclaration decl, ProtocolListTypeSpec ps, SwiftType st, TypeMapper typeMap) - { - var protoList = st as SwiftProtocolListType; - if (protoList == null || protoList.Protocols.Count != ps.Protocols.Count) - return false; - for (int i=0; i < ps.Protocols.Count; i++) { - if (!TypeMatches (decl, ps.Protocols.Keys [i], protoList.Protocols [i], typeMap)) - return false; - } - return true; - } - - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftType st, TypeMapper typeMap) - { - switch (st.Type) { - case CoreCompoundType.Scalar: - return TypeMatches (decl, ts, st as SwiftBuiltInType, typeMap); - case CoreCompoundType.Class: - return TypeMatches (decl, ts, st as SwiftClassType, typeMap); - case CoreCompoundType.MetaClass: - if (st is SwiftExistentialMetaType exist) - return TypeMatches (decl, ts, exist, typeMap); - else - return TypeMatches (decl, ts, st as SwiftMetaClassType, typeMap); - case CoreCompoundType.BoundGeneric: - return TypeMatches (decl, ts, st as SwiftBoundGenericType, typeMap); - case CoreCompoundType.ProtocolList: - return TypeMatches (decl, ts, st as SwiftProtocolListType, typeMap); - case CoreCompoundType.GenericReference: - return TypeMatches (decl, ts, st as SwiftGenericArgReferenceType, typeMap); - case CoreCompoundType.Struct: - default: - return false; - } - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftGenericArgReferenceType genArg, TypeMapper typeMap) - { - if (genArg.HasAssociatedTypePath) { - if (!decl.IsProtocolWithAssociatedTypesFullPath (ts, typeMap)) - return false; - var parts = ts.Name.Split ('.'); - // parts will have the generic part at 0, genArg will not - if (parts.Length != genArg.AssociatedTypePath.Count + 1) - return false; - var depthAndIndex = decl.GetGenericDepthAndIndex (parts [0]); - if (genArg.Depth != depthAndIndex.Item1 || genArg.Index != depthAndIndex.Item2) - return false; - for (int i = 0; i < genArg.AssociatedTypePath.Count; i++) { - if (genArg.AssociatedTypePath [i] != parts [i + 1]) - return false; - } - return true; - } else { - if (!decl.IsTypeSpecGeneric (ts)) - return false; - var depthAndIndex = decl.GetGenericDepthAndIndex (ts.Name); - return genArg.Depth == depthAndIndex.Item1 && genArg.Index == depthAndIndex.Item2; - } - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftProtocolListType protList, TypeMapper typeMap) - { - if (protList == null) - return false; - if (protList.Protocols.Count == 1 && !ts.IsProtocolList) { - return TypeMatches (decl, ts, protList.Protocols [0], typeMap); - } - - if (protList.Protocols.Count != ts.GenericParameters.Count || !ts.IsProtocolList) - return false; - for (int i = 0; i < ts.GenericParameters.Count; i++) { - if (!TypeMatches (decl, ts.GenericParameters [i], protList.Protocols [i], typeMap)) - return false; - } - return true; - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftClassType ct, TypeMapper typeMap) - { - if (ct == null) - return false; - return ts.Name == ct.ClassName.ToFullyQualifiedName (true) || - ts.NameWithoutModule == ct.ClassName.ToFullyQualifiedName (false); - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftBuiltInType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (ts.IsInOut != st.IsReference) - return false; - switch (st.BuiltInType) { - case CoreBuiltInType.Bool: - return ts.Name == "Swift.Bool"; - case CoreBuiltInType.Double: - return ts.Name == "Swift.Double"; - case CoreBuiltInType.Float: - return ts.Name == "Swift.Float"; - case CoreBuiltInType.Int: - return ts.Name == "Swift.Int"; - case CoreBuiltInType.UInt: - return ts.Name == "Swift.UInt"; - default: - throw new ArgumentOutOfRangeException ("st"); - } - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftExistentialMetaType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (st.Protocol.Protocols.Count != 1) - return false; - var protoClass = st.Protocol.Protocols [0]; - if (ts.Name == "Any.Type") { - return protoClass.ClassName.ToFullyQualifiedName () == "Swift.Any"; - } - if (ts.Name == protoClass.ClassName.ToFullyQualifiedName ()) - return true; - if (ts.Name.EndsWith (".Type", StringComparison.Ordinal)) { - var maybeClassName = ts.Name.Substring (0, ts.Name.Length - ".Type".Length); - return maybeClassName == protoClass.ClassName.ToFullyQualifiedName (); - } - return false; - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftMetaClassType st, TypeMapper typeMap) - { - if (st == null) - return false; - return ts.Name == st.Class.ClassName.ToFullyQualifiedName (true); - } - - static bool TypeMatches (FunctionDeclaration decl, NamedTypeSpec ts, SwiftBoundGenericType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (!ts.ContainsGenericParameters) - return false; - return TypeMatches (decl, ts.GenericParameters, st.BoundTypes, typeMap); - } - - static bool TypeMatches (FunctionDeclaration decl, List ts, List st, TypeMapper typeMap) - { - if (ts == null || st == null) - return false; - if (ts.Count != st.Count) - return false; - if (ts.Count == 1) { - // Thanks swift, you're the best... - if (IsVoid (ts [0]) && st [0].IsEmptyTuple) - return true; - } - for (int i = 0; i < ts.Count; i++) { - if (!TypeMatches (decl, ts [i], st [i], typeMap)) - return false; - } - return true; - } - - static bool IsVoid (TypeSpec ts) - { - var ns = ts as NamedTypeSpec; - return ns != null && (ns.Name == "Void" || ns.Name == "Swift.Void"); - } - } +namespace SwiftReflector +{ + public class XmlToTLFunctionMapper + { + public static TLFunction ToProtocolFactory(string swiftProxyFactoryName, ModuleDeclaration modDecl, ModuleContents contents, TypeMapper typeMap) + { + var swiftProxyFunctionDecl = modDecl.TopLevelFunctions.Where(fn => fn.Name == swiftProxyFactoryName).FirstOrDefault(); + if (swiftProxyFunctionDecl == null) + return null; + return ToTLFunction(swiftProxyFunctionDecl, contents, typeMap); + } + + public static TLFunction ToTLFunction(FunctionDeclaration decl, ModuleContents contents, TypeMapper typeMap) + { + string nameToSearch = GetNameToSearchOn(decl); + var funcs = FuncsToSearch(contents, decl, nameToSearch); + return MatchFunctionDecl(decl, funcs, typeMap); + } + + public static TLFunction ToTLFunction(FunctionDeclaration decl, ModuleInventory mi, TypeMapper typeMap) + { + var scn = ToSwiftClassName(decl); + var contents = mi.Values.FirstOrDefault(mc => mc.Name.Equals(scn.Module)); + if (contents == null) + return null; + return ToTLFunction(decl, contents, typeMap); + } + + public static TLFunction ToTLFunction(FunctionDeclaration decl, ClassContents classContents, TypeMapper typeMap) + { + string name = decl.IsProperty ? decl.PropertyName : decl.Name; + var funcsToSearch = FuncsToSearch(classContents, decl, name);//decl.ParameterLists.Count == 2 ? classContents.Methods.MethodsWithName (decl.Name) + //: classContents.StaticFunctions.MethodsWithName (decl.Name); + return MatchFunctionDecl(decl, funcsToSearch, typeMap); + } + + static List FuncsToSearch(ModuleContents contents, FunctionDeclaration decl, string name) + { + + List funcs = null; + if (decl.Parent == null) + { // top level + if (decl.IsProperty) + { + funcs = contents.Functions.MethodsWithName(name).Where(tlf => tlf.Signature is SwiftPropertyType).ToList(); + } + else + { + funcs = contents.Functions.MethodsWithName(name).Where(tlf => !(tlf.Signature is SwiftPropertyType)).ToList(); + } + } + else + { + var cn = ToSwiftClassName(decl); + var theClass = LocateClassContents(contents, cn); + funcs = FuncsToSearch(theClass, decl, name); + } + return funcs; + } + + static List FuncsToSearch(ClassContents theClass, FunctionDeclaration decl, string name) + { + List funcs = null; + + if (theClass == null) + { + funcs = new List(); + } + else + { + if (decl.IsProperty) + { + funcs = new List(); + if (decl.IsSubscript) + { + funcs.AddRange(theClass.Subscripts); + } + else + { + foreach (var pc in theClass.AllPropertiesWithName(name)) + { + var propType = pc.TLFGetter.Signature as SwiftPropertyType; + if (propType == null) // should never happen, but... + continue; + if (propType.IsStatic != decl.IsStatic) + continue; + if (decl.IsGetter) + funcs.Add(pc.TLFGetter); + else if (decl.IsSetter && pc.TLFSetter != null) + funcs.Add(pc.TLFSetter); + else if (decl.IsMaterializer && pc.TLFMaterializer != null) + funcs.Add(pc.TLFMaterializer); + } + } + } + else if (decl.IsConstructor) + { + funcs = theClass.Constructors.AllocatingConstructors(); + } + else if (decl.IsDestructor) + { + funcs = theClass.Destructors.DeallocatingDestructors(); + } + else + { + if (decl.IsStatic) + funcs = theClass.StaticFunctions.MethodsWithName(name); + else + funcs = theClass.Methods.MethodsWithName(name); + } + } + return funcs; + } + + static string GetNameToSearchOn(FunctionDeclaration decl) + { + if (!decl.IsProperty) + return decl.Name; + if (decl.IsGetter) + return decl.Name.Substring(FunctionDeclaration.kPropertyGetterPrefix.Length); + else if (decl.IsSetter) + return decl.Name.Substring(FunctionDeclaration.kPropertySetterPrefix.Length); + else if (decl.IsMaterializer) + return decl.Name.Substring(FunctionDeclaration.kPropertyMaterializerPrefix.Length); + else + throw new ArgumentOutOfRangeException("decl", "Expected getter or setter but got something else?"); + } + + public static ClassContents LocateClassContents(ModuleContents contents, SwiftClassName cn) + { + return contents.Classes.Values.FirstOrDefault(cc => cc.Name.Equals(cn)); + } + + public static ClassContents LocateClassContents(ModuleInventory modInventory, SwiftClassName className) + { + var contents = modInventory.Values.FirstOrDefault(mod => mod.Name.Equals(className.Module)); + if (contents == null) + return null; + return LocateClassContents(contents, className); + } + + public static ProtocolContents LocateProtocolContents(ModuleContents contents, SwiftClassName cn) + { + return contents.Protocols.Values.FirstOrDefault(cc => cc.Name.Equals(cn)); + } + + public static ProtocolContents LocateProtocolContents(ModuleInventory modInventory, SwiftClassName className) + { + var contents = modInventory.Values.FirstOrDefault(mod => mod.Name.Equals(className.Module)); + if (contents == null) + return null; + return LocateProtocolContents(contents, className); + } + + + + public static SwiftClassName ToSwiftClassName(BaseDeclaration bdl, string suffix = null) + { + var nesting = new List(); + var names = new List(); + var walker = bdl; + do + { + if (IsNestable(walker)) + { + nesting.Insert(0, ToMemberNesting(walker)); + names.Insert(0, new SwiftName(walker.Name + (walker == bdl && suffix != null ? suffix : ""), false)); + } + walker = walker.Parent; + } while (walker != null); + return new SwiftClassName(new SwiftName(bdl.Module.Name, false), nesting, names); + } + + static bool IsNestable(BaseDeclaration bdl) + { + return bdl is ClassDeclaration || bdl is StructDeclaration + || bdl is EnumDeclaration + ; + } + + static MemberNesting ToMemberNesting(BaseDeclaration decl) + { + // Don't reorder - a ProtocolDeclaration is a ClassDeclaration (for now) + if (decl is ProtocolDeclaration) + { + return MemberNesting.Protocol; + } + if (decl is ClassDeclaration) + { + return MemberNesting.Class; + } + if (decl is StructDeclaration) + { + return MemberNesting.Struct; + } + if (decl is EnumDeclaration) + { + return MemberNesting.Enum; + } + throw new ArgumentOutOfRangeException("decl", String.Format("unknown class entity type {0}", decl.GetType().Name)); + } + + static TLFunction MatchFunctionDecl(FunctionDeclaration decl, List funcs, TypeMapper typeMap) + { + if (decl.Parent == null) + funcs = funcs.Where(fn => fn.IsTopLevelFunction).ToList(); + else + funcs = funcs.Where(fn => !fn.IsTopLevelFunction).ToList(); + + foreach (var func in funcs) + { + if (SignaturesMatch(decl, func, typeMap)) + return func; + } + return null; + } + + + static bool SignaturesMatch(FunctionDeclaration decl, TLFunction func, TypeMapper typeMap) + { + if (decl.IsConstructor && !(func.Signature is SwiftConstructorType) || + (!decl.IsConstructor && func.Signature is SwiftConstructorType)) + return false; + List significantParameterList = decl.ParameterLists.Last(); + if (decl.ParameterLists.Count > 1 && !decl.IsStatic) + { + var ucf = func.Signature as SwiftUncurriedFunctionType; + if (ucf == null) + return false; + + var uncurriedParameter = ucf.UncurriedParameter; + var uncurriedTuple = uncurriedParameter as SwiftTupleType; + + // the !decl.IsConstructor is because the uncurried parameter in a constructor comes out + // "funny" in XmlReflection and won't match + if ((decl.Parent == null || !(decl.Parent is StructDeclaration)) && !decl.IsConstructor) + { + if (decl.ParameterLists[0].Count == 1) + { + if (!TypeMatches(decl, decl.ParameterLists[0][0], uncurriedParameter, false, typeMap)) + return false; + } + else if (decl.ParameterLists[0].Count == 0) + { + if (uncurriedTuple == null || !uncurriedTuple.IsEmpty) + return false; + } + else + { + if (uncurriedTuple == null || !TypeMatches(decl, decl.ParameterLists[0], uncurriedTuple, typeMap)) + return false; + } + } + } + + // return is implied in constructor - we're good on that, thanks + bool dontMatchReturn = decl.IsConstructor; + + if (func.Signature.ParameterCount == significantParameterList.Count) + { + if (func.Signature.ParameterCount == 0) + return dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); + if (func.Signature.ParameterCount == 1) + { + var tuple = func.Signature.Parameters as SwiftTupleType; + var argsMatch = TypeMatches(decl, significantParameterList[0], tuple != null ? tuple.Contents[0] : func.Signature.Parameters, decl.IsSetter, typeMap); + var returnMatches = (dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); + return argsMatch && returnMatches; + } + else + { + var argsMatch = TypeMatches(decl, significantParameterList, func.Signature.Parameters as SwiftTupleType, typeMap); + var returnMatches = dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); + return argsMatch && returnMatches; + } + } + else + { + // oh, hooray. Swift does a reduction in the tuple-ness of arguments. + // if I declare a function, func a(a:(Bool, Bool)) { } + // This should get turned into: + // __TF6Module1aFTTSbSb__T_ + // Instead, swift turns it into: + // __TF6Module1aFTSbSb_T_ + // In other words, if the only argument to the function is a tuple, unwrap it. + if (significantParameterList.Count == 1 && significantParameterList[0].TypeSpec is TupleTypeSpec) + { + return TypeMatches(decl, significantParameterList[0], func.Signature.Parameters, false, typeMap) + && (dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); + } + } + return false; + } + + + static bool TypeMatches(FunctionDeclaration decl, List parms, SwiftTupleType tuple, TypeMapper typeMap) + { + if (tuple == null || parms.Count != tuple.Contents.Count) + return false; + for (int i = 0; i < parms.Count; i++) + { + if (!TypeMatches(decl, parms[i], tuple.Contents[i], decl.IsSubscript, typeMap)) + return false; + } + return true; + } + + static bool TypeMatches(FunctionDeclaration decl, ParameterItem pi, SwiftType st, bool ignoreName, TypeMapper typeMap) + { + // some SwiftType parameters have no names, such as operators + if (!ignoreName && pi.PublicName != "self" && st.Name != null && pi.PublicName != st.Name.Name) + return false; + if (pi.IsVariadic != st.IsVariadic) + return false; + return TypeMatches(decl, pi.TypeSpec, st, typeMap); + } + + static bool TypeMatches(FunctionDeclaration decl, TypeSpec ts, SwiftType st, TypeMapper typeMap) + { + switch (ts.Kind) + { + case TypeSpecKind.Named: + return TypeMatches(decl, ts as NamedTypeSpec, st, typeMap); + case TypeSpecKind.Closure: + return TypeMatches(decl, ts as ClosureTypeSpec, st, typeMap); + case TypeSpecKind.Tuple: + return TypeMatches(decl, ts as TupleTypeSpec, st, typeMap); + case TypeSpecKind.ProtocolList: + return TypeMatches(decl, ts as ProtocolListTypeSpec, st, typeMap); + default: + throw new ArgumentOutOfRangeException(nameof(ts)); + } + } + + static bool TypeMatches(FunctionDeclaration decl, ClosureTypeSpec cs, SwiftType st, TypeMapper typeMap) + { + SwiftBaseFunctionType bft = st as SwiftBaseFunctionType; + return TypeMatches(decl, cs.Arguments, bft.Parameters, typeMap) && + TypeMatches(decl, cs.ReturnType, bft.ReturnType, typeMap); + } + + static bool TypeMatches(FunctionDeclaration decl, TupleTypeSpec ts, SwiftType st, TypeMapper typeMap) + { + var tuple = st as SwiftTupleType; + if (tuple == null || tuple.Contents.Count != ts.Elements.Count) + return false; + for (int i = 0; i < ts.Elements.Count; i++) + { + if (!TypeMatches(decl, ts.Elements[i], tuple.Contents[i], typeMap)) + return false; + } + return true; + } + + static bool TypeMatches(FunctionDeclaration decl, ProtocolListTypeSpec ps, SwiftType st, TypeMapper typeMap) + { + var protoList = st as SwiftProtocolListType; + if (protoList == null || protoList.Protocols.Count != ps.Protocols.Count) + return false; + for (int i = 0; i < ps.Protocols.Count; i++) + { + if (!TypeMatches(decl, ps.Protocols.Keys[i], protoList.Protocols[i], typeMap)) + return false; + } + return true; + } + + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftType st, TypeMapper typeMap) + { + switch (st.Type) + { + case CoreCompoundType.Scalar: + return TypeMatches(decl, ts, st as SwiftBuiltInType, typeMap); + case CoreCompoundType.Class: + return TypeMatches(decl, ts, st as SwiftClassType, typeMap); + case CoreCompoundType.MetaClass: + if (st is SwiftExistentialMetaType exist) + return TypeMatches(decl, ts, exist, typeMap); + else + return TypeMatches(decl, ts, st as SwiftMetaClassType, typeMap); + case CoreCompoundType.BoundGeneric: + return TypeMatches(decl, ts, st as SwiftBoundGenericType, typeMap); + case CoreCompoundType.ProtocolList: + return TypeMatches(decl, ts, st as SwiftProtocolListType, typeMap); + case CoreCompoundType.GenericReference: + return TypeMatches(decl, ts, st as SwiftGenericArgReferenceType, typeMap); + case CoreCompoundType.Struct: + default: + return false; + } + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftGenericArgReferenceType genArg, TypeMapper typeMap) + { + if (genArg.HasAssociatedTypePath) + { + if (!decl.IsProtocolWithAssociatedTypesFullPath(ts, typeMap)) + return false; + var parts = ts.Name.Split('.'); + // parts will have the generic part at 0, genArg will not + if (parts.Length != genArg.AssociatedTypePath.Count + 1) + return false; + var depthAndIndex = decl.GetGenericDepthAndIndex(parts[0]); + if (genArg.Depth != depthAndIndex.Item1 || genArg.Index != depthAndIndex.Item2) + return false; + for (int i = 0; i < genArg.AssociatedTypePath.Count; i++) + { + if (genArg.AssociatedTypePath[i] != parts[i + 1]) + return false; + } + return true; + } + else + { + if (!decl.IsTypeSpecGeneric(ts)) + return false; + var depthAndIndex = decl.GetGenericDepthAndIndex(ts.Name); + return genArg.Depth == depthAndIndex.Item1 && genArg.Index == depthAndIndex.Item2; + } + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftProtocolListType protList, TypeMapper typeMap) + { + if (protList == null) + return false; + if (protList.Protocols.Count == 1 && !ts.IsProtocolList) + { + return TypeMatches(decl, ts, protList.Protocols[0], typeMap); + } + + if (protList.Protocols.Count != ts.GenericParameters.Count || !ts.IsProtocolList) + return false; + for (int i = 0; i < ts.GenericParameters.Count; i++) + { + if (!TypeMatches(decl, ts.GenericParameters[i], protList.Protocols[i], typeMap)) + return false; + } + return true; + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftClassType ct, TypeMapper typeMap) + { + if (ct == null) + return false; + return ts.Name == ct.ClassName.ToFullyQualifiedName(true) || + ts.NameWithoutModule == ct.ClassName.ToFullyQualifiedName(false); + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftBuiltInType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (ts.IsInOut != st.IsReference) + return false; + switch (st.BuiltInType) + { + case CoreBuiltInType.Bool: + return ts.Name == "Swift.Bool"; + case CoreBuiltInType.Double: + return ts.Name == "Swift.Double"; + case CoreBuiltInType.Float: + return ts.Name == "Swift.Float"; + case CoreBuiltInType.Int: + return ts.Name == "Swift.Int"; + case CoreBuiltInType.UInt: + return ts.Name == "Swift.UInt"; + default: + throw new ArgumentOutOfRangeException("st"); + } + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftExistentialMetaType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (st.Protocol.Protocols.Count != 1) + return false; + var protoClass = st.Protocol.Protocols[0]; + if (ts.Name == "Any.Type") + { + return protoClass.ClassName.ToFullyQualifiedName() == "Swift.Any"; + } + if (ts.Name == protoClass.ClassName.ToFullyQualifiedName()) + return true; + if (ts.Name.EndsWith(".Type", StringComparison.Ordinal)) + { + var maybeClassName = ts.Name.Substring(0, ts.Name.Length - ".Type".Length); + return maybeClassName == protoClass.ClassName.ToFullyQualifiedName(); + } + return false; + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftMetaClassType st, TypeMapper typeMap) + { + if (st == null) + return false; + return ts.Name == st.Class.ClassName.ToFullyQualifiedName(true); + } + + static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftBoundGenericType st, TypeMapper typeMap) + { + if (st == null) + return false; + if (!ts.ContainsGenericParameters) + return false; + return TypeMatches(decl, ts.GenericParameters, st.BoundTypes, typeMap); + } + + static bool TypeMatches(FunctionDeclaration decl, List ts, List st, TypeMapper typeMap) + { + if (ts == null || st == null) + return false; + if (ts.Count != st.Count) + return false; + if (ts.Count == 1) + { + // Thanks swift, you're the best... + if (IsVoid(ts[0]) && st[0].IsEmptyTuple) + return true; + } + for (int i = 0; i < ts.Count; i++) + { + if (!TypeMatches(decl, ts[i], st[i], typeMap)) + return false; + } + return true; + } + + static bool IsVoid(TypeSpec ts) + { + var ns = ts as NamedTypeSpec; + return ns != null && (ns.Name == "Void" || ns.Name == "Swift.Void"); + } + } } diff --git a/src/SwiftRuntimeLibrary/Exceptions.cs b/src/SwiftRuntimeLibrary/Exceptions.cs index 6a1bdb68351d..495285d05bec 100644 --- a/src/SwiftRuntimeLibrary/Exceptions.cs +++ b/src/SwiftRuntimeLibrary/Exceptions.cs @@ -3,22 +3,24 @@ using System; -namespace SwiftRuntimeLibrary { - public static class Exceptions { - public static T ThrowOnNull(T o, string name, string message = null) where T : class - { - if (o == null) - ThrowArgumentNull(name, message); - return o!; - } +namespace SwiftRuntimeLibrary +{ + public static class Exceptions + { + public static T ThrowOnNull(T o, string name, string message = null) where T : class + { + if (o == null) + ThrowArgumentNull(name, message); + return o!; + } - static void ThrowArgumentNull(string name, string message = null) - { - name = name ?? "::no name supplied::"; - if (message == null) - throw new ArgumentNullException(name); - else - throw new ArgumentNullException(name, message); - } - } + static void ThrowArgumentNull(string name, string message = null) + { + name = name ?? "::no name supplied::"; + if (message == null) + throw new ArgumentNullException(name); + else + throw new ArgumentNullException(name, message); + } + } } diff --git a/src/SwiftRuntimeLibrary/ISwiftObject.cs b/src/SwiftRuntimeLibrary/ISwiftObject.cs index 0538401dee23..1ededa64b6a8 100644 --- a/src/SwiftRuntimeLibrary/ISwiftObject.cs +++ b/src/SwiftRuntimeLibrary/ISwiftObject.cs @@ -4,9 +4,11 @@ using System; using System.Runtime.InteropServices; -namespace SwiftRuntimeLibrary { - public unsafe interface ISwiftObject : IDisposable { - void* SwiftObject { get; } - } +namespace SwiftRuntimeLibrary +{ + public unsafe interface ISwiftObject : IDisposable + { + void* SwiftObject { get; } + } } diff --git a/src/SyntaxDynamo/CodeElementCollection.cs b/src/SyntaxDynamo/CodeElementCollection.cs index 251a0e5e5256..ccdd7fdc369f 100644 --- a/src/SyntaxDynamo/CodeElementCollection.cs +++ b/src/SyntaxDynamo/CodeElementCollection.cs @@ -5,56 +5,60 @@ using System.Collections.Generic; using System.Linq; -namespace SyntaxDynamo { - public class CodeElementCollection : List, ICodeElementSet where T : ICodeElement { - public CodeElementCollection () : base () - { - } +namespace SyntaxDynamo +{ + public class CodeElementCollection : List, ICodeElementSet where T : ICodeElement + { + public CodeElementCollection() : base() + { + } - #region ICodeElem implementation + #region ICodeElem implementation - public event EventHandler Begin = (s, e) => { }; + public event EventHandler Begin = (s, e) => { }; - public event EventHandler End = (s, e) => { }; + public event EventHandler End = (s, e) => { }; - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } - public virtual void Write (ICodeWriter writer, object o) - { - } + public virtual void Write(ICodeWriter writer, object o) + { + } - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } - #endregion + #endregion - #region ICodeElemSet implementation + #region ICodeElemSet implementation - public System.Collections.Generic.IEnumerable Elements { - get { - return this.Cast (); - } - } + public System.Collections.Generic.IEnumerable Elements + { + get + { + return this.Cast(); + } + } - #endregion + #endregion - } + } } diff --git a/src/SyntaxDynamo/CodeWriter.cs b/src/SyntaxDynamo/CodeWriter.cs index 8789ccc2fd71..5d32962399d9 100644 --- a/src/SyntaxDynamo/CodeWriter.cs +++ b/src/SyntaxDynamo/CodeWriter.cs @@ -5,145 +5,153 @@ using System.Globalization; using System.IO; -namespace SyntaxDynamo { - public class CodeWriter : ICodeWriter { - int charsWrittenThisLine; - bool indentedThisLine; - - const int kSpacesPerIndent = 4; - const int kWrapPoint = 60; - - public CodeWriter (Stream stm) - : this (new StreamWriter (Exceptions.ThrowOnNull (stm, "stm"))) - { - } - - public CodeWriter (TextWriter tw) - { - TextWriter = Exceptions.ThrowOnNull (tw, "tw"); - charsWrittenThisLine = 0; - IndentLevel = 0; - IsAtLineStart = true; - } - - public static void WriteToFile (string fileName, ICodeElement element) - { - using (var stm = new FileStream (fileName, FileMode.Create)) { - CodeWriter writer = new CodeWriter (stm); - element.WriteAll (writer); - writer.TextWriter.Flush (); - } - } - - public static Stream WriteToStream (ICodeElement element) - { - var stm = new MemoryStream (); - var codeWriter = new CodeWriter (stm); - element.WriteAll (codeWriter); - codeWriter.TextWriter.Flush (); - stm.Flush (); - stm.Seek (0, SeekOrigin.Begin); - return stm; - } - - public static string WriteToString (ICodeElement element) - { - using (var reader = new StreamReader (WriteToStream (element))) - return reader.ReadToEnd (); - } - - public TextWriter TextWriter { get; private set; } - - #region ICodeWriter implementation - - public void BeginNewLine (bool prependIndents) - { - Write (Environment.NewLine, false); - if (prependIndents) - WriteIndents (); - IsAtLineStart = true; - } - - public void EndLine () - { - charsWrittenThisLine = 0; - if (indentedThisLine) { - indentedThisLine = false; - // strictly speaking, this test shouldn't be necessary - if (IndentLevel > 0) - Exdent (); - } - } - - public bool IsAtLineStart { get; private set; } - - public void Write (string code, bool allowSplit) - { - var characterEnum = StringInfo.GetTextElementEnumerator (code); - while (characterEnum.MoveNext ()) { - string c = characterEnum.GetTextElement (); - WriteUnicode (c, allowSplit); - } - } - - public void Write (char c, bool allowSplit) - { - Write (c.ToString (), allowSplit); - } - - void WriteUnicode (string c, bool allowSplit) - { - var info = new StringInfo (c); - if (info.LengthInTextElements > 1) - throw new ArgumentOutOfRangeException (nameof (c), $"Expected a single unicode value but got '{c}'"); - WriteNoBookKeeping (c); - IsAtLineStart = false; - charsWrittenThisLine++; - if (allowSplit && charsWrittenThisLine > kWrapPoint && IsWhiteSpace (c)) { - if (!indentedThisLine) { - Indent (); - indentedThisLine = true; - } - WriteNoBookKeeping (Environment.NewLine); - charsWrittenThisLine = 0; - WriteIndents (); - IsAtLineStart = true; - } - } - - bool IsWhiteSpace (string c) { - return c.Length == 1 && Char.IsWhiteSpace (c[0]); - - } - - void WriteNoBookKeeping (string s) - { - TextWriter.Write (s); - } - - void WriteIndents () - { - int totalSpaces = IndentLevel * kSpacesPerIndent; - // know what's embarrassing? When your indents cause breaks which generates more indents. - for (int i = 0; i < totalSpaces; i++) - Write (" ", false); - } - - public void Indent () - { - IndentLevel++; - } - - public void Exdent () - { - if (IndentLevel == 0) - throw new Exception ("IndentLevel is at 0."); - IndentLevel--; - } - - public int IndentLevel { get; private set; } - - #endregion - } +namespace SyntaxDynamo +{ + public class CodeWriter : ICodeWriter + { + int charsWrittenThisLine; + bool indentedThisLine; + + const int kSpacesPerIndent = 4; + const int kWrapPoint = 60; + + public CodeWriter(Stream stm) + : this(new StreamWriter(Exceptions.ThrowOnNull(stm, "stm"))) + { + } + + public CodeWriter(TextWriter tw) + { + TextWriter = Exceptions.ThrowOnNull(tw, "tw"); + charsWrittenThisLine = 0; + IndentLevel = 0; + IsAtLineStart = true; + } + + public static void WriteToFile(string fileName, ICodeElement element) + { + using (var stm = new FileStream(fileName, FileMode.Create)) + { + CodeWriter writer = new CodeWriter(stm); + element.WriteAll(writer); + writer.TextWriter.Flush(); + } + } + + public static Stream WriteToStream(ICodeElement element) + { + var stm = new MemoryStream(); + var codeWriter = new CodeWriter(stm); + element.WriteAll(codeWriter); + codeWriter.TextWriter.Flush(); + stm.Flush(); + stm.Seek(0, SeekOrigin.Begin); + return stm; + } + + public static string WriteToString(ICodeElement element) + { + using (var reader = new StreamReader(WriteToStream(element))) + return reader.ReadToEnd(); + } + + public TextWriter TextWriter { get; private set; } + + #region ICodeWriter implementation + + public void BeginNewLine(bool prependIndents) + { + Write(Environment.NewLine, false); + if (prependIndents) + WriteIndents(); + IsAtLineStart = true; + } + + public void EndLine() + { + charsWrittenThisLine = 0; + if (indentedThisLine) + { + indentedThisLine = false; + // strictly speaking, this test shouldn't be necessary + if (IndentLevel > 0) + Exdent(); + } + } + + public bool IsAtLineStart { get; private set; } + + public void Write(string code, bool allowSplit) + { + var characterEnum = StringInfo.GetTextElementEnumerator(code); + while (characterEnum.MoveNext()) + { + string c = characterEnum.GetTextElement(); + WriteUnicode(c, allowSplit); + } + } + + public void Write(char c, bool allowSplit) + { + Write(c.ToString(), allowSplit); + } + + void WriteUnicode(string c, bool allowSplit) + { + var info = new StringInfo(c); + if (info.LengthInTextElements > 1) + throw new ArgumentOutOfRangeException(nameof(c), $"Expected a single unicode value but got '{c}'"); + WriteNoBookKeeping(c); + IsAtLineStart = false; + charsWrittenThisLine++; + if (allowSplit && charsWrittenThisLine > kWrapPoint && IsWhiteSpace(c)) + { + if (!indentedThisLine) + { + Indent(); + indentedThisLine = true; + } + WriteNoBookKeeping(Environment.NewLine); + charsWrittenThisLine = 0; + WriteIndents(); + IsAtLineStart = true; + } + } + + bool IsWhiteSpace(string c) + { + return c.Length == 1 && Char.IsWhiteSpace(c[0]); + + } + + void WriteNoBookKeeping(string s) + { + TextWriter.Write(s); + } + + void WriteIndents() + { + int totalSpaces = IndentLevel * kSpacesPerIndent; + // know what's embarrassing? When your indents cause breaks which generates more indents. + for (int i = 0; i < totalSpaces; i++) + Write(" ", false); + } + + public void Indent() + { + IndentLevel++; + } + + public void Exdent() + { + if (IndentLevel == 0) + throw new Exception("IndentLevel is at 0."); + IndentLevel--; + } + + public int IndentLevel { get; private set; } + + #endregion + } } diff --git a/src/SyntaxDynamo/CommaListElementCollection.cs b/src/SyntaxDynamo/CommaListElementCollection.cs index a314d203e28c..8aeb8ad982eb 100644 --- a/src/SyntaxDynamo/CommaListElementCollection.cs +++ b/src/SyntaxDynamo/CommaListElementCollection.cs @@ -4,81 +4,85 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo { - public class CommaListElementCollection : List, ICodeElement where T : ICodeElement { - public CommaListElementCollection () - : this ("", "") - { - } - - - public CommaListElementCollection (IEnumerable objs) - : this ("", "", objs) - { - } - - public CommaListElementCollection (string prefix, string suffix) - : base () - { - Prefix = Exceptions.ThrowOnNull (prefix, nameof (prefix)); - Suffix = Exceptions.ThrowOnNull (suffix, nameof (suffix)); - } - - public CommaListElementCollection (string prefix, string suffix, IEnumerable objs, bool newlineAfterEach = false) - : this (prefix, suffix) - { - AddRange (Exceptions.ThrowOnNull (objs, nameof (objs))); - NewlineAfterEach = newlineAfterEach; - } - - - public string Prefix { get; private set; } - public string Suffix { get; private set; } - public bool NewlineAfterEach { get; private set; } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - writer.Write (Prefix, true); - for (int i = 0; i < Count; i++) { - this [i].WriteAll (writer); - if (i < Count - 1) - writer.Write (", ", true); - if (NewlineAfterEach && !writer.IsAtLineStart) { - writer.BeginNewLine (true); - } - } - writer.Write (Suffix, true); - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - } +namespace SyntaxDynamo +{ + public class CommaListElementCollection : List, ICodeElement where T : ICodeElement + { + public CommaListElementCollection() + : this("", "") + { + } + + + public CommaListElementCollection(IEnumerable objs) + : this("", "", objs) + { + } + + public CommaListElementCollection(string prefix, string suffix) + : base() + { + Prefix = Exceptions.ThrowOnNull(prefix, nameof(prefix)); + Suffix = Exceptions.ThrowOnNull(suffix, nameof(suffix)); + } + + public CommaListElementCollection(string prefix, string suffix, IEnumerable objs, bool newlineAfterEach = false) + : this(prefix, suffix) + { + AddRange(Exceptions.ThrowOnNull(objs, nameof(objs))); + NewlineAfterEach = newlineAfterEach; + } + + + public string Prefix { get; private set; } + public string Suffix { get; private set; } + public bool NewlineAfterEach { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + writer.Write(Prefix, true); + for (int i = 0; i < Count; i++) + { + this[i].WriteAll(writer); + if (i < Count - 1) + writer.Write(", ", true); + if (NewlineAfterEach && !writer.IsAtLineStart) + { + writer.BeginNewLine(true); + } + } + writer.Write(Suffix, true); + } + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + } } diff --git a/src/SyntaxDynamo/DecoratedCodeElementCollection.cs b/src/SyntaxDynamo/DecoratedCodeElementCollection.cs index 3b3f4f19d9fe..b8420188ace5 100644 --- a/src/SyntaxDynamo/DecoratedCodeElementCollection.cs +++ b/src/SyntaxDynamo/DecoratedCodeElementCollection.cs @@ -3,77 +3,81 @@ using System.Collections.Generic; -namespace SyntaxDynamo { - public class DecoratedCodeElementCollection : CodeElementCollection where T : ICodeElement { - bool startOnOwnLine, endOnOwnLine, indent; +namespace SyntaxDynamo +{ + public class DecoratedCodeElementCollection : CodeElementCollection where T : ICodeElement + { + bool startOnOwnLine, endOnOwnLine, indent; - public DecoratedCodeElementCollection (string startDecoration, string endDecoration, - bool startOnOwnLine, bool endOnOwnLine, bool indent, - IEnumerable elems) - : base () - { - StartDecoration = startDecoration; - EndDecoration = endDecoration; - this.startOnOwnLine = startOnOwnLine; - this.endOnOwnLine = endOnOwnLine; - this.indent = indent; - if (elems != null) - AddRange (elems); - } + public DecoratedCodeElementCollection(string startDecoration, string endDecoration, + bool startOnOwnLine, bool endOnOwnLine, bool indent, + IEnumerable elems) + : base() + { + StartDecoration = startDecoration; + EndDecoration = endDecoration; + this.startOnOwnLine = startOnOwnLine; + this.endOnOwnLine = endOnOwnLine; + this.indent = indent; + if (elems != null) + AddRange(elems); + } - public DecoratedCodeElementCollection (string startDecoration, string endDecoration, - bool startOnOwnLine, bool endOnOwnLine, bool indent) - : this (startDecoration, endDecoration, startOnOwnLine, endOnOwnLine, indent, null) - { - } + public DecoratedCodeElementCollection(string startDecoration, string endDecoration, + bool startOnOwnLine, bool endOnOwnLine, bool indent) + : this(startDecoration, endDecoration, startOnOwnLine, endOnOwnLine, indent, null) + { + } - public string StartDecoration { get; private set; } - public string EndDecoration { get; private set; } + public string StartDecoration { get; private set; } + public string EndDecoration { get; private set; } - public override void Write (ICodeWriter writer, object o) - { - if (StartDecoration != null) { - if (startOnOwnLine) - writer.BeginNewLine (true); - writer.Write (StartDecoration, true); - if (startOnOwnLine) - writer.EndLine (); - } - if (indent) - writer.Indent (); - } + public override void Write(ICodeWriter writer, object o) + { + if (StartDecoration != null) + { + if (startOnOwnLine) + writer.BeginNewLine(true); + writer.Write(StartDecoration, true); + if (startOnOwnLine) + writer.EndLine(); + } + if (indent) + writer.Indent(); + } - public override void EndWrite (ICodeWriter writer, object o) - { - if (indent) - writer.Exdent (); - if (EndDecoration != null) { - if (endOnOwnLine) - writer.BeginNewLine (true); - writer.Write (EndDecoration, true); - if (endOnOwnLine) - writer.EndLine (); - } + public override void EndWrite(ICodeWriter writer, object o) + { + if (indent) + writer.Exdent(); + if (EndDecoration != null) + { + if (endOnOwnLine) + writer.BeginNewLine(true); + writer.Write(EndDecoration, true); + if (endOnOwnLine) + writer.EndLine(); + } - base.EndWrite (writer, o); - } + base.EndWrite(writer, o); + } - public override string ToString () - { - return string.Format ("{0}{1}{2}", - StartDecoration ?? "", - StartDecoration != null && EndDecoration != null ? "..." : "", - EndDecoration ?? ""); - } + public override string ToString() + { + return string.Format("{0}{1}{2}", + StartDecoration ?? "", + StartDecoration != null && EndDecoration != null ? "..." : "", + EndDecoration ?? ""); + } - public static DecoratedCodeElementCollection CBlock (IEnumerable elems) - { - var col = new DecoratedCodeElementCollection ("{", "}", true, true, true); - if (elems != null) - col.AddRange (elems); - return col; - } - } + public static DecoratedCodeElementCollection CBlock(IEnumerable elems) + { + var col = new DecoratedCodeElementCollection("{", "}", true, true, true); + if (elems != null) + col.AddRange(elems); + return col; + } + } } diff --git a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs index 9e4c9d6e25bc..2d3d8dbd4d08 100644 --- a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs +++ b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs @@ -4,56 +4,59 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo { - public class DelegatedCommaListElemCollection : List, ICodeElement where T : ICodeElement { - Action elementWriter; - public DelegatedCommaListElemCollection (Action elementWriter) - : base () - { - this.elementWriter = Exceptions.ThrowOnNull (elementWriter, nameof(elementWriter)); - } - - public DelegatedCommaListElemCollection (Action elementWriter, IEnumerable objs) - : base () - { - this.elementWriter = Exceptions.ThrowOnNull (elementWriter, nameof (elementWriter)); - AddRange (Exceptions.ThrowOnNull (objs, nameof(objs))); - } - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - for (int i = 0; i < Count; i++) { - elementWriter (writer, i, this [i]); - if (i < Count - 1) - writer.Write (", ", true); - } - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - } +namespace SyntaxDynamo +{ + public class DelegatedCommaListElemCollection : List, ICodeElement where T : ICodeElement + { + Action elementWriter; + public DelegatedCommaListElemCollection(Action elementWriter) + : base() + { + this.elementWriter = Exceptions.ThrowOnNull(elementWriter, nameof(elementWriter)); + } + + public DelegatedCommaListElemCollection(Action elementWriter, IEnumerable objs) + : base() + { + this.elementWriter = Exceptions.ThrowOnNull(elementWriter, nameof(elementWriter)); + AddRange(Exceptions.ThrowOnNull(objs, nameof(objs))); + } + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + for (int i = 0; i < Count; i++) + { + elementWriter(writer, i, this[i]); + if (i < Count - 1) + writer.Write(", ", true); + } + } + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + } } diff --git a/src/SyntaxDynamo/DelegatedSimpleElement.cs b/src/SyntaxDynamo/DelegatedSimpleElement.cs index e9b9ca177a93..f3f4df5fee71 100644 --- a/src/SyntaxDynamo/DelegatedSimpleElement.cs +++ b/src/SyntaxDynamo/DelegatedSimpleElement.cs @@ -3,51 +3,54 @@ using System; -namespace SyntaxDynamo { - public abstract class DelegatedSimpleElement : ICodeElement { - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - LLWrite (writer, o); - } - - protected abstract void LLWrite (ICodeWriter writer, object o); - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - } - - public class LineBreak : DelegatedSimpleElement { - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.EndLine (); - writer.BeginNewLine (true); - } - } +namespace SyntaxDynamo +{ + public abstract class DelegatedSimpleElement : ICodeElement + { + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + LLWrite(writer, o); + } + + protected abstract void LLWrite(ICodeWriter writer, object o); + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + } + + public class LineBreak : DelegatedSimpleElement + { + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.EndLine(); + writer.BeginNewLine(true); + } + } } diff --git a/src/SyntaxDynamo/Exceptions.cs b/src/SyntaxDynamo/Exceptions.cs index 5d6aa86c3599..a6777a75fe94 100644 --- a/src/SyntaxDynamo/Exceptions.cs +++ b/src/SyntaxDynamo/Exceptions.cs @@ -3,19 +3,22 @@ using System; -namespace SyntaxDynamo { - public class Exceptions { - public static T ThrowOnNull (T o, string name, string message = null) where T : class - { - name = name ?? "::no name supplied::"; - if (o == null) { - if (message == null) - throw new ArgumentNullException (name); - else - throw new ArgumentNullException (name, message); - } - return o; - } - } +namespace SyntaxDynamo +{ + public class Exceptions + { + public static T ThrowOnNull(T o, string name, string message = null) where T : class + { + name = name ?? "::no name supplied::"; + if (o == null) + { + if (message == null) + throw new ArgumentNullException(name); + else + throw new ArgumentNullException(name, message); + } + return o; + } + } } diff --git a/src/SyntaxDynamo/Extensions.cs b/src/SyntaxDynamo/Extensions.cs index fb1471437098..561ae3c70c22 100644 --- a/src/SyntaxDynamo/Extensions.cs +++ b/src/SyntaxDynamo/Extensions.cs @@ -4,65 +4,73 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo { - public static class Extensions { - public static void WriteAll (this ICodeElement elem, ICodeWriter writer) - { - object memento = elem.BeginWrite (writer); - elem.Write (writer, memento); - ICodeElementSet set = elem as ICodeElementSet; - if (set != null) { - foreach (ICodeElement sub in set.Elements) { - sub.WriteAll (writer); - } - } - elem.EndWrite (writer, memento); - } +namespace SyntaxDynamo +{ + public static class Extensions + { + public static void WriteAll(this ICodeElement elem, ICodeWriter writer) + { + object memento = elem.BeginWrite(writer); + elem.Write(writer, memento); + ICodeElementSet set = elem as ICodeElementSet; + if (set != null) + { + foreach (ICodeElement sub in set.Elements) + { + sub.WriteAll(writer); + } + } + elem.EndWrite(writer, memento); + } - public static void FireInReverse (this EventHandler handler, object sender, EventArgs args) where T : EventArgs - { - var dels = handler.GetInvocationList (); - for (int i = dels.Length - 1; i >= 0; i--) { - dels [i].DynamicInvoke (new object [] { sender, args }); - } - } + public static void FireInReverse(this EventHandler handler, object sender, EventArgs args) where T : EventArgs + { + var dels = handler.GetInvocationList(); + for (int i = dels.Length - 1; i >= 0; i--) + { + dels[i].DynamicInvoke(new object[] { sender, args }); + } + } - public static IEnumerable Interleave (this IEnumerable contents, T separator, bool includeSeparatorFirst = false) - { - bool first = true; - foreach (T t in contents) { - if (!first || includeSeparatorFirst) - yield return separator; - first = false; - yield return t; - } - } + public static IEnumerable Interleave(this IEnumerable contents, T separator, bool includeSeparatorFirst = false) + { + bool first = true; + foreach (T t in contents) + { + if (!first || includeSeparatorFirst) + yield return separator; + first = false; + yield return t; + } + } - public static IEnumerable BracketInterleave (this IEnumerable contents, T start, T end, T separator, bool includeSeparatorFirst = false) - { - yield return start; - foreach (T t in contents.Interleave (separator, includeSeparatorFirst)) - yield return t; - yield return end; - } + public static IEnumerable BracketInterleave(this IEnumerable contents, T start, T end, T separator, bool includeSeparatorFirst = false) + { + yield return start; + foreach (T t in contents.Interleave(separator, includeSeparatorFirst)) + yield return t; + yield return end; + } - public static T AttachBefore (this T attacher, ICodeElement attachTo) where T : ICodeElement - { - Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); - attachTo.Begin += (s, eventArgs) => { - attacher.WriteAll (eventArgs.Writer); - }; - return attacher; - } + public static T AttachBefore(this T attacher, ICodeElement attachTo) where T : ICodeElement + { + Exceptions.ThrowOnNull(attachTo, nameof(attachTo)); + attachTo.Begin += (s, eventArgs) => + { + attacher.WriteAll(eventArgs.Writer); + }; + return attacher; + } - public static T AttachAfter (this T attacher, ICodeElement attachTo) where T : ICodeElement - { - Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); - attachTo.End += (s, eventArgs) => { - attacher.WriteAll (eventArgs.Writer); - }; - return attacher; - } - } + public static T AttachAfter(this T attacher, ICodeElement attachTo) where T : ICodeElement + { + Exceptions.ThrowOnNull(attachTo, nameof(attachTo)); + attachTo.End += (s, eventArgs) => + { + attacher.WriteAll(eventArgs.Writer); + }; + return attacher; + } + } } diff --git a/src/SyntaxDynamo/ICodeElement.cs b/src/SyntaxDynamo/ICodeElement.cs index 855364f31605..3346c97dea40 100644 --- a/src/SyntaxDynamo/ICodeElement.cs +++ b/src/SyntaxDynamo/ICodeElement.cs @@ -3,22 +3,24 @@ using System; -namespace SyntaxDynamo { - public interface ICodeElement { - // these three methods represent the memento pattern. The object returned is only ever used by - // the ICodeElem. - object BeginWrite (ICodeWriter writer); - void Write (ICodeWriter writer, object o); - void EndWrite (ICodeWriter writer, object o); +namespace SyntaxDynamo +{ + public interface ICodeElement + { + // these three methods represent the memento pattern. The object returned is only ever used by + // the ICodeElem. + object BeginWrite(ICodeWriter writer); + void Write(ICodeWriter writer, object o); + void EndWrite(ICodeWriter writer, object o); - // These events seem redundant, but they are intended for use for non-structural code elements - // such as block comments or #region or #if/#else/#endif + // These events seem redundant, but they are intended for use for non-structural code elements + // such as block comments or #region or #if/#else/#endif - // Begin should be fired by BeginWrite BEFORE anything is written - event EventHandler Begin; - // Note, when you implement End, it should use GetInvocationList and fire in reverse order. - // End should be fired by EndWrite AFTER anything is written - event EventHandler End; - } + // Begin should be fired by BeginWrite BEFORE anything is written + event EventHandler Begin; + // Note, when you implement End, it should use GetInvocationList and fire in reverse order. + // End should be fired by EndWrite AFTER anything is written + event EventHandler End; + } } diff --git a/src/SyntaxDynamo/ICodeElementSet.cs b/src/SyntaxDynamo/ICodeElementSet.cs index 63c13176bb0f..67f85843db57 100644 --- a/src/SyntaxDynamo/ICodeElementSet.cs +++ b/src/SyntaxDynamo/ICodeElementSet.cs @@ -3,9 +3,11 @@ using System.Collections.Generic; -namespace SyntaxDynamo { - public interface ICodeElementSet : ICodeElement { - IEnumerable Elements { get; } - } +namespace SyntaxDynamo +{ + public interface ICodeElementSet : ICodeElement + { + IEnumerable Elements { get; } + } } diff --git a/src/SyntaxDynamo/ICodeWriter.cs b/src/SyntaxDynamo/ICodeWriter.cs index 0871e20fac6e..e10015db8fb9 100644 --- a/src/SyntaxDynamo/ICodeWriter.cs +++ b/src/SyntaxDynamo/ICodeWriter.cs @@ -3,16 +3,18 @@ using System; -namespace SyntaxDynamo { - public interface ICodeWriter { - void BeginNewLine (bool prependIndents); - void EndLine (); - void Write (char c, bool allowSplit); - void Write (string code, bool allowSplit); - void Indent (); - void Exdent (); - int IndentLevel { get; } - bool IsAtLineStart { get; } - } +namespace SyntaxDynamo +{ + public interface ICodeWriter + { + void BeginNewLine(bool prependIndents); + void EndLine(); + void Write(char c, bool allowSplit); + void Write(string code, bool allowSplit); + void Indent(); + void Exdent(); + int IndentLevel { get; } + bool IsAtLineStart { get; } + } } diff --git a/src/SyntaxDynamo/LabeledCodeElementCollection.cs b/src/SyntaxDynamo/LabeledCodeElementCollection.cs index c4ec14215dd2..f829f486d5d9 100644 --- a/src/SyntaxDynamo/LabeledCodeElementCollection.cs +++ b/src/SyntaxDynamo/LabeledCodeElementCollection.cs @@ -4,61 +4,65 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo { - public class LabeledCodeElementCollection : ICodeElementSet where T : ICodeElement { - public LabeledCodeElementCollection (SimpleLineElement label, CodeElementCollection block) - { - Label = Exceptions.ThrowOnNull (label, nameof(label)); - Block = Exceptions.ThrowOnNull (block, nameof(block)); - } - - public SimpleLineElement Label { get; private set; } - public CodeElementCollection Block { get; private set; } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - yield return Label; - yield return Block; - } - } - - #endregion - - } +namespace SyntaxDynamo +{ + public class LabeledCodeElementCollection : ICodeElementSet where T : ICodeElement + { + public LabeledCodeElementCollection(SimpleLineElement label, CodeElementCollection block) + { + Label = Exceptions.ThrowOnNull(label, nameof(label)); + Block = Exceptions.ThrowOnNull(block, nameof(block)); + } + + public SimpleLineElement Label { get; private set; } + public CodeElementCollection Block { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + } + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements + { + get + { + yield return Label; + yield return Block; + } + } + + #endregion + + } } diff --git a/src/SyntaxDynamo/LineCodeElementCollection.cs b/src/SyntaxDynamo/LineCodeElementCollection.cs index 5b750cd86243..34ca0376e032 100644 --- a/src/SyntaxDynamo/LineCodeElementCollection.cs +++ b/src/SyntaxDynamo/LineCodeElementCollection.cs @@ -3,51 +3,54 @@ using System.Collections.Generic; -namespace SyntaxDynamo { - public class LineCodeElementCollection : CodeElementCollection where T : ICodeElement { - bool indent, prependIndents, isSingleLine; - public LineCodeElementCollection (IEnumerable elems, bool indent, bool prependIndents) - : this (elems, true, indent, prependIndents) - { - } - - public LineCodeElementCollection (bool isSingleLine, bool indent, bool prependIndents) - : this (null, isSingleLine, indent, prependIndents) - { - } - - public LineCodeElementCollection (IEnumerable elems, bool isSingleLine, bool indent, bool prependIndents) - { - this.isSingleLine = isSingleLine; - this.indent = indent; - this.prependIndents = prependIndents; - if (elems != null) - AddRange (elems); - } - - - public override void Write (ICodeWriter writer, object o) - { - if (isSingleLine) { - if (indent) - writer.Indent (); - writer.BeginNewLine (prependIndents); - } - } - - protected override void OnEndWrite (WriteEventArgs args) - { - if (isSingleLine) - args.Writer.EndLine (); - base.OnEndWrite (args); - } - - public LineCodeElementCollection And (T elem) - { - Add (elem); - return this; - } - - } +namespace SyntaxDynamo +{ + public class LineCodeElementCollection : CodeElementCollection where T : ICodeElement + { + bool indent, prependIndents, isSingleLine; + public LineCodeElementCollection(IEnumerable elems, bool indent, bool prependIndents) + : this(elems, true, indent, prependIndents) + { + } + + public LineCodeElementCollection(bool isSingleLine, bool indent, bool prependIndents) + : this(null, isSingleLine, indent, prependIndents) + { + } + + public LineCodeElementCollection(IEnumerable elems, bool isSingleLine, bool indent, bool prependIndents) + { + this.isSingleLine = isSingleLine; + this.indent = indent; + this.prependIndents = prependIndents; + if (elems != null) + AddRange(elems); + } + + + public override void Write(ICodeWriter writer, object o) + { + if (isSingleLine) + { + if (indent) + writer.Indent(); + writer.BeginNewLine(prependIndents); + } + } + + protected override void OnEndWrite(WriteEventArgs args) + { + if (isSingleLine) + args.Writer.EndLine(); + base.OnEndWrite(args); + } + + public LineCodeElementCollection And(T elem) + { + Add(elem); + return this; + } + + } } diff --git a/src/SyntaxDynamo/SimpleElement.cs b/src/SyntaxDynamo/SimpleElement.cs index 46ccad436d5d..015f5dca3148 100644 --- a/src/SyntaxDynamo/SimpleElement.cs +++ b/src/SyntaxDynamo/SimpleElement.cs @@ -3,57 +3,59 @@ using System; -namespace SyntaxDynamo { - public class SimpleElement : ICodeElement { - bool allowSplit; - public SimpleElement (string label, bool allowSplit = false) - { - Label = label; - this.allowSplit = allowSplit; - } - - public string Label { get; private set; } - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - writer.Write (Label, allowSplit); - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - public override string ToString () - { - return Label; - } - - static SimpleElement spacer = new SimpleElement (" ", true); - public static SimpleElement Spacer { get { return spacer; } } - } +namespace SyntaxDynamo +{ + public class SimpleElement : ICodeElement + { + bool allowSplit; + public SimpleElement(string label, bool allowSplit = false) + { + Label = label; + this.allowSplit = allowSplit; + } + + public string Label { get; private set; } + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + writer.Write(Label, allowSplit); + } + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + + public override string ToString() + { + return Label; + } + + static SimpleElement spacer = new SimpleElement(" ", true); + public static SimpleElement Spacer { get { return spacer; } } + } } diff --git a/src/SyntaxDynamo/SimpleLineElement.cs b/src/SyntaxDynamo/SimpleLineElement.cs index 63e70582604d..fac2ca831a64 100644 --- a/src/SyntaxDynamo/SimpleLineElement.cs +++ b/src/SyntaxDynamo/SimpleLineElement.cs @@ -3,62 +3,64 @@ using System; -namespace SyntaxDynamo { - public class SimpleLineElement : ICodeElement { - bool indent, prependIndents, allowSplit; +namespace SyntaxDynamo +{ + public class SimpleLineElement : ICodeElement + { + bool indent, prependIndents, allowSplit; - public SimpleLineElement (string contents, bool indent, bool prependIdents, bool allowSplit) - { - Contents = contents ?? ""; - this.indent = indent; - this.prependIndents = prependIdents; - this.allowSplit = allowSplit; - } + public SimpleLineElement(string contents, bool indent, bool prependIdents, bool allowSplit) + { + Contents = contents ?? ""; + this.indent = indent; + this.prependIndents = prependIdents; + this.allowSplit = allowSplit; + } - public string Contents { get; private set; } + public string Contents { get; private set; } - #region ICodeElem implementation + #region ICodeElem implementation - public event EventHandler Begin = (s, e) => { }; + public event EventHandler Begin = (s, e) => { }; - public event EventHandler End = (s, e) => { }; + public event EventHandler End = (s, e) => { }; - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } - public void Write (ICodeWriter writer, object o) - { - if (indent) - writer.Indent (); - writer.BeginNewLine (prependIndents); - writer.Write (Contents, allowSplit); - writer.EndLine (); - } + public void Write(ICodeWriter writer, object o) + { + if (indent) + writer.Indent(); + writer.BeginNewLine(prependIndents); + writer.Write(Contents, allowSplit); + writer.EndLine(); + } - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } - #endregion + #endregion - public override string ToString () - { - return Contents; - } - } + public override string ToString() + { + return Contents; + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs index 11c5acda9d99..f945c23a7ff8 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs @@ -1,35 +1,38 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SyntaxDynamo.CSLang { - public class CSArgument : DelegatedSimpleElement { - public CSArgument (ICSExpression expr) - { - Value = Exceptions.ThrowOnNull (expr, nameof(expr)); - } +namespace SyntaxDynamo.CSLang +{ + public class CSArgument : DelegatedSimpleElement + { + public CSArgument(ICSExpression expr) + { + Value = Exceptions.ThrowOnNull(expr, nameof(expr)); + } - public ICSExpression Value { get; private set; } + public ICSExpression Value { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - Value.WriteAll (writer); - } - } + protected override void LLWrite(ICodeWriter writer, object o) + { + Value.WriteAll(writer); + } + } - public class CSArgumentList : CommaListElementCollection { + public class CSArgumentList : CommaListElementCollection + { - public void Add (ICSExpression expr) - { - Add (new CSArgument (expr)); - } + public void Add(ICSExpression expr) + { + Add(new CSArgument(expr)); + } - public static CSArgumentList FromExpressions (params ICSExpression [] exprs) - { - var al = new CSArgumentList (); - foreach (var ex in exprs) - al.Add (new CSArgument (ex)); - return al; - } - } + public static CSArgumentList FromExpressions(params ICSExpression[] exprs) + { + var al = new CSArgumentList(); + foreach (var ex in exprs) + al.Add(new CSArgument(ex)); + return al; + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs index 01bca40d5272..fb37e94a94e5 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs @@ -6,110 +6,112 @@ namespace SyntaxDynamo.CSLang { - public class CSArray1D : CSBaseExpression - { - public CSArray1D (CSIdentifier name, CommaListElementCollection paramList) - { - Name = Exceptions.ThrowOnNull (name, "name"); - Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); - } - - public CSArray1D(string name, params CSBaseExpression[] parameters) - : this(new CSIdentifier(name), new CommaListElementCollection(parameters)) - { - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Name.WriteAll (writer); - writer.Write ("[", false); - Parameters.WriteAll (writer); - writer.Write ("]", false); - } - - public CSIdentifier Name { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - - public static CSArray1D New(CSSimpleType type, bool isStackAlloc, params CSBaseExpression[] parameters) - { - string ID = (isStackAlloc ? "stackalloc " : "new ") + type.Name; - return new CSArray1D (ID, parameters); - } - } - - public class CSArray1DInitialized : CSBaseExpression { - public CSArray1DInitialized(CSType type, CommaListElementCollection initializers) - { - Type = Exceptions.ThrowOnNull (type, "type"); - Parameters = Exceptions.ThrowOnNull (initializers, "initializers"); - } - - public CSArray1DInitialized(CSType type, params CSBaseExpression[] parameters) - : this(type, new CommaListElementCollection(parameters)) - { - } - - public CSArray1DInitialized(string typeName, params CSBaseExpression[] parameters) - : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) - { - } - - public CSArray1DInitialized(string typeName, IEnumerable parameters) - : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) - { - } - - public CSType Type { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("new ", true); - Type.WriteAll (writer); - writer.Write ("[", false); - writer.Write ("] ", true); - writer.Write ("{ ", true); - Parameters.WriteAll (writer); - writer.Write ("}", false); - } - - } - - public class CSListInitialized : CSBaseExpression { - public CSListInitialized (CSType type, CommaListElementCollection initializers) - { - Type = Exceptions.ThrowOnNull (type, "type"); - Parameters = Exceptions.ThrowOnNull (initializers, "initializers"); - } - - public CSListInitialized (CSType type, params CSBaseExpression [] parameters) - : this (type, new CommaListElementCollection (parameters)) - { - } - - public CSListInitialized (string typeName, params CSBaseExpression [] parameters) - : this (new CSSimpleType (typeName), new CommaListElementCollection (parameters)) - { - } - - public CSListInitialized (string typeName, IEnumerable parameters) - : this (new CSSimpleType (typeName), new CommaListElementCollection (parameters)) - { - } - - public CSType Type { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("new List<", true); - Type.WriteAll (writer); - writer.Write (">", true); - writer.Write ("(", false); - writer.Write (") ", true); - writer.Write ("{ ", true); - Parameters.WriteAll (writer); - writer.Write ("}", false); - } - - } + public class CSArray1D : CSBaseExpression + { + public CSArray1D(CSIdentifier name, CommaListElementCollection paramList) + { + Name = Exceptions.ThrowOnNull(name, "name"); + Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + } + + public CSArray1D(string name, params CSBaseExpression[] parameters) + : this(new CSIdentifier(name), new CommaListElementCollection(parameters)) + { + } + + protected override void LLWrite(ICodeWriter writer, object o) + { + Name.WriteAll(writer); + writer.Write("[", false); + Parameters.WriteAll(writer); + writer.Write("]", false); + } + + public CSIdentifier Name { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + public static CSArray1D New(CSSimpleType type, bool isStackAlloc, params CSBaseExpression[] parameters) + { + string ID = (isStackAlloc ? "stackalloc " : "new ") + type.Name; + return new CSArray1D(ID, parameters); + } + } + + public class CSArray1DInitialized : CSBaseExpression + { + public CSArray1DInitialized(CSType type, CommaListElementCollection initializers) + { + Type = Exceptions.ThrowOnNull(type, "type"); + Parameters = Exceptions.ThrowOnNull(initializers, "initializers"); + } + + public CSArray1DInitialized(CSType type, params CSBaseExpression[] parameters) + : this(type, new CommaListElementCollection(parameters)) + { + } + + public CSArray1DInitialized(string typeName, params CSBaseExpression[] parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSArray1DInitialized(string typeName, IEnumerable parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("new ", true); + Type.WriteAll(writer); + writer.Write("[", false); + writer.Write("] ", true); + writer.Write("{ ", true); + Parameters.WriteAll(writer); + writer.Write("}", false); + } + + } + + public class CSListInitialized : CSBaseExpression + { + public CSListInitialized(CSType type, CommaListElementCollection initializers) + { + Type = Exceptions.ThrowOnNull(type, "type"); + Parameters = Exceptions.ThrowOnNull(initializers, "initializers"); + } + + public CSListInitialized(CSType type, params CSBaseExpression[] parameters) + : this(type, new CommaListElementCollection(parameters)) + { + } + + public CSListInitialized(string typeName, params CSBaseExpression[] parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSListInitialized(string typeName, IEnumerable parameters) + : this(new CSSimpleType(typeName), new CommaListElementCollection(parameters)) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("new List<", true); + Type.WriteAll(writer); + writer.Write(">", true); + writer.Write("(", false); + writer.Write(") ", true); + writer.Write("{ ", true); + Parameters.WriteAll(writer); + writer.Write("}", false); + } + + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs index db23c117c330..8c717c19721f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs @@ -4,76 +4,79 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSAssignment : CSBaseExpression, ICSLineable { - public CSAssignment (CSBaseExpression lhs, CSAssignmentOperator op, CSBaseExpression rhs) - { - Target = Exceptions.ThrowOnNull (lhs, "lhs"); - Value = Exceptions.ThrowOnNull (rhs, "rhs"); - Operation = op; - } +namespace SyntaxDynamo.CSLang +{ + public class CSAssignment : CSBaseExpression, ICSLineable + { + public CSAssignment(CSBaseExpression lhs, CSAssignmentOperator op, CSBaseExpression rhs) + { + Target = Exceptions.ThrowOnNull(lhs, "lhs"); + Value = Exceptions.ThrowOnNull(rhs, "rhs"); + Operation = op; + } - public CSAssignment(string lhs, CSAssignmentOperator op, CSBaseExpression rhs) - : this(new CSIdentifier(Exceptions.ThrowOnNull(lhs, "lhs")), op, rhs) - { - } + public CSAssignment(string lhs, CSAssignmentOperator op, CSBaseExpression rhs) + : this(new CSIdentifier(Exceptions.ThrowOnNull(lhs, "lhs")), op, rhs) + { + } - protected override void LLWrite (ICodeWriter writer, object o) - { - Target.WriteAll (writer); - writer.Write (string.Format (" {0} ", ToAssignmentOpString (Operation)), true); - Value.WriteAll (writer); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + Target.WriteAll(writer); + writer.Write(string.Format(" {0} ", ToAssignmentOpString(Operation)), true); + Value.WriteAll(writer); + } - public CSBaseExpression Target { get; private set; } - public CSBaseExpression Value { get; private set; } - public CSAssignmentOperator Operation { get; private set; } + public CSBaseExpression Target { get; private set; } + public CSBaseExpression Value { get; private set; } + public CSAssignmentOperator Operation { get; private set; } - static string ToAssignmentOpString(CSAssignmentOperator op) - { - switch (op) { - case CSAssignmentOperator.Assign: - return "="; - case CSAssignmentOperator.AddAssign: - return "+="; - case CSAssignmentOperator.SubAssign: - return "-="; - case CSAssignmentOperator.MulAssign: - return "*="; - case CSAssignmentOperator.DivAssign: - return "/="; - case CSAssignmentOperator.ModAssign: - return "%="; - case CSAssignmentOperator.AndAssign: - return "&="; - case CSAssignmentOperator.OrAssign: - return "|="; - case CSAssignmentOperator.XorAssign: - return "^="; - default: - throw new ArgumentOutOfRangeException ("op"); - } - } + static string ToAssignmentOpString(CSAssignmentOperator op) + { + switch (op) + { + case CSAssignmentOperator.Assign: + return "="; + case CSAssignmentOperator.AddAssign: + return "+="; + case CSAssignmentOperator.SubAssign: + return "-="; + case CSAssignmentOperator.MulAssign: + return "*="; + case CSAssignmentOperator.DivAssign: + return "/="; + case CSAssignmentOperator.ModAssign: + return "%="; + case CSAssignmentOperator.AndAssign: + return "&="; + case CSAssignmentOperator.OrAssign: + return "|="; + case CSAssignmentOperator.XorAssign: + return "^="; + default: + throw new ArgumentOutOfRangeException("op"); + } + } - public static CSLine Assign(string name, CSAssignmentOperator op, CSBaseExpression value) - { - return new CSLine (new CSAssignment (name, op, value)); - } + public static CSLine Assign(string name, CSAssignmentOperator op, CSBaseExpression value) + { + return new CSLine(new CSAssignment(name, op, value)); + } - public static CSLine Assign(string name, CSBaseExpression value) - { - return Assign (name, CSAssignmentOperator.Assign, value); - } + public static CSLine Assign(string name, CSBaseExpression value) + { + return Assign(name, CSAssignmentOperator.Assign, value); + } - public static CSLine Assign(CSBaseExpression name, CSBaseExpression value) - { - return Assign (name, CSAssignmentOperator.Assign, value); - } + public static CSLine Assign(CSBaseExpression name, CSBaseExpression value) + { + return Assign(name, CSAssignmentOperator.Assign, value); + } - public static CSLine Assign(CSBaseExpression name, CSAssignmentOperator op, CSBaseExpression value) - { - return new CSLine (new CSAssignment (name, op, value)); - } - } + public static CSLine Assign(CSBaseExpression name, CSAssignmentOperator op, CSBaseExpression value) + { + return new CSLine(new CSAssignment(name, op, value)); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs index 56504c47c3ae..6ed7aca85208 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs @@ -4,86 +4,89 @@ using System; using System.Runtime.InteropServices; -namespace SyntaxDynamo.CSLang { - public class CSAttribute : LineCodeElementCollection { - public CSAttribute (CSIdentifier name, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) - : base (isSingleLine, false, isSingleLine) - { - Add (new SimpleElement ("[")); - if (isReturn) - Add (new SimpleElement ("return:")); - Add (Exceptions.ThrowOnNull (name, nameof(name))); - if (args != null) { - Add (new SimpleElement ("(")); - Add (args); - Add (new SimpleElement (")")); - } - Add (new SimpleElement ("]")); - } +namespace SyntaxDynamo.CSLang +{ + public class CSAttribute : LineCodeElementCollection + { + public CSAttribute(CSIdentifier name, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) + : base(isSingleLine, false, isSingleLine) + { + Add(new SimpleElement("[")); + if (isReturn) + Add(new SimpleElement("return:")); + Add(Exceptions.ThrowOnNull(name, nameof(name))); + if (args != null) + { + Add(new SimpleElement("(")); + Add(args); + Add(new SimpleElement(")")); + } + Add(new SimpleElement("]")); + } - public CSAttribute (string name, CSArgumentList args) - : this (new CSIdentifier (name), args) - { - } + public CSAttribute(string name, CSArgumentList args) + : this(new CSIdentifier(name), args) + { + } - public CSAttribute (string name, params ICSExpression [] exprs) - : this (new CSIdentifier(name), CSArgumentList.FromExpressions (exprs)) - { - } + public CSAttribute(string name, params ICSExpression[] exprs) + : this(new CSIdentifier(name), CSArgumentList.FromExpressions(exprs)) + { + } - // DllImport("msvcrt.dll", EntryPoint="puts") - public static CSAttribute DllImport (string dllName, string entryPoint = null) - { - CSArgumentList args = new CSArgumentList (); - args.Add (CSConstant.Val (dllName)); - if (entryPoint != null) - args.Add (new CSAssignment ("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val (entryPoint))); - return new CSAttribute (new CSIdentifier ("DllImport"), args, true); - } + // DllImport("msvcrt.dll", EntryPoint="puts") + public static CSAttribute DllImport(string dllName, string entryPoint = null) + { + CSArgumentList args = new CSArgumentList(); + args.Add(CSConstant.Val(dllName)); + if (entryPoint != null) + args.Add(new CSAssignment("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val(entryPoint))); + return new CSAttribute(new CSIdentifier("DllImport"), args, true); + } - public static CSAttribute DllImport (CSBaseExpression dllName, string entryPoint = null) - { - CSArgumentList args = new CSArgumentList (); - args.Add (dllName); - if (entryPoint != null) - args.Add (new CSAssignment ("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val (entryPoint))); - return new CSAttribute (new CSIdentifier ("DllImport"), args, true); - } + public static CSAttribute DllImport(CSBaseExpression dllName, string entryPoint = null) + { + CSArgumentList args = new CSArgumentList(); + args.Add(dllName); + if (entryPoint != null) + args.Add(new CSAssignment("EntryPoint", CSAssignmentOperator.Assign, CSConstant.Val(entryPoint))); + return new CSAttribute(new CSIdentifier("DllImport"), args, true); + } - static CSAttribute returnMarshalAsI1 = new CSAttribute ("return: MarshalAs", new CSIdentifier ("UnmanagedType.I1")); + static CSAttribute returnMarshalAsI1 = new CSAttribute("return: MarshalAs", new CSIdentifier("UnmanagedType.I1")); - public static CSAttribute ReturnMarshalAsI1 => returnMarshalAsI1; + public static CSAttribute ReturnMarshalAsI1 => returnMarshalAsI1; - public static CSAttribute FieldOffset (int offset) - { - CSArgumentList args = new CSArgumentList (); - args.Add (CSConstant.Val (offset)); - return new CSAttribute (new CSIdentifier ("FieldOffset"), args, true); - } + public static CSAttribute FieldOffset(int offset) + { + CSArgumentList args = new CSArgumentList(); + args.Add(CSConstant.Val(offset)); + return new CSAttribute(new CSIdentifier("FieldOffset"), args, true); + } - public static CSAttribute LayoutKind (LayoutKind layout) - { - CSArgumentList args = new CSArgumentList (); - args.Add (new CSIdentifier (String.Format ("LayoutKind.{0}", layout))); - return new CSAttribute (new CSIdentifier ("StructLayout"), args, true); - } + public static CSAttribute LayoutKind(LayoutKind layout) + { + CSArgumentList args = new CSArgumentList(); + args.Add(new CSIdentifier(String.Format("LayoutKind.{0}", layout))); + return new CSAttribute(new CSIdentifier("StructLayout"), args, true); + } - public static CSAttribute FromAttr (Type attribute, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) - { - Exceptions.ThrowOnNull (attribute, nameof(attribute)); - if (!attribute.IsSubclassOf (typeof (Attribute))) - throw new ArgumentException (String.Format ("Type {0} is not an Attribute type.", attribute.Name), nameof(attribute)); - var name = attribute.Name.EndsWith ("Attribute") ? - attribute.Name.Substring (0, attribute.Name.Length - "Attribute".Length) : attribute.Name; - return new CSAttribute (new CSIdentifier (name), args, isSingleLine, isReturn); - } + public static CSAttribute FromAttr(Type attribute, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) + { + Exceptions.ThrowOnNull(attribute, nameof(attribute)); + if (!attribute.IsSubclassOf(typeof(Attribute))) + throw new ArgumentException(String.Format("Type {0} is not an Attribute type.", attribute.Name), nameof(attribute)); + var name = attribute.Name.EndsWith("Attribute") ? + attribute.Name.Substring(0, attribute.Name.Length - "Attribute".Length) : attribute.Name; + return new CSAttribute(new CSIdentifier(name), args, isSingleLine, isReturn); + } - public static CSAttribute MarshalAsFunctionPointer () - { - CSArgumentList list = new CSArgumentList (); - list.Add (new CSArgument (new CSIdentifier ("UnmanagedType.FunctionPtr"))); - return FromAttr (typeof (MarshalAsAttribute), list, false); - } - } + public static CSAttribute MarshalAsFunctionPointer() + { + CSArgumentList list = new CSArgumentList(); + list.Add(new CSArgument(new CSIdentifier("UnmanagedType.FunctionPtr"))); + return FromAttr(typeof(MarshalAsAttribute), list, false); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs index 92a71f61eaa0..5c6cf0425409 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs @@ -4,94 +4,96 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public abstract class CSBaseExpression : DelegatedSimpleElement, ICSExpression { - public CSBaseExpression Dot (CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Dot, this, rhs); - } - public static CSBaseExpression operator + (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Add, lhs, rhs); - } - public static CSBaseExpression operator - (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Sub, lhs, rhs); - } - public static CSBaseExpression operator * (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Mul, lhs, rhs); - } - public static CSBaseExpression operator / (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Div, lhs, rhs); - } - public static CSBaseExpression operator % (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Mod, lhs, rhs); - } - public static CSBaseExpression operator < (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Less, lhs, rhs); - } - public static CSBaseExpression operator > (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Greater, lhs, rhs); - } - public static CSBaseExpression operator == (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.Equal, lhs, rhs); - } - public static CSBaseExpression operator != (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.NotEqual, lhs, rhs); - } - public static CSBaseExpression operator <= (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.LessEqual, lhs, rhs); - } - public static CSBaseExpression operator >= (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.GreaterEqual, lhs, rhs); - } - public static CSBaseExpression operator & (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.BitAnd, lhs, rhs); - } - public static CSBaseExpression operator | (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.BitOr, lhs, rhs); - } - public static CSBaseExpression operator ^ (CSBaseExpression lhs, CSBaseExpression rhs) - { - return new CSBinaryExpression (CSBinaryOperator.BitXor, lhs, rhs); - } - public static CSBaseExpression operator << (CSBaseExpression lhs, int bits) - { - return new CSBinaryExpression (CSBinaryOperator.LeftShift, lhs, CSConstant.Val (bits)); - } - public static CSBaseExpression operator >> (CSBaseExpression lhs, int bits) - { - return new CSBinaryExpression (CSBinaryOperator.RightShift, lhs, CSConstant.Val (bits)); - } - public override bool Equals(object obj) - { - if (obj == null || GetType() != obj.GetType()) - { - return false; - } +namespace SyntaxDynamo.CSLang +{ + public abstract class CSBaseExpression : DelegatedSimpleElement, ICSExpression + { + public CSBaseExpression Dot(CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Dot, this, rhs); + } + public static CSBaseExpression operator +(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Add, lhs, rhs); + } + public static CSBaseExpression operator -(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Sub, lhs, rhs); + } + public static CSBaseExpression operator *(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Mul, lhs, rhs); + } + public static CSBaseExpression operator /(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Div, lhs, rhs); + } + public static CSBaseExpression operator %(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Mod, lhs, rhs); + } + public static CSBaseExpression operator <(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Less, lhs, rhs); + } + public static CSBaseExpression operator >(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Greater, lhs, rhs); + } + public static CSBaseExpression operator ==(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.Equal, lhs, rhs); + } + public static CSBaseExpression operator !=(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.NotEqual, lhs, rhs); + } + public static CSBaseExpression operator <=(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.LessEqual, lhs, rhs); + } + public static CSBaseExpression operator >=(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.GreaterEqual, lhs, rhs); + } + public static CSBaseExpression operator &(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.BitAnd, lhs, rhs); + } + public static CSBaseExpression operator |(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.BitOr, lhs, rhs); + } + public static CSBaseExpression operator ^(CSBaseExpression lhs, CSBaseExpression rhs) + { + return new CSBinaryExpression(CSBinaryOperator.BitXor, lhs, rhs); + } + public static CSBaseExpression operator <<(CSBaseExpression lhs, int bits) + { + return new CSBinaryExpression(CSBinaryOperator.LeftShift, lhs, CSConstant.Val(bits)); + } + public static CSBaseExpression operator >>(CSBaseExpression lhs, int bits) + { + return new CSBinaryExpression(CSBinaryOperator.RightShift, lhs, CSConstant.Val(bits)); + } + public override bool Equals(object obj) + { + if (obj == null || GetType() != obj.GetType()) + { + return false; + } - // Add your custom equality logic here + // Add your custom equality logic here - return base.Equals(obj); - } + return base.Equals(obj); + } - public override int GetHashCode() - { - // Add your custom hash code logic here + public override int GetHashCode() + { + // Add your custom hash code logic here - return base.GetHashCode(); - } - } + return base.GetHashCode(); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs index 7fdb393d736f..cecd457a58cd 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs @@ -4,77 +4,80 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSBinaryExpression : CSBaseExpression { - public CSBinaryExpression (CSBinaryOperator op, ICSExpression lhs, ICSExpression rhs) - { - Operation = op; - Left = Exceptions.ThrowOnNull (lhs, "lhs"); - Right = Exceptions.ThrowOnNull (rhs, "rhs"); - } +namespace SyntaxDynamo.CSLang +{ + public class CSBinaryExpression : CSBaseExpression + { + public CSBinaryExpression(CSBinaryOperator op, ICSExpression lhs, ICSExpression rhs) + { + Operation = op; + Left = Exceptions.ThrowOnNull(lhs, "lhs"); + Right = Exceptions.ThrowOnNull(rhs, "rhs"); + } - protected override void LLWrite (ICodeWriter writer, object o) - { - Left.WriteAll (writer); - writer.Write (string.Format (Operation == CSBinaryOperator.Dot ? "{0}" : " {0} ", OpToString (Operation)), true); - Right.WriteAll (writer); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + Left.WriteAll(writer); + writer.Write(string.Format(Operation == CSBinaryOperator.Dot ? "{0}" : " {0} ", OpToString(Operation)), true); + Right.WriteAll(writer); + } - public CSBinaryOperator Operation { get; private set; } - public ICSExpression Left { get; private set; } - public ICSExpression Right { get; private set; } + public CSBinaryOperator Operation { get; private set; } + public ICSExpression Left { get; private set; } + public ICSExpression Right { get; private set; } - static string OpToString (CSBinaryOperator op) - { - switch (op) { - case CSBinaryOperator.Add: - return "+"; - case CSBinaryOperator.Sub: - return "-"; - case CSBinaryOperator.Mul: - return "*"; - case CSBinaryOperator.Div: - return "/"; - case CSBinaryOperator.Mod: - return "%"; - case CSBinaryOperator.And: - return "&&"; - case CSBinaryOperator.Or: - return "||"; - case CSBinaryOperator.Less: - return "<"; - case CSBinaryOperator.Greater: - return ">"; - case CSBinaryOperator.Equal: - return "=="; - case CSBinaryOperator.NotEqual: - return "!="; - case CSBinaryOperator.LessEqual: - return "<="; - case CSBinaryOperator.GreaterEqual: - return ">="; - case CSBinaryOperator.BitAnd: - return "&"; - case CSBinaryOperator.BitOr: - return "|"; - case CSBinaryOperator.BitXor: - return "^"; - case CSBinaryOperator.LeftShift: - return ">>"; - case CSBinaryOperator.RightShift: - return "<<"; - case CSBinaryOperator.Dot: - return "."; - case CSBinaryOperator.Is: - return "is"; - case CSBinaryOperator.As: - return "as"; - case CSBinaryOperator.NullCoalesce: - return "??"; - default: - throw new ArgumentOutOfRangeException ("op"); - } - } - } + static string OpToString(CSBinaryOperator op) + { + switch (op) + { + case CSBinaryOperator.Add: + return "+"; + case CSBinaryOperator.Sub: + return "-"; + case CSBinaryOperator.Mul: + return "*"; + case CSBinaryOperator.Div: + return "/"; + case CSBinaryOperator.Mod: + return "%"; + case CSBinaryOperator.And: + return "&&"; + case CSBinaryOperator.Or: + return "||"; + case CSBinaryOperator.Less: + return "<"; + case CSBinaryOperator.Greater: + return ">"; + case CSBinaryOperator.Equal: + return "=="; + case CSBinaryOperator.NotEqual: + return "!="; + case CSBinaryOperator.LessEqual: + return "<="; + case CSBinaryOperator.GreaterEqual: + return ">="; + case CSBinaryOperator.BitAnd: + return "&"; + case CSBinaryOperator.BitOr: + return "|"; + case CSBinaryOperator.BitXor: + return "^"; + case CSBinaryOperator.LeftShift: + return ">>"; + case CSBinaryOperator.RightShift: + return "<<"; + case CSBinaryOperator.Dot: + return "."; + case CSBinaryOperator.Is: + return "is"; + case CSBinaryOperator.As: + return "as"; + case CSBinaryOperator.NullCoalesce: + return "??"; + default: + throw new ArgumentOutOfRangeException("op"); + } + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs index 6b8a6ab5f0fe..b2a5e7c59461 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs @@ -5,75 +5,80 @@ using System.Linq; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSBinding : ICodeElementSet { - public CSBinding (CSIdentifier name, ICSExpression val = null, bool onOwnLine = false) - { - Name = name; - Value = val; - OnOwnLine = onOwnLine; - } +namespace SyntaxDynamo.CSLang +{ + public class CSBinding : ICodeElementSet + { + public CSBinding(CSIdentifier name, ICSExpression val = null, bool onOwnLine = false) + { + Name = name; + Value = val; + OnOwnLine = onOwnLine; + } - public CSBinding (string name, ICSExpression val = null, bool onOwnLine = false) - : this (new CSIdentifier (name), val, onOwnLine) - { - } + public CSBinding(string name, ICSExpression val = null, bool onOwnLine = false) + : this(new CSIdentifier(name), val, onOwnLine) + { + } - public CSIdentifier Name { get; private set; } - public ICSExpression Value { get; private set; } - public bool OnOwnLine { get; private set; } + public CSIdentifier Name { get; private set; } + public ICSExpression Value { get; private set; } + public bool OnOwnLine { get; private set; } - public override string ToString () - { - return string.Format ("{0}{1}{2}", - Name.Name, Value == null ? "" : " = ", Value == null ? "" : Value.ToString ()); - } + public override string ToString() + { + return string.Format("{0}{1}{2}", + Name.Name, Value == null ? "" : " = ", Value == null ? "" : Value.ToString()); + } - #region ICodeElem implementation - public event EventHandler Begin = (s, e) => { }; + #region ICodeElem implementation + public event EventHandler Begin = (s, e) => { }; - public event EventHandler End = (s, e) => { }; + public event EventHandler End = (s, e) => { }; - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - if (OnOwnLine) - args.Writer.BeginNewLine (true); - } + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + if (OnOwnLine) + args.Writer.BeginNewLine(true); + } - public void Write (ICodeWriter writer, object o) - { - } + public void Write(ICodeWriter writer, object o) + { + } - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } - protected virtual void OnEnd (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - #endregion + protected virtual void OnEnd(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + #endregion - #region ICodeElemSet implementation - public IEnumerable Elements { - get { - yield return Name; - if (Value != null) { - yield return new SimpleElement (" = ", true); - yield return Value; - } - } - } - #endregion - } + #region ICodeElemSet implementation + public IEnumerable Elements + { + get + { + yield return Name; + if (Value != null) + { + yield return new SimpleElement(" = ", true); + yield return Value; + } + } + } + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs index 764737769203..ca1d60b1fee4 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs @@ -6,200 +6,213 @@ using System.Linq; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSClass : ICodeElementSet, ICSTopLevelDeclaration { - public CSClass (CSVisibility vis, CSIdentifier name, IEnumerable methods = null, - bool isStatic = false, bool isSealed = false) - { - Visibility = vis; - IsStatic = isStatic; - IsSealed = isSealed; - Name = Exceptions.ThrowOnNull (name, "name"); - Inheritance = new CSInheritance (); - Delegates = new List (); - Fields = new List (); - Constructors = new List (); - Methods = new List (); - Properties = new List (); - InnerClasses = new CSClasses (); - InnerEnums = new List (); - StaticConstructor = new CSCodeBlock (); - GenericParams = new CSGenericTypeDeclarationCollection (); - GenericConstraints = new CSGenericConstraintCollection (); - - if (methods != null) - Methods.AddRange (methods); - } - - public CSClass (CSVisibility vis, string name, - IEnumerable members = null, bool isStatic = false, bool isSealed = false) - : this (vis, new CSIdentifier (name), members, isStatic, isSealed) - { - } - - protected virtual string EntityLabel { get { return "class"; } } - - public CSVisibility Visibility { get; private set; } - public bool IsStatic { get; private set; } - public bool IsSealed { get; private set; } - public CSIdentifier Name { get; private set; } - public CSInheritance Inheritance { get; private set; } - public List Delegates { get; private set; } - public List Fields { get; private set; } - public List Constructors { get; private set; } - public List Methods { get; private set; } - public List Properties { get; private set; } - public CSClasses InnerClasses { get; private set; } - public List InnerEnums { get; private set; } - public CSCodeBlock StaticConstructor { get; private set; } - public CSGenericTypeDeclarationCollection GenericParams { get; private set; } - public CSGenericConstraintCollection GenericConstraints { get; private set; } - - public CSType ToCSType (IEnumerable genericReplacements) - { - List replacements = genericReplacements.ToList (); - if (replacements.Count < GenericParams.Count) { - replacements.AddRange (GenericParams.Skip (replacements.Count).Select (gen => new CSSimpleType (gen.Name.Name))); - } - CSSimpleType t = new CSSimpleType (Name.Name, false, replacements.ToArray ()); - return t; - } - - public CSType ToCSType () - { - return ToCSType (GenericParams.Select (gen => new CSSimpleType (gen.Name.Name))); - } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - var decl = new LineCodeElementCollection (true, false, true); - if (Visibility != CSVisibility.None) - decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); - if (IsStatic) - decl.Add (new SimpleElement ("static ", true)); - if (IsSealed) - decl.Add (new SimpleElement ("sealed ", true)); - decl.Add (new CSIdentifier (EntityLabel + " ")); - decl.Add (Name); - decl.Add (GenericParams); - if (Inheritance.Count > 0) { - decl.Add (new SimpleElement (" : ", true)); - decl.Add (Inheritance); - } - if (GenericConstraints.Count > 0) { - decl.Add (SimpleElement.Spacer); - decl.Add (GenericConstraints); - } - yield return decl; - - var contents = new DecoratedCodeElementCollection ("{", "}", - true, true, true); - - contents.AddRange (Delegates); - contents.AddRange (Fields); - - if (StaticConstructor.Count > 0) { - var m = new CSMethod (CSVisibility.None, CSMethodKind.Static, - null, Name, new CSParameterList (), StaticConstructor); - contents.Add (m); - } - contents.AddRange (Constructors); - contents.AddRange (Methods); - contents.AddRange (Properties); - contents.Add (InnerClasses); - contents.AddRange (InnerEnums); - - yield return contents; - - } - } - - #endregion - } - - public class CSClasses : CodeElementCollection { - public CSClasses (IEnumerable classes = null) - : base () - { - if (classes != null) - AddRange (classes); - } - - public CSClasses And (CSClass use) - { - Add (use); - return this; - } - } - - public class CSStruct : CSClass { - public CSStruct (CSVisibility vis, CSIdentifier name, IEnumerable methods = null, - bool isStatic = false, bool isSealed = false) - : base (vis, name, methods, isStatic, isSealed) - { - } - - public CSStruct (CSVisibility vis, string name, - IEnumerable members = null, bool isStatic = false, bool isSealed = false) - : this (vis, new CSIdentifier (name), members, isStatic, isSealed) - { - } - - protected override string EntityLabel { - get { - return "struct"; - } - } - } - - public class CSStructs : CodeElementCollection { - public CSStructs (IEnumerable structs = null) - : base () - { - if (structs != null) - AddRange (structs); - } - - public CSStructs And (CSStruct st) - { - Add (st); - return this; - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSClass : ICodeElementSet, ICSTopLevelDeclaration + { + public CSClass(CSVisibility vis, CSIdentifier name, IEnumerable methods = null, + bool isStatic = false, bool isSealed = false) + { + Visibility = vis; + IsStatic = isStatic; + IsSealed = isSealed; + Name = Exceptions.ThrowOnNull(name, "name"); + Inheritance = new CSInheritance(); + Delegates = new List(); + Fields = new List(); + Constructors = new List(); + Methods = new List(); + Properties = new List(); + InnerClasses = new CSClasses(); + InnerEnums = new List(); + StaticConstructor = new CSCodeBlock(); + GenericParams = new CSGenericTypeDeclarationCollection(); + GenericConstraints = new CSGenericConstraintCollection(); + + if (methods != null) + Methods.AddRange(methods); + } + + public CSClass(CSVisibility vis, string name, + IEnumerable members = null, bool isStatic = false, bool isSealed = false) + : this(vis, new CSIdentifier(name), members, isStatic, isSealed) + { + } + + protected virtual string EntityLabel { get { return "class"; } } + + public CSVisibility Visibility { get; private set; } + public bool IsStatic { get; private set; } + public bool IsSealed { get; private set; } + public CSIdentifier Name { get; private set; } + public CSInheritance Inheritance { get; private set; } + public List Delegates { get; private set; } + public List Fields { get; private set; } + public List Constructors { get; private set; } + public List Methods { get; private set; } + public List Properties { get; private set; } + public CSClasses InnerClasses { get; private set; } + public List InnerEnums { get; private set; } + public CSCodeBlock StaticConstructor { get; private set; } + public CSGenericTypeDeclarationCollection GenericParams { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + + public CSType ToCSType(IEnumerable genericReplacements) + { + List replacements = genericReplacements.ToList(); + if (replacements.Count < GenericParams.Count) + { + replacements.AddRange(GenericParams.Skip(replacements.Count).Select(gen => new CSSimpleType(gen.Name.Name))); + } + CSSimpleType t = new CSSimpleType(Name.Name, false, replacements.ToArray()); + return t; + } + + public CSType ToCSType() + { + return ToCSType(GenericParams.Select(gen => new CSSimpleType(gen.Name.Name))); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } + + public virtual void Write(ICodeWriter writer, object o) + { + } + + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } + + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements + { + get + { + var decl = new LineCodeElementCollection(true, false, true); + if (Visibility != CSVisibility.None) + decl.Add(new SimpleElement(CSMethod.VisibilityToString(Visibility) + " ")); + if (IsStatic) + decl.Add(new SimpleElement("static ", true)); + if (IsSealed) + decl.Add(new SimpleElement("sealed ", true)); + decl.Add(new CSIdentifier(EntityLabel + " ")); + decl.Add(Name); + decl.Add(GenericParams); + if (Inheritance.Count > 0) + { + decl.Add(new SimpleElement(" : ", true)); + decl.Add(Inheritance); + } + if (GenericConstraints.Count > 0) + { + decl.Add(SimpleElement.Spacer); + decl.Add(GenericConstraints); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection("{", "}", + true, true, true); + + contents.AddRange(Delegates); + contents.AddRange(Fields); + + if (StaticConstructor.Count > 0) + { + var m = new CSMethod(CSVisibility.None, CSMethodKind.Static, + null, Name, new CSParameterList(), StaticConstructor); + contents.Add(m); + } + contents.AddRange(Constructors); + contents.AddRange(Methods); + contents.AddRange(Properties); + contents.Add(InnerClasses); + contents.AddRange(InnerEnums); + + yield return contents; + + } + } + + #endregion + } + + public class CSClasses : CodeElementCollection + { + public CSClasses(IEnumerable classes = null) + : base() + { + if (classes != null) + AddRange(classes); + } + + public CSClasses And(CSClass use) + { + Add(use); + return this; + } + } + + public class CSStruct : CSClass + { + public CSStruct(CSVisibility vis, CSIdentifier name, IEnumerable methods = null, + bool isStatic = false, bool isSealed = false) + : base(vis, name, methods, isStatic, isSealed) + { + } + + public CSStruct(CSVisibility vis, string name, + IEnumerable members = null, bool isStatic = false, bool isSealed = false) + : this(vis, new CSIdentifier(name), members, isStatic, isSealed) + { + } + + protected override string EntityLabel + { + get + { + return "struct"; + } + } + } + + public class CSStructs : CodeElementCollection + { + public CSStructs(IEnumerable structs = null) + : base() + { + if (structs != null) + AddRange(structs); + } + + public CSStructs And(CSStruct st) + { + Add(st); + return this; + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs index 4d39f5e2c6f4..1520e9b2fb20 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs @@ -4,49 +4,54 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSCodeBlock : DecoratedCodeElementCollection, ICSStatement { - public CSCodeBlock () - : this (null) - { - - } - - public CSCodeBlock (IEnumerable statements) - : this ("{", "}", statements) - { - } - - public static CSCodeBlock Create (params ICodeElement [] statements) - { - return new CSCodeBlock (statements); - } - - public CSCodeBlock (string start, string end, IEnumerable statements) - : base (Exceptions.ThrowOnNull (start, "start"), Exceptions.ThrowOnNull (end, "end"), true, true, true) - { - if (statements != null) { - foreach (ICodeElement elem in statements) { - And (elem); - } - } - } - - public CSCodeBlock And (ICodeElement elem) - { - if (!(elem is ICSStatement)) - throw new ArgumentException ($"contents must each be an IStatement, got {elem.GetType ()}"); - Add (elem); - return this; - } - } - - public class CSUnsafeCodeBlock : CSCodeBlock { - public CSUnsafeCodeBlock (IEnumerable statements) - : base ("unsafe {", "}", statements) - { - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSCodeBlock : DecoratedCodeElementCollection, ICSStatement + { + public CSCodeBlock() + : this(null) + { + + } + + public CSCodeBlock(IEnumerable statements) + : this("{", "}", statements) + { + } + + public static CSCodeBlock Create(params ICodeElement[] statements) + { + return new CSCodeBlock(statements); + } + + public CSCodeBlock(string start, string end, IEnumerable statements) + : base(Exceptions.ThrowOnNull(start, "start"), Exceptions.ThrowOnNull(end, "end"), true, true, true) + { + if (statements != null) + { + foreach (ICodeElement elem in statements) + { + And(elem); + } + } + } + + public CSCodeBlock And(ICodeElement elem) + { + if (!(elem is ICSStatement)) + throw new ArgumentException($"contents must each be an IStatement, got {elem.GetType()}"); + Add(elem); + return this; + } + } + + public class CSUnsafeCodeBlock : CSCodeBlock + { + public CSUnsafeCodeBlock(IEnumerable statements) + : base("unsafe {", "}", statements) + { + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs index 825a5880b260..8ffc0e40ecae 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs @@ -4,53 +4,57 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSComment : SimpleLineElement { - public CSComment (string text) - : base (Commentize (text), false, true, false) - { - } - - static string Commentize (string text) - { - text = text ?? ""; - if (text.Contains ("\n")) - throw new ArgumentException ("Comment text must not contain new line characters.", "text"); - return "// " + text; - } - } - - public class CSCommentBlock : CodeElementCollection { - public CSCommentBlock (params CSComment [] comments) - { - AddRange (comments); - } - - public CSCommentBlock (params string [] text) - { - AddRange (Sanitize (Exceptions.ThrowOnNull (text, "text"))); - } - - static IEnumerable Sanitize (string [] text) - { - foreach (string s in text) { - string [] lines = s.Split ('\n'); - foreach (string line in lines) - yield return new CSComment (line); - } - } - - public CSCommentBlock And (string text) - { - AddRange (Sanitize (new string [] { text })); - return this; - } - - public CSCommentBlock And (CSComment comment) - { - Add (Exceptions.ThrowOnNull (comment, "comment")); - return this; - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSComment : SimpleLineElement + { + public CSComment(string text) + : base(Commentize(text), false, true, false) + { + } + + static string Commentize(string text) + { + text = text ?? ""; + if (text.Contains("\n")) + throw new ArgumentException("Comment text must not contain new line characters.", "text"); + return "// " + text; + } + } + + public class CSCommentBlock : CodeElementCollection + { + public CSCommentBlock(params CSComment[] comments) + { + AddRange(comments); + } + + public CSCommentBlock(params string[] text) + { + AddRange(Sanitize(Exceptions.ThrowOnNull(text, "text"))); + } + + static IEnumerable Sanitize(string[] text) + { + foreach (string s in text) + { + string[] lines = s.Split('\n'); + foreach (string line in lines) + yield return new CSComment(line); + } + } + + public CSCommentBlock And(string text) + { + AddRange(Sanitize(new string[] { text })); + return this; + } + + public CSCommentBlock And(CSComment comment) + { + Add(Exceptions.ThrowOnNull(comment, "comment")); + return this; + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs index 36b574185965..5e576ce1ba6f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs @@ -4,34 +4,37 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSConditionalCompilation : LineCodeElementCollection { - CSConditionalCompilation (CSIdentifier tag, CSIdentifier condition) - : base (true, false, false) - { - Add (tag); - if ((object)condition != null) { - Add (SimpleElement.Spacer); - Add (condition); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSConditionalCompilation : LineCodeElementCollection + { + CSConditionalCompilation(CSIdentifier tag, CSIdentifier condition) + : base(true, false, false) + { + Add(tag); + if ((object)condition != null) + { + Add(SimpleElement.Spacer); + Add(condition); + } + } - static CSConditionalCompilation _else = new CSConditionalCompilation (new CSIdentifier ("#else"), null); - public static CSConditionalCompilation Else { get { return _else; } } - static CSConditionalCompilation _endif = new CSConditionalCompilation (new CSIdentifier ("#endif"), null); - public static CSConditionalCompilation Endif { get { return _endif; } } + static CSConditionalCompilation _else = new CSConditionalCompilation(new CSIdentifier("#else"), null); + public static CSConditionalCompilation Else { get { return _else; } } + static CSConditionalCompilation _endif = new CSConditionalCompilation(new CSIdentifier("#endif"), null); + public static CSConditionalCompilation Endif { get { return _endif; } } - public static CSConditionalCompilation If (CSIdentifier condition) - { - return new CSConditionalCompilation (new CSIdentifier ("#if"), Exceptions.ThrowOnNull (condition, nameof (condition))); - } + public static CSConditionalCompilation If(CSIdentifier condition) + { + return new CSConditionalCompilation(new CSIdentifier("#if"), Exceptions.ThrowOnNull(condition, nameof(condition))); + } - public static void ProtectWithIfEndif (CSIdentifier condition, ICodeElement elem) - { - var @if = If (condition); - @if.AttachBefore (elem); - Endif.AttachAfter (elem); - } - } + public static void ProtectWithIfEndif(CSIdentifier condition, ICodeElement elem) + { + var @if = If(condition); + @if.AttachBefore(elem); + Endif.AttachAfter(elem); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs index 5e791b123223..257ad0ccdb2d 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs @@ -7,66 +7,72 @@ using System.CodeDom.Compiler; using System.CodeDom; -namespace SyntaxDynamo.CSLang { - public class CSConstant : CSBaseExpression { - public CSConstant (string val) - { - Value = Exceptions.ThrowOnNull (val, "val"); - } +namespace SyntaxDynamo.CSLang +{ + public class CSConstant : CSBaseExpression + { + public CSConstant(string val) + { + Value = Exceptions.ThrowOnNull(val, "val"); + } - public static explicit operator CSConstant (string val) - { - return new CSConstant (val); - } + public static explicit operator CSConstant(string val) + { + return new CSConstant(val); + } - public string Value { get; private set; } + public string Value { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Value, false); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write(Value, false); + } - public static CSConstant Val (byte b) { return new CSConstant (b.ToString ()); } - public static CSConstant Val (sbyte sb) { return new CSConstant (sb.ToString ()); } - public static CSConstant Val (ushort us) { return new CSConstant (us.ToString ()); } - public static CSConstant Val (short s) { return new CSConstant (s.ToString ()); } - public static CSConstant Val (uint ui) { return new CSConstant (ui.ToString ()); } - public static CSConstant Val (int i) { return new CSConstant (i.ToString ()); } - public static CSConstant Val (ulong ul) { return new CSConstant (ul.ToString ()); } - public static CSConstant Val (long l) { return new CSConstant (l.ToString ()); } - public static CSConstant Val (float f) - { - return new CSConstant (f.ToString () + "f"); - } - public static CSConstant Val (double d) { return new CSConstant (d.ToString ()); } - public static CSConstant Val (bool b) { return new CSConstant (b ? "true" : "false"); } - public static CSConstant Val (char c) { return new CSConstant (ToCharLiteral (c)); } - public static CSConstant Val (string s) { return new CSConstant (ToStringLiteral (s)); } - static CSConstant cNull = new CSConstant ("null"); - public static CSConstant Null { get { return cNull; } } - static CSConstant cIntPtrZero = new CSConstant ("IntPtr.Zero"); - public static CSConstant IntPtrZero { get { return cIntPtrZero; } } - public static CSBaseExpression ValNFloat (double d) { return new CSCastExpression (CSSimpleType.NFloat, Val (d)); } + public static CSConstant Val(byte b) { return new CSConstant(b.ToString()); } + public static CSConstant Val(sbyte sb) { return new CSConstant(sb.ToString()); } + public static CSConstant Val(ushort us) { return new CSConstant(us.ToString()); } + public static CSConstant Val(short s) { return new CSConstant(s.ToString()); } + public static CSConstant Val(uint ui) { return new CSConstant(ui.ToString()); } + public static CSConstant Val(int i) { return new CSConstant(i.ToString()); } + public static CSConstant Val(ulong ul) { return new CSConstant(ul.ToString()); } + public static CSConstant Val(long l) { return new CSConstant(l.ToString()); } + public static CSConstant Val(float f) + { + return new CSConstant(f.ToString() + "f"); + } + public static CSConstant Val(double d) { return new CSConstant(d.ToString()); } + public static CSConstant Val(bool b) { return new CSConstant(b ? "true" : "false"); } + public static CSConstant Val(char c) { return new CSConstant(ToCharLiteral(c)); } + public static CSConstant Val(string s) { return new CSConstant(ToStringLiteral(s)); } + static CSConstant cNull = new CSConstant("null"); + public static CSConstant Null { get { return cNull; } } + static CSConstant cIntPtrZero = new CSConstant("IntPtr.Zero"); + public static CSConstant IntPtrZero { get { return cIntPtrZero; } } + public static CSBaseExpression ValNFloat(double d) { return new CSCastExpression(CSSimpleType.NFloat, Val(d)); } - static string ToCharLiteral (char c) - { - using (var writer = new StringWriter ()) { - using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { - provider.GenerateCodeFromExpression (new CodePrimitiveExpression (c), writer, null); - return writer.ToString (); - } - } - } + static string ToCharLiteral(char c) + { + using (var writer = new StringWriter()) + { + using (var provider = CodeDomProvider.CreateProvider("CSharp")) + { + provider.GenerateCodeFromExpression(new CodePrimitiveExpression(c), writer, null); + return writer.ToString(); + } + } + } - static string ToStringLiteral (string s) - { - using (var writer = new StringWriter ()) { - using (var provider = CodeDomProvider.CreateProvider ("CSharp")) { - provider.GenerateCodeFromExpression (new CodePrimitiveExpression (s), writer, null); - return writer.ToString (); - } - } - } - } + static string ToStringLiteral(string s) + { + using (var writer = new StringWriter()) + { + using (var provider = CodeDomProvider.CreateProvider("CSharp")) + { + provider.GenerateCodeFromExpression(new CodePrimitiveExpression(s), writer, null); + return writer.ToString(); + } + } + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs index 1c26bfdcea5e..f3404d183519 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs @@ -3,39 +3,41 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSDelegateTypeDecl : DelegatedSimpleElement, ICSStatement { - public CSDelegateTypeDecl (CSVisibility vis, CSType type, CSIdentifier name, CSParameterList parms, bool isUnsafe = false) - { - Visibility = vis; - Type = type != null ? type : CSSimpleType.Void; - Name = Exceptions.ThrowOnNull (name, "name"); - Parameters = parms; - IsUnsafe = isUnsafe; - } +namespace SyntaxDynamo.CSLang +{ + public class CSDelegateTypeDecl : DelegatedSimpleElement, ICSStatement + { + public CSDelegateTypeDecl(CSVisibility vis, CSType type, CSIdentifier name, CSParameterList parms, bool isUnsafe = false) + { + Visibility = vis; + Type = type != null ? type : CSSimpleType.Void; + Name = Exceptions.ThrowOnNull(name, "name"); + Parameters = parms; + IsUnsafe = isUnsafe; + } - public CSVisibility Visibility { get; private set; } - public CSType Type { get; private set; } - public CSIdentifier Name { get; private set; } - public CSParameterList Parameters { get; private set; } - public bool IsUnsafe { get; private set; } + public CSVisibility Visibility { get; private set; } + public CSType Type { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList Parameters { get; private set; } + public bool IsUnsafe { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write (CSMethod.VisibilityToString (Visibility), false); - if (IsUnsafe) - writer.Write (" unsafe", true); - writer.Write (" delegate ", true); - Type.WriteAll (writer); - writer.Write (' ', true); - Name.WriteAll (writer); - writer.Write ('(', true); - Parameters.WriteAll (writer); - writer.Write (')', true); - writer.Write (';', false); - writer.EndLine (); - } - } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + writer.Write(CSMethod.VisibilityToString(Visibility), false); + if (IsUnsafe) + writer.Write(" unsafe", true); + writer.Write(" delegate ", true); + Type.WriteAll(writer); + writer.Write(' ', true); + Name.WriteAll(writer); + writer.Write('(', true); + Parameters.WriteAll(writer); + writer.Write(')', true); + writer.Write(';', false); + writer.EndLine(); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs index 92d798ed1ad8..8bbedbaf2e74 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs @@ -5,97 +5,103 @@ using System.Collections.Generic; using System.Linq; -namespace SyntaxDynamo.CSLang { - public class CSEnum : ICodeElementSet, ICSTopLevelDeclaration { - public CSEnum (CSVisibility vis, CSIdentifier name, CSType optionalType) - { - Values = new List (); - Name = Exceptions.ThrowOnNull (name, "name"); - OptionalType = optionalType; - Visibility = vis; - } - - public CSEnum (CSVisibility vis, string name, CSType optionalType) - : this (vis, new CSIdentifier (name), optionalType) - { - } - - public List Values { get; private set; } - public CSVisibility Visibility { get; private set; } - public CSType OptionalType { get; private set; } - public CSIdentifier Name { get; private set; } - - public CSType ToCSType () - { - return new CSSimpleType (Name.Name); - } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - var decl = new LineCodeElementCollection (true, false, true); - if (Visibility != CSVisibility.None) - decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); - decl.Add (new CSIdentifier ("enum" + " ")); - decl.Add (Name); - - if (OptionalType != null) { - decl.Add (new SimpleElement (" : ", true)); - decl.Add (OptionalType); - } - yield return decl; - - var contents = new DecoratedCodeElementCollection ("{", "}", - true, true, true); - - var bindings = new CommaListElementCollection (); - bindings.AddRange (Values); - if (bindings.Count > 0 && !bindings [0].OnOwnLine) { - bindings [0] = new CSBinding (bindings [0].Name, bindings [0].Value, true); - } - contents.Add (bindings); - - yield return contents; - - } - } - - #endregion - - } +namespace SyntaxDynamo.CSLang +{ + public class CSEnum : ICodeElementSet, ICSTopLevelDeclaration + { + public CSEnum(CSVisibility vis, CSIdentifier name, CSType optionalType) + { + Values = new List(); + Name = Exceptions.ThrowOnNull(name, "name"); + OptionalType = optionalType; + Visibility = vis; + } + + public CSEnum(CSVisibility vis, string name, CSType optionalType) + : this(vis, new CSIdentifier(name), optionalType) + { + } + + public List Values { get; private set; } + public CSVisibility Visibility { get; private set; } + public CSType OptionalType { get; private set; } + public CSIdentifier Name { get; private set; } + + public CSType ToCSType() + { + return new CSSimpleType(Name.Name); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } + + public virtual void Write(ICodeWriter writer, object o) + { + } + + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } + + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements + { + get + { + var decl = new LineCodeElementCollection(true, false, true); + if (Visibility != CSVisibility.None) + decl.Add(new SimpleElement(CSMethod.VisibilityToString(Visibility) + " ")); + decl.Add(new CSIdentifier("enum" + " ")); + decl.Add(Name); + + if (OptionalType != null) + { + decl.Add(new SimpleElement(" : ", true)); + decl.Add(OptionalType); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection("{", "}", + true, true, true); + + var bindings = new CommaListElementCollection(); + bindings.AddRange(Values); + if (bindings.Count > 0 && !bindings[0].OnOwnLine) + { + bindings[0] = new CSBinding(bindings[0].Name, bindings[0].Value, true); + } + contents.Add(bindings); + + yield return contents; + + } + } + + #endregion + + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs index 7e729c90e904..f6512d2f8b11 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs @@ -6,101 +6,108 @@ using System.Linq; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSVariableDeclaration : LineCodeElementCollection, ICSExpression, ICSLineable { - public CSVariableDeclaration (CSType type, IEnumerable bindings) - : base (null, false, true) - { - Type = Exceptions.ThrowOnNull (type, "type"); - And (Type).And (SimpleElement.Spacer); - Bindings = new CommaListElementCollection (Exceptions.ThrowOnNull (bindings, "bindings")); - Add (Bindings); - } - - public CSVariableDeclaration (CSType type, string name, ICSExpression value = null) - : this (type, new CSIdentifier (name), value) - { - } - - public CSVariableDeclaration (CSType type, CSIdentifier name, ICSExpression value = null) - : this (type, new CSBinding [] { new CSBinding (name, value) }) - { - } - - public CSType Type { get; private set; } - public CommaListElementCollection Bindings { get; private set; } - - - public static CSLine VarLine (CSType type, CSIdentifier name, ICSExpression value = null) - { - return new CSLine (new CSVariableDeclaration (type, name, value)); - } - - public static CSLine VarLine (CSType type, string name, ICSExpression value = null) - { - return new CSLine (new CSVariableDeclaration (type, name, value)); - } - - public static CSLine VarLine (string name, ICSExpression value) - { - return new CSLine (new CSVariableDeclaration (CSSimpleType.Var, name, value)); - } - - public static CSLine VarLine (CSIdentifier name, ICSExpression value) - { - return new CSLine (new CSVariableDeclaration (CSSimpleType.Var, name, value)); - } - } - - public class CSFieldDeclaration : CSVariableDeclaration { - public CSFieldDeclaration (CSType type, IEnumerable bindings, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) - : base (type, bindings) - { - Visibilty = vis; - IsStatic = isStatic; - IsUnsafe = isUnsafe; - if (isReadonly) { - this.Insert (0, new SimpleElement ("readonly")); - this.Insert (1, SimpleElement.Spacer); - } - if (IsUnsafe) { - this.Insert (0, new SimpleElement ("unsafe")); - this.Insert (1, SimpleElement.Spacer); - } - if (isStatic) { - this.Insert (0, new SimpleElement ("static")); - this.Insert (1, SimpleElement.Spacer); - } - if (vis != CSVisibility.None) { - this.Insert (0, new SimpleElement (CSMethod.VisibilityToString (vis))); - this.Insert (1, SimpleElement.Spacer); - } - } - - public CSFieldDeclaration (CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) - : this (type, new CSIdentifier (name), value, vis, isStatic, isReadonly, isUnsafe) - { - } - - public CSFieldDeclaration (CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadOnly = false, bool isUnsafe = false) - : this (type, new CSBinding [] { new CSBinding (name, value) }, vis, isStatic, isReadOnly, isUnsafe) - { - } - - - public CSVisibility Visibilty { get; private set; } - public bool IsStatic { get; private set; } - public bool IsUnsafe { get; private set; } - - public static CSLine FieldLine (CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) - { - return new CSLine (new CSFieldDeclaration (type, name, value, vis, isStatic)); - } - - public static CSLine FieldLine (CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) - { - return new CSLine (new CSFieldDeclaration (type, name, value, vis, isStatic)); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSVariableDeclaration : LineCodeElementCollection, ICSExpression, ICSLineable + { + public CSVariableDeclaration(CSType type, IEnumerable bindings) + : base(null, false, true) + { + Type = Exceptions.ThrowOnNull(type, "type"); + And(Type).And(SimpleElement.Spacer); + Bindings = new CommaListElementCollection(Exceptions.ThrowOnNull(bindings, "bindings")); + Add(Bindings); + } + + public CSVariableDeclaration(CSType type, string name, ICSExpression value = null) + : this(type, new CSIdentifier(name), value) + { + } + + public CSVariableDeclaration(CSType type, CSIdentifier name, ICSExpression value = null) + : this(type, new CSBinding[] { new CSBinding(name, value) }) + { + } + + public CSType Type { get; private set; } + public CommaListElementCollection Bindings { get; private set; } + + + public static CSLine VarLine(CSType type, CSIdentifier name, ICSExpression value = null) + { + return new CSLine(new CSVariableDeclaration(type, name, value)); + } + + public static CSLine VarLine(CSType type, string name, ICSExpression value = null) + { + return new CSLine(new CSVariableDeclaration(type, name, value)); + } + + public static CSLine VarLine(string name, ICSExpression value) + { + return new CSLine(new CSVariableDeclaration(CSSimpleType.Var, name, value)); + } + + public static CSLine VarLine(CSIdentifier name, ICSExpression value) + { + return new CSLine(new CSVariableDeclaration(CSSimpleType.Var, name, value)); + } + } + + public class CSFieldDeclaration : CSVariableDeclaration + { + public CSFieldDeclaration(CSType type, IEnumerable bindings, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) + : base(type, bindings) + { + Visibilty = vis; + IsStatic = isStatic; + IsUnsafe = isUnsafe; + if (isReadonly) + { + this.Insert(0, new SimpleElement("readonly")); + this.Insert(1, SimpleElement.Spacer); + } + if (IsUnsafe) + { + this.Insert(0, new SimpleElement("unsafe")); + this.Insert(1, SimpleElement.Spacer); + } + if (isStatic) + { + this.Insert(0, new SimpleElement("static")); + this.Insert(1, SimpleElement.Spacer); + } + if (vis != CSVisibility.None) + { + this.Insert(0, new SimpleElement(CSMethod.VisibilityToString(vis))); + this.Insert(1, SimpleElement.Spacer); + } + } + + public CSFieldDeclaration(CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadonly = false, bool isUnsafe = false) + : this(type, new CSIdentifier(name), value, vis, isStatic, isReadonly, isUnsafe) + { + } + + public CSFieldDeclaration(CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false, bool isReadOnly = false, bool isUnsafe = false) + : this(type, new CSBinding[] { new CSBinding(name, value) }, vis, isStatic, isReadOnly, isUnsafe) + { + } + + + public CSVisibility Visibilty { get; private set; } + public bool IsStatic { get; private set; } + public bool IsUnsafe { get; private set; } + + public static CSLine FieldLine(CSType type, CSIdentifier name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) + { + return new CSLine(new CSFieldDeclaration(type, name, value, vis, isStatic)); + } + + public static CSLine FieldLine(CSType type, string name, ICSExpression value = null, CSVisibility vis = CSVisibility.None, bool isStatic = false) + { + return new CSLine(new CSFieldDeclaration(type, name, value, vis, isStatic)); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs index ac78e03b69b2..149e47ca780a 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs @@ -6,66 +6,70 @@ using System.Linq; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSFile : ICodeElementSet { - public CSFile (CSUsingPackages use, IEnumerable ns) - { - Using = use ?? new CSUsingPackages (); - ns = ns ?? new CSNamespace [0]; - Namespaces = new CSNamespaceBlock (ns); - } - - public static CSFile Create (CSUsingPackages use, params CSNamespace [] ns) - { - return new CSFile (use, ns); - } - - public CSUsingPackages Using { get; private set; } - public CSNamespaceBlock Namespaces { get; private set; } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public object BeginWrite (ICodeWriter writer) - { - OnBegin (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBegin (WriteEventArgs args) - { - Begin (this, args); - } - - public void Write (ICodeWriter writer, object o) - { - } - - public void EndWrite (ICodeWriter writer, object o) - { - OnEnd (new WriteEventArgs (writer)); - } - - protected virtual void OnEnd (WriteEventArgs args) - { - End (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public System.Collections.Generic.IEnumerable Elements { - get { - yield return Using; - yield return Namespaces; - } - } - - #endregion - } +namespace SyntaxDynamo.CSLang +{ + public class CSFile : ICodeElementSet + { + public CSFile(CSUsingPackages use, IEnumerable ns) + { + Using = use ?? new CSUsingPackages(); + ns = ns ?? new CSNamespace[0]; + Namespaces = new CSNamespaceBlock(ns); + } + + public static CSFile Create(CSUsingPackages use, params CSNamespace[] ns) + { + return new CSFile(use, ns); + } + + public CSUsingPackages Using { get; private set; } + public CSNamespaceBlock Namespaces { get; private set; } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public object BeginWrite(ICodeWriter writer) + { + OnBegin(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBegin(WriteEventArgs args) + { + Begin(this, args); + } + + public void Write(ICodeWriter writer, object o) + { + } + + public void EndWrite(ICodeWriter writer, object o) + { + OnEnd(new WriteEventArgs(writer)); + } + + protected virtual void OnEnd(WriteEventArgs args) + { + End(this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public System.Collections.Generic.IEnumerable Elements + { + get + { + yield return Using; + yield return Namespaces; + } + } + + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs index 30416874f59e..3e5ad11de975 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs @@ -3,63 +3,67 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSFileBasic : ICodeElementSet { - string nameSpace; - - public CSFileBasic (string nameSpace) - { - this.nameSpace = Exceptions.ThrowOnNull (nameSpace, "nameSpace"); - Using = new CSUsingPackages (); - Classes = new CSClasses (); - } - - #region ICodeElem implementation - - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public CSClasses Classes { get; private set; } - public CSUsingPackages Using { get; private set; } - - public object BeginWrite (ICodeWriter writer) - { - return null; - } - - public void Write (ICodeWriter writer, object o) - { - } - - public void EndWrite (ICodeWriter writer, object o) - { - } - - protected virtual void OnBegin (WriteEventArgs e) - { - Begin (this, e); - } - - protected virtual void OnEnd (WriteEventArgs e) - { - End (this, e); - } - - #endregion - - #region ICodeElemSet implementation - - public System.Collections.Generic.IEnumerable Elements { - get { - yield return Using; - CSNamespace ns = new CSNamespace (nameSpace); - ns.Block.AddRange (Classes); - yield return ns; - } - } - - #endregion - } +namespace SyntaxDynamo.CSLang +{ + public class CSFileBasic : ICodeElementSet + { + string nameSpace; + + public CSFileBasic(string nameSpace) + { + this.nameSpace = Exceptions.ThrowOnNull(nameSpace, "nameSpace"); + Using = new CSUsingPackages(); + Classes = new CSClasses(); + } + + #region ICodeElem implementation + + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public CSClasses Classes { get; private set; } + public CSUsingPackages Using { get; private set; } + + public object BeginWrite(ICodeWriter writer) + { + return null; + } + + public void Write(ICodeWriter writer, object o) + { + } + + public void EndWrite(ICodeWriter writer, object o) + { + } + + protected virtual void OnBegin(WriteEventArgs e) + { + Begin(this, e); + } + + protected virtual void OnEnd(WriteEventArgs e) + { + End(this, e); + } + + #endregion + + #region ICodeElemSet implementation + + public System.Collections.Generic.IEnumerable Elements + { + get + { + yield return Using; + CSNamespace ns = new CSNamespace(nameSpace); + ns.Block.AddRange(Classes); + yield return ns; + } + } + + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs index 21847bd9a111..2d76968ca9c5 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs @@ -4,32 +4,34 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSFixedCodeBlock : CSCodeBlock, ICSStatement { - public CSFixedCodeBlock (CSType type, CSIdentifier ident, CSBaseExpression expr, IEnumerable body) - : base (body) - { - Type = Exceptions.ThrowOnNull (type, "type"); - Identifier = Exceptions.ThrowOnNull (ident, "ident"); - Expr = Exceptions.ThrowOnNull (expr, "expr"); - } +namespace SyntaxDynamo.CSLang +{ + public class CSFixedCodeBlock : CSCodeBlock, ICSStatement + { + public CSFixedCodeBlock(CSType type, CSIdentifier ident, CSBaseExpression expr, IEnumerable body) + : base(body) + { + Type = Exceptions.ThrowOnNull(type, "type"); + Identifier = Exceptions.ThrowOnNull(ident, "ident"); + Expr = Exceptions.ThrowOnNull(expr, "expr"); + } - public override void Write (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write ("fixed (", true); - Type.Write (writer, o); - writer.Write (' ', false); - Identifier.Write (writer, o); - writer.Write (" = ", true); - Expr.Write (writer, o); - writer.Write (") ", true); - base.Write (writer, o); - } + public override void Write(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + writer.Write("fixed (", true); + Type.Write(writer, o); + writer.Write(' ', false); + Identifier.Write(writer, o); + writer.Write(" = ", true); + Expr.Write(writer, o); + writer.Write(") ", true); + base.Write(writer, o); + } - public CSType Type { get; private set; } - public CSIdentifier Identifier { get; private set; } - public CSBaseExpression Expr { get; private set; } - } + public CSType Type { get; private set; } + public CSIdentifier Identifier { get; private set; } + public CSBaseExpression Expr { get; private set; } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs index fe9cfd004c77..445ce3695c85 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs @@ -2,59 +2,65 @@ // Licensed under the MIT License. using System; -namespace SyntaxDynamo.CSLang { - public class CSForEach : CodeElementCollection, ICSStatement { - - class ForElement : DelegatedSimpleElement, ICSStatement { - public ForElement (CSType type, CSIdentifier ident, CSBaseExpression expr) - : base () - { - Type = type; - Ident = ident; - Expr = expr; - } - - public CSType Type { get; private set; } - public CSIdentifier Ident { get; private set; } - public CSBaseExpression Expr { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write ("foreach (", false); - if (Type != null) { - Type.WriteAll (writer); - } else { - writer.Write ("var", false); - } - SimpleElement.Spacer.WriteAll (writer); - Ident.WriteAll (writer); - writer.Write (" in ", true); - Expr.WriteAll (writer); - writer.Write (")", false); - writer.EndLine (); - } - } - - - public CSForEach (CSType type, CSIdentifier ident, CSBaseExpression expr, CSCodeBlock body) - { - Type = type; - Ident = Exceptions.ThrowOnNull (ident, nameof (ident)); - Expr = Exceptions.ThrowOnNull (expr, nameof (expr)); - Body = body ?? new CSCodeBlock (); - Add (new ForElement (type, ident, expr)); - Add (Body); - } - - public CSForEach (CSType type, string ident, CSBaseExpression expr, CSCodeBlock body) - : this (type, new CSIdentifier (ident), expr, body) - { - } - - public CSType Type { get; private set; } - public CSIdentifier Ident { get; private set; } - public CSBaseExpression Expr { get; private set; } - public CSCodeBlock Body { get; private set; } - } +namespace SyntaxDynamo.CSLang +{ + public class CSForEach : CodeElementCollection, ICSStatement + { + + class ForElement : DelegatedSimpleElement, ICSStatement + { + public ForElement(CSType type, CSIdentifier ident, CSBaseExpression expr) + : base() + { + Type = type; + Ident = ident; + Expr = expr; + } + + public CSType Type { get; private set; } + public CSIdentifier Ident { get; private set; } + public CSBaseExpression Expr { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + writer.Write("foreach (", false); + if (Type != null) + { + Type.WriteAll(writer); + } + else + { + writer.Write("var", false); + } + SimpleElement.Spacer.WriteAll(writer); + Ident.WriteAll(writer); + writer.Write(" in ", true); + Expr.WriteAll(writer); + writer.Write(")", false); + writer.EndLine(); + } + } + + + public CSForEach(CSType type, CSIdentifier ident, CSBaseExpression expr, CSCodeBlock body) + { + Type = type; + Ident = Exceptions.ThrowOnNull(ident, nameof(ident)); + Expr = Exceptions.ThrowOnNull(expr, nameof(expr)); + Body = body ?? new CSCodeBlock(); + Add(new ForElement(type, ident, expr)); + Add(Body); + } + + public CSForEach(CSType type, string ident, CSBaseExpression expr, CSCodeBlock body) + : this(type, new CSIdentifier(ident), expr, body) + { + } + + public CSType Type { get; private set; } + public CSIdentifier Ident { get; private set; } + public CSBaseExpression Expr { get; private set; } + public CSCodeBlock Body { get; private set; } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs index ac6473589aa1..02e250877d10 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs @@ -3,130 +3,132 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSFunctionCall : CSBaseExpression, ICSLineable { - public CSFunctionCall (CSIdentifier ident, CommaListElementCollection paramList, bool isConstructor = false) - { - Name = Exceptions.ThrowOnNull (ident, "ident"); - Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); - IsConstructor = isConstructor; - } - - public CSFunctionCall (string identifier, bool isConstructor, params CSBaseExpression [] parameters) - : this (new CSIdentifier (identifier), new CommaListElementCollection (parameters), isConstructor) - { - } - - public static CSFunctionCall Function (string identifier, params CSBaseExpression [] parameters) - { - return new CSFunctionCall (identifier, false, parameters); - } - public static CSLine FunctionLine (string identifier, params CSBaseExpression [] parameters) => new CSLine (Function (identifier, parameters)); - - public static CSFunctionCall Ctor (string identifier, params CSBaseExpression [] parameters) - { - return new CSFunctionCall (identifier, true, parameters); - } - public static CSLine CtorLine (string identifier, params CSBaseExpression [] parameters) => new CSLine (Ctor (identifier, parameters)); - - public static CSLine ConsoleWriteLine (params CSBaseExpression [] parameters) => FunctionLine ("Console.WriteLine", parameters); - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (IsConstructor) - writer.Write ("new ", false); - Name.WriteAll (writer); - writer.Write ("(", false); - Parameters.WriteAll (writer); - writer.Write (")", false); - } - - public bool IsConstructor { get; private set; } - public CSIdentifier Name { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - - public static CSLine FunctionCallLine (CSIdentifier identifier, params CSBaseExpression [] parameters) - { - return FunctionCallLine (identifier, false, parameters); - } - - public static CSLine FunctionCallLine (CSIdentifier identifier, bool isConstructor, params CSBaseExpression [] parameters) - { - return new CSLine (new CSFunctionCall (identifier, - new CommaListElementCollection (parameters), isConstructor)); - } - - public static CSLine FunctionCallLine (string identifier, params CSBaseExpression [] parameters) - { - return FunctionCallLine (identifier, false, parameters); - } - - public static CSLine FunctionCallLine (string identifier, bool isConstructor, params CSBaseExpression [] parameters) - { - return new CSLine (new CSFunctionCall (new CSIdentifier (Exceptions.ThrowOnNull (identifier, "identifier")), - new CommaListElementCollection (parameters), isConstructor)); - } - - static CSIdentifier iNameOf = new CSIdentifier ("nameof"); - - public static CSFunctionCall Nameof (CSIdentifier id) - { - return FooOf (iNameOf, id); - } - - public static CSFunctionCall Nameof (string name) - { - return Nameof (new CSIdentifier (name)); - } - - static CSIdentifier iTypeof = new CSIdentifier ("typeof"); - - public static CSFunctionCall Typeof (Type t) - { - return Typeof (t.Name); - } - - public static CSFunctionCall Typeof (string t) - { - return FooOf (iTypeof, new CSIdentifier (t)); - } - - public static CSFunctionCall Typeof (CSSimpleType t) - { - return Typeof (t.Name); - } - - static CSIdentifier iSizeof = new CSIdentifier ("sizeof"); - - public static CSFunctionCall Sizeof (CSBaseExpression expr) - { - return FooOf (iSizeof, expr); - } - - static CSIdentifier iDefault = new CSIdentifier ("default"); - - public static CSFunctionCall Default (Type t) - { - return Default (t.Name); - } - - public static CSFunctionCall Default (string t) - { - return FooOf (iDefault, new CSIdentifier (t)); - } - - public static CSFunctionCall Default (CSSimpleType t) - { - return Default (t.Name); - } - - static CSFunctionCall FooOf (CSIdentifier foo, CSBaseExpression parameter) - { - CommaListElementCollection parms = new CommaListElementCollection (); - parms.Add (parameter); - return new CSFunctionCall (foo, parms, false); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSFunctionCall : CSBaseExpression, ICSLineable + { + public CSFunctionCall(CSIdentifier ident, CommaListElementCollection paramList, bool isConstructor = false) + { + Name = Exceptions.ThrowOnNull(ident, "ident"); + Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + IsConstructor = isConstructor; + } + + public CSFunctionCall(string identifier, bool isConstructor, params CSBaseExpression[] parameters) + : this(new CSIdentifier(identifier), new CommaListElementCollection(parameters), isConstructor) + { + } + + public static CSFunctionCall Function(string identifier, params CSBaseExpression[] parameters) + { + return new CSFunctionCall(identifier, false, parameters); + } + public static CSLine FunctionLine(string identifier, params CSBaseExpression[] parameters) => new CSLine(Function(identifier, parameters)); + + public static CSFunctionCall Ctor(string identifier, params CSBaseExpression[] parameters) + { + return new CSFunctionCall(identifier, true, parameters); + } + public static CSLine CtorLine(string identifier, params CSBaseExpression[] parameters) => new CSLine(Ctor(identifier, parameters)); + + public static CSLine ConsoleWriteLine(params CSBaseExpression[] parameters) => FunctionLine("Console.WriteLine", parameters); + + protected override void LLWrite(ICodeWriter writer, object o) + { + if (IsConstructor) + writer.Write("new ", false); + Name.WriteAll(writer); + writer.Write("(", false); + Parameters.WriteAll(writer); + writer.Write(")", false); + } + + public bool IsConstructor { get; private set; } + public CSIdentifier Name { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + public static CSLine FunctionCallLine(CSIdentifier identifier, params CSBaseExpression[] parameters) + { + return FunctionCallLine(identifier, false, parameters); + } + + public static CSLine FunctionCallLine(CSIdentifier identifier, bool isConstructor, params CSBaseExpression[] parameters) + { + return new CSLine(new CSFunctionCall(identifier, + new CommaListElementCollection(parameters), isConstructor)); + } + + public static CSLine FunctionCallLine(string identifier, params CSBaseExpression[] parameters) + { + return FunctionCallLine(identifier, false, parameters); + } + + public static CSLine FunctionCallLine(string identifier, bool isConstructor, params CSBaseExpression[] parameters) + { + return new CSLine(new CSFunctionCall(new CSIdentifier(Exceptions.ThrowOnNull(identifier, "identifier")), + new CommaListElementCollection(parameters), isConstructor)); + } + + static CSIdentifier iNameOf = new CSIdentifier("nameof"); + + public static CSFunctionCall Nameof(CSIdentifier id) + { + return FooOf(iNameOf, id); + } + + public static CSFunctionCall Nameof(string name) + { + return Nameof(new CSIdentifier(name)); + } + + static CSIdentifier iTypeof = new CSIdentifier("typeof"); + + public static CSFunctionCall Typeof(Type t) + { + return Typeof(t.Name); + } + + public static CSFunctionCall Typeof(string t) + { + return FooOf(iTypeof, new CSIdentifier(t)); + } + + public static CSFunctionCall Typeof(CSSimpleType t) + { + return Typeof(t.Name); + } + + static CSIdentifier iSizeof = new CSIdentifier("sizeof"); + + public static CSFunctionCall Sizeof(CSBaseExpression expr) + { + return FooOf(iSizeof, expr); + } + + static CSIdentifier iDefault = new CSIdentifier("default"); + + public static CSFunctionCall Default(Type t) + { + return Default(t.Name); + } + + public static CSFunctionCall Default(string t) + { + return FooOf(iDefault, new CSIdentifier(t)); + } + + public static CSFunctionCall Default(CSSimpleType t) + { + return Default(t.Name); + } + + static CSFunctionCall FooOf(CSIdentifier foo, CSBaseExpression parameter) + { + CommaListElementCollection parms = new CommaListElementCollection(); + parms.Add(parameter); + return new CSFunctionCall(foo, parms, false); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs index ee0f318d7211..36539f39a64a 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs @@ -4,78 +4,85 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSGenericConstraint : DelegatedSimpleElement { - public CSGenericConstraint (CSIdentifier name, CSIdentifier isA) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - IsA = new CommaListElementCollection (); - IsA.Add (Exceptions.ThrowOnNull (isA, nameof (isA))); - } +namespace SyntaxDynamo.CSLang +{ + public class CSGenericConstraint : DelegatedSimpleElement + { + public CSGenericConstraint(CSIdentifier name, CSIdentifier isA) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + IsA = new CommaListElementCollection(); + IsA.Add(Exceptions.ThrowOnNull(isA, nameof(isA))); + } - public CSGenericConstraint (CSIdentifier name, IEnumerable multiIs) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - IsA = new CommaListElementCollection (); - if (multiIs != null) - IsA.AddRange (multiIs); - } + public CSGenericConstraint(CSIdentifier name, IEnumerable multiIs) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + IsA = new CommaListElementCollection(); + if (multiIs != null) + IsA.AddRange(multiIs); + } - public CSIdentifier Name { get; private set; } - public CommaListElementCollection IsA { get; private set; } + public CSIdentifier Name { get; private set; } + public CommaListElementCollection IsA { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("where ", true); - Name.Write (writer, o); - writer.Write (" : ", true); - IsA.WriteAll (writer); - } - } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("where ", true); + Name.Write(writer, o); + writer.Write(" : ", true); + IsA.WriteAll(writer); + } + } - public class CSGenericConstraintCollection : List, ICodeElementSet { - public IEnumerable Elements { - get { - bool first = true; - foreach (CSGenericConstraint tc in this) { - if (!first) { - yield return new LineBreak (); - } - first = false; - yield return tc; - } - } - } + public class CSGenericConstraintCollection : List, ICodeElementSet + { + public IEnumerable Elements + { + get + { + bool first = true; + foreach (CSGenericConstraint tc in this) + { + if (!first) + { + yield return new LineBreak(); + } + first = false; + yield return tc; + } + } + } - public event EventHandler Begin = (s, e) => { }; + public event EventHandler Begin = (s, e) => { }; - public event EventHandler End = (s, e) => { }; + public event EventHandler End = (s, e) => { }; - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } - public virtual void Write (ICodeWriter writer, object o) - { - } + public virtual void Write(ICodeWriter writer, object o) + { + } - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } - } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs index 2ef843588c8d..58c3c6b466cd 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs @@ -4,68 +4,78 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSGenericTypeDeclaration { - public CSGenericTypeDeclaration (CSIdentifier name) - { - Name = Exceptions.ThrowOnNull (name, nameof (name)); - } +namespace SyntaxDynamo.CSLang +{ + public class CSGenericTypeDeclaration + { + public CSGenericTypeDeclaration(CSIdentifier name) + { + Name = Exceptions.ThrowOnNull(name, nameof(name)); + } - public CSIdentifier Name { get; private set; } - } + public CSIdentifier Name { get; private set; } + } - public class CSGenericTypeDeclarationCollection : List, ICodeElementSet { - public CSGenericTypeDeclarationCollection () - : base () - { - } + public class CSGenericTypeDeclarationCollection : List, ICodeElementSet + { + public CSGenericTypeDeclarationCollection() + : base() + { + } - public IEnumerable Elements { - get { - if (this.Count > 0) { - yield return new SimpleElement ("<"); - bool first = true; - foreach (CSGenericTypeDeclaration decl in this) { - if (!first) { - yield return new SimpleElement (",", true); - yield return SimpleElement.Spacer; - } else { - first = false; - } - yield return decl.Name; - } - yield return new SimpleElement (">"); - } - } - } + public IEnumerable Elements + { + get + { + if (this.Count > 0) + { + yield return new SimpleElement("<"); + bool first = true; + foreach (CSGenericTypeDeclaration decl in this) + { + if (!first) + { + yield return new SimpleElement(",", true); + yield return SimpleElement.Spacer; + } + else + { + first = false; + } + yield return decl.Name; + } + yield return new SimpleElement(">"); + } + } + } - public event EventHandler Begin = (s, e) => { }; + public event EventHandler Begin = (s, e) => { }; - public event EventHandler End = (s, e) => { }; + public event EventHandler End = (s, e) => { }; - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } - public virtual void Write (ICodeWriter writer, object o) - { - } + public virtual void Write(ICodeWriter writer, object o) + { + } - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - } + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs index 6df2a664bd27..856bbea1ee3b 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs @@ -4,36 +4,38 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSIdentifier : CSBaseExpression { - public CSIdentifier (string name) - { - Name = Exceptions.ThrowOnNull (name, "name"); - } - - public static explicit operator CSIdentifier (string name) - { - return new CSIdentifier (name); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Name, false); - } - - public string Name { get; private set; } - - public override string ToString () - { - return Name; - } - - public static CSIdentifier Create (string name) => new CSIdentifier (name); - - static CSIdentifier thisID = new CSIdentifier ("this"); - public static CSIdentifier This { get { return thisID; } } - static CSIdentifier baseID = new CSIdentifier ("base"); - public static CSIdentifier Base { get { return baseID; } } - } +namespace SyntaxDynamo.CSLang +{ + public class CSIdentifier : CSBaseExpression + { + public CSIdentifier(string name) + { + Name = Exceptions.ThrowOnNull(name, "name"); + } + + public static explicit operator CSIdentifier(string name) + { + return new CSIdentifier(name); + } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write(Name, false); + } + + public string Name { get; private set; } + + public override string ToString() + { + return Name; + } + + public static CSIdentifier Create(string name) => new CSIdentifier(name); + + static CSIdentifier thisID = new CSIdentifier("this"); + public static CSIdentifier This { get { return thisID; } } + static CSIdentifier baseID = new CSIdentifier("base"); + public static CSIdentifier Base { get { return baseID; } } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs index 02b906f7104e..ffcff9b5c823 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs @@ -4,55 +4,59 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSIfElse : CodeElementCollection, ICSStatement { - class CSIfElement : DelegatedSimpleElement, ICSStatement { - public CSIfElement (CSBaseExpression condition) - : base () - { - Condition = condition; - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - writer.Write ("if (", false); - Condition.WriteAll (writer); - writer.Write (")", false); - writer.EndLine (); - } - - public CSBaseExpression Condition { get; private set; } - } - - public CSIfElse (CSBaseExpression condition, CSCodeBlock ifClause, CSCodeBlock elseClause = null) - : base () - { - Condition = new CSIfElement (Exceptions.ThrowOnNull (condition, "condition")); - IfClause = Exceptions.ThrowOnNull (ifClause, "ifClause"); - ElseClause = elseClause; - - Add (Condition); - Add (IfClause); - if (ElseClause != null && ElseClause.Count > 0) { - Add (new SimpleLineElement ("else", false, true, false)); - Add (ElseClause); - } - } - - public CSIfElse (CSBaseExpression expr, IEnumerable ifClause, IEnumerable elseClause) - : this (expr, new CSCodeBlock (ifClause), - elseClause != null ? new CSCodeBlock (elseClause) : null) - - { - - } - - public DelegatedSimpleElement Condition { get; private set; } - public CSCodeBlock IfClause { get; private set; } - public CSCodeBlock ElseClause { get; private set; } - - - } +namespace SyntaxDynamo.CSLang +{ + public class CSIfElse : CodeElementCollection, ICSStatement + { + class CSIfElement : DelegatedSimpleElement, ICSStatement + { + public CSIfElement(CSBaseExpression condition) + : base() + { + Condition = condition; + } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + writer.Write("if (", false); + Condition.WriteAll(writer); + writer.Write(")", false); + writer.EndLine(); + } + + public CSBaseExpression Condition { get; private set; } + } + + public CSIfElse(CSBaseExpression condition, CSCodeBlock ifClause, CSCodeBlock elseClause = null) + : base() + { + Condition = new CSIfElement(Exceptions.ThrowOnNull(condition, "condition")); + IfClause = Exceptions.ThrowOnNull(ifClause, "ifClause"); + ElseClause = elseClause; + + Add(Condition); + Add(IfClause); + if (ElseClause != null && ElseClause.Count > 0) + { + Add(new SimpleLineElement("else", false, true, false)); + Add(ElseClause); + } + } + + public CSIfElse(CSBaseExpression expr, IEnumerable ifClause, IEnumerable elseClause) + : this(expr, new CSCodeBlock(ifClause), + elseClause != null ? new CSCodeBlock(elseClause) : null) + + { + + } + + public DelegatedSimpleElement Condition { get; private set; } + public CSCodeBlock IfClause { get; private set; } + public CSCodeBlock ElseClause { get; private set; } + + + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs index dd9d3606feb0..8ec0d0656377 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs @@ -3,41 +3,43 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSIndexExpression : CSBaseExpression { - public CSIndexExpression (CSBaseExpression aggregate, CommaListElementCollection paramList, bool addParensAroundAggregate) - { - AddParensAroundAggregate = addParensAroundAggregate; - Aggregate = Exceptions.ThrowOnNull (aggregate, "aggregate"); - Parameters = Exceptions.ThrowOnNull (paramList, "paramList"); - } - - public CSIndexExpression (string identifier, bool addParensAroundAggregate, params CSBaseExpression [] parameters) - : this (new CSIdentifier (identifier), new CommaListElementCollection (parameters), addParensAroundAggregate) - { - } - - public CSIndexExpression (CSBaseExpression aggregate, bool addParensAroundAggregate, params CSBaseExpression [] parameters) - : this (aggregate, new CommaListElementCollection (parameters), addParensAroundAggregate) - { - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - if (AddParensAroundAggregate) - writer.Write ('(', false); - Aggregate.WriteAll (writer); - if (AddParensAroundAggregate) - writer.Write (')', false); - writer.Write ("[", false); - Parameters.WriteAll (writer); - writer.Write ("]", false); - } - - public bool AddParensAroundAggregate { get; private set; } - public CSBaseExpression Aggregate { get; private set; } - public CommaListElementCollection Parameters { get; private set; } - - } +namespace SyntaxDynamo.CSLang +{ + public class CSIndexExpression : CSBaseExpression + { + public CSIndexExpression(CSBaseExpression aggregate, CommaListElementCollection paramList, bool addParensAroundAggregate) + { + AddParensAroundAggregate = addParensAroundAggregate; + Aggregate = Exceptions.ThrowOnNull(aggregate, "aggregate"); + Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + } + + public CSIndexExpression(string identifier, bool addParensAroundAggregate, params CSBaseExpression[] parameters) + : this(new CSIdentifier(identifier), new CommaListElementCollection(parameters), addParensAroundAggregate) + { + } + + public CSIndexExpression(CSBaseExpression aggregate, bool addParensAroundAggregate, params CSBaseExpression[] parameters) + : this(aggregate, new CommaListElementCollection(parameters), addParensAroundAggregate) + { + } + + protected override void LLWrite(ICodeWriter writer, object o) + { + if (AddParensAroundAggregate) + writer.Write('(', false); + Aggregate.WriteAll(writer); + if (AddParensAroundAggregate) + writer.Write(')', false); + writer.Write("[", false); + Parameters.WriteAll(writer); + writer.Write("]", false); + } + + public bool AddParensAroundAggregate { get; private set; } + public CSBaseExpression Aggregate { get; private set; } + public CommaListElementCollection Parameters { get; private set; } + + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs index bbdb8263a575..77f91acd69cb 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs @@ -6,24 +6,26 @@ using System.Linq; using System.IO; -namespace SyntaxDynamo.CSLang { - public class CSInheritance : CommaListElementCollection { - public CSInheritance (IEnumerable identifiers) - { - if (identifiers != null) - AddRange (identifiers); - } +namespace SyntaxDynamo.CSLang +{ + public class CSInheritance : CommaListElementCollection + { + public CSInheritance(IEnumerable identifiers) + { + if (identifiers != null) + AddRange(identifiers); + } - public CSInheritance (params string [] identifiers) - : this (identifiers.Select (str => new CSIdentifier (str))) - { - } + public CSInheritance(params string[] identifiers) + : this(identifiers.Select(str => new CSIdentifier(str))) + { + } - public void Add (Type t) - { - Exceptions.ThrowOnNull (t, "t"); - Add (new CSIdentifier (t.Name)); - } - } + public void Add(Type t) + { + Exceptions.ThrowOnNull(t, "t"); + Add(new CSIdentifier(t.Name)); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs index 06916ae0214c..8293e4453ed1 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs @@ -4,43 +4,46 @@ using System; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSInitializer : CSBaseExpression { - public CSInitializer (IEnumerable parameters, bool appendNewlineAfterEach) - { - Parameters = new CommaListElementCollection ("", "", parameters, appendNewlineAfterEach); - } - - public CommaListElementCollection Parameters { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("{ ", false); - Parameters.WriteAll (writer); - writer.Write (" }", false); - } - } - - public class CSInitializedType : CSBaseExpression { - public CSInitializedType (CSFunctionCall call, CSInitializer initializer) - { - Call = Exceptions.ThrowOnNull (call, nameof (call)); - Initializer = Exceptions.ThrowOnNull (initializer, nameof (initializer)); - } - - public CSInitializedType (CSFunctionCall call, IEnumerable parameters, bool appendNewlineAfterEach) - : this (call, new CSInitializer (parameters, appendNewlineAfterEach)) - { - } - - public CSFunctionCall Call { get; private set; } - public CSInitializer Initializer { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - Call.WriteAll (writer); - SimpleElement.Spacer.WriteAll (writer); - Initializer.WriteAll (writer); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSInitializer : CSBaseExpression + { + public CSInitializer(IEnumerable parameters, bool appendNewlineAfterEach) + { + Parameters = new CommaListElementCollection("", "", parameters, appendNewlineAfterEach); + } + + public CommaListElementCollection Parameters { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("{ ", false); + Parameters.WriteAll(writer); + writer.Write(" }", false); + } + } + + public class CSInitializedType : CSBaseExpression + { + public CSInitializedType(CSFunctionCall call, CSInitializer initializer) + { + Call = Exceptions.ThrowOnNull(call, nameof(call)); + Initializer = Exceptions.ThrowOnNull(initializer, nameof(initializer)); + } + + public CSInitializedType(CSFunctionCall call, IEnumerable parameters, bool appendNewlineAfterEach) + : this(call, new CSInitializer(parameters, appendNewlineAfterEach)) + { + } + + public CSFunctionCall Call { get; private set; } + public CSInitializer Initializer { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + Call.WriteAll(writer); + SimpleElement.Spacer.WriteAll(writer); + Initializer.WriteAll(writer); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs index 368a1b6bcb13..a522a92b4e8f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs @@ -1,19 +1,21 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SyntaxDynamo.CSLang { - // CSInject is a way to more formalize the notion of code that is just plain easier to - // inject as raw text. It's not strictly necessary, but when you see a CSInject, it will make - // it clear that you're doing something not quite on the up and up. - public class CSInject : CSIdentifier { - public CSInject (string name) - : base (name) - { - } +namespace SyntaxDynamo.CSLang +{ + // CSInject is a way to more formalize the notion of code that is just plain easier to + // inject as raw text. It's not strictly necessary, but when you see a CSInject, it will make + // it clear that you're doing something not quite on the up and up. + public class CSInject : CSIdentifier + { + public CSInject(string name) + : base(name) + { + } - public static explicit operator CSInject (string name) - { - return new CSInject (name); - } - } + public static explicit operator CSInject(string name) + { + return new CSInject(name); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs index 10f918ed1d19..37faa49174be 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs @@ -5,115 +5,122 @@ using System.Collections.Generic; using System.Linq; -namespace SyntaxDynamo.CSLang { - public class CSInterface : ICodeElementSet, ICSTopLevelDeclaration { - public CSInterface (CSVisibility vis, CSIdentifier name, - IEnumerable methods = null) - { - Visibility = vis; - Name = Exceptions.ThrowOnNull (name, "name"); - Inheritance = new CSInheritance (); - Methods = new List (); - Properties = new List (); - GenericParams = new CSGenericTypeDeclarationCollection (); - GenericConstraints = new CSGenericConstraintCollection (); - if (methods != null) - Methods.AddRange (methods); - } - - public CSInterface (CSVisibility vis, string name, IEnumerable methods = null) - : this (vis, new CSIdentifier (name), methods) - { - } - - - public CSType ToCSType (IEnumerable genericReplacements) - { - var replacements = genericReplacements.ToList (); - if (replacements.Count < GenericParams.Count) { - replacements.AddRange (GenericParams.Skip (replacements.Count).Select (gen => new CSSimpleType (gen.Name.Name))); - } - return new CSSimpleType (Name.Name, false, replacements.ToArray ()); - } - - public CSType ToCSType () - { - return ToCSType (GenericParams.Select (gen => new CSSimpleType (gen.Name.Name))); - } - - public CSVisibility Visibility { get; private set; } - public CSIdentifier Name { get; private set; } - public CSInheritance Inheritance { get; private set; } - public List Methods { get; private set; } - public List Properties { get; private set; } - public CSGenericTypeDeclarationCollection GenericParams { get; private set; } - public CSGenericConstraintCollection GenericConstraints { get; private set; } - - #region ICodeElem implementation - public event EventHandler Begin = (s, e) => { }; - - public event EventHandler End = (s, e) => { }; - - public virtual object BeginWrite (ICodeWriter writer) - { - OnBeginWrite (new WriteEventArgs (writer)); - return null; - } - - protected virtual void OnBeginWrite (WriteEventArgs args) - { - Begin (this, args); - } - - public virtual void Write (ICodeWriter writer, object o) - { - } - - public virtual void EndWrite (ICodeWriter writer, object o) - { - OnEndWrite (new WriteEventArgs (writer)); - } - - protected virtual void OnEndWrite (WriteEventArgs args) - { - End.FireInReverse (this, args); - } - - #endregion - - #region ICodeElemSet implementation - - public IEnumerable Elements { - get { - var decl = new LineCodeElementCollection (true, false, true); - if (Visibility != CSVisibility.None) - decl.Add (new SimpleElement (CSMethod.VisibilityToString (Visibility) + " ")); - decl.Add (new CSIdentifier ("interface ")); - decl.Add (Name); - - decl.Add (GenericParams); - if (Inheritance.Count > 0) { - decl.Add (new SimpleElement (" : ", true)); - decl.Add (Inheritance); - } - if (GenericConstraints.Count > 0) { - decl.Add (SimpleElement.Spacer); - decl.Add (GenericConstraints); - } - yield return decl; - - var contents = new DecoratedCodeElementCollection ("{", "}", - true, true, true); - - contents.AddRange (Methods); - contents.AddRange (Properties); - - yield return contents; - - } - } - - #endregion - } +namespace SyntaxDynamo.CSLang +{ + public class CSInterface : ICodeElementSet, ICSTopLevelDeclaration + { + public CSInterface(CSVisibility vis, CSIdentifier name, + IEnumerable methods = null) + { + Visibility = vis; + Name = Exceptions.ThrowOnNull(name, "name"); + Inheritance = new CSInheritance(); + Methods = new List(); + Properties = new List(); + GenericParams = new CSGenericTypeDeclarationCollection(); + GenericConstraints = new CSGenericConstraintCollection(); + if (methods != null) + Methods.AddRange(methods); + } + + public CSInterface(CSVisibility vis, string name, IEnumerable methods = null) + : this(vis, new CSIdentifier(name), methods) + { + } + + + public CSType ToCSType(IEnumerable genericReplacements) + { + var replacements = genericReplacements.ToList(); + if (replacements.Count < GenericParams.Count) + { + replacements.AddRange(GenericParams.Skip(replacements.Count).Select(gen => new CSSimpleType(gen.Name.Name))); + } + return new CSSimpleType(Name.Name, false, replacements.ToArray()); + } + + public CSType ToCSType() + { + return ToCSType(GenericParams.Select(gen => new CSSimpleType(gen.Name.Name))); + } + + public CSVisibility Visibility { get; private set; } + public CSIdentifier Name { get; private set; } + public CSInheritance Inheritance { get; private set; } + public List Methods { get; private set; } + public List Properties { get; private set; } + public CSGenericTypeDeclarationCollection GenericParams { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + + #region ICodeElem implementation + public event EventHandler Begin = (s, e) => { }; + + public event EventHandler End = (s, e) => { }; + + public virtual object BeginWrite(ICodeWriter writer) + { + OnBeginWrite(new WriteEventArgs(writer)); + return null; + } + + protected virtual void OnBeginWrite(WriteEventArgs args) + { + Begin(this, args); + } + + public virtual void Write(ICodeWriter writer, object o) + { + } + + public virtual void EndWrite(ICodeWriter writer, object o) + { + OnEndWrite(new WriteEventArgs(writer)); + } + + protected virtual void OnEndWrite(WriteEventArgs args) + { + End.FireInReverse(this, args); + } + + #endregion + + #region ICodeElemSet implementation + + public IEnumerable Elements + { + get + { + var decl = new LineCodeElementCollection(true, false, true); + if (Visibility != CSVisibility.None) + decl.Add(new SimpleElement(CSMethod.VisibilityToString(Visibility) + " ")); + decl.Add(new CSIdentifier("interface ")); + decl.Add(Name); + + decl.Add(GenericParams); + if (Inheritance.Count > 0) + { + decl.Add(new SimpleElement(" : ", true)); + decl.Add(Inheritance); + } + if (GenericConstraints.Count > 0) + { + decl.Add(SimpleElement.Spacer); + decl.Add(GenericConstraints); + } + yield return decl; + + var contents = new DecoratedCodeElementCollection("{", "}", + true, true, true); + + contents.AddRange(Methods); + contents.AddRange(Properties); + + yield return contents; + + } + } + + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs index c33cca59169d..834ae0819117 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs @@ -5,68 +5,78 @@ using System.Linq; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSLambda : CSBaseExpression { - public CSLambda (CSParameterList parameters, ICSExpression value) - { - Parameters = parameters ?? new CSParameterList (); - Value = Exceptions.ThrowOnNull (value, "value"); - Body = null; - } +namespace SyntaxDynamo.CSLang +{ + public class CSLambda : CSBaseExpression + { + public CSLambda(CSParameterList parameters, ICSExpression value) + { + Parameters = parameters ?? new CSParameterList(); + Value = Exceptions.ThrowOnNull(value, "value"); + Body = null; + } - public CSLambda (CSParameterList parameters, CSCodeBlock body) - { - body = body ?? new CSCodeBlock (); - Parameters = parameters ?? new CSParameterList (); - Value = null; - Body = body; - } + public CSLambda(CSParameterList parameters, CSCodeBlock body) + { + body = body ?? new CSCodeBlock(); + Parameters = parameters ?? new CSParameterList(); + Value = null; + Body = body; + } - public CSLambda (ICSExpression value, params string [] parameters) - : this (new CSParameterList (parameters.Select (p => new CSParameter (CSSimpleType.Void, new CSIdentifier (p)))), value) - { - } + public CSLambda(ICSExpression value, params string[] parameters) + : this(new CSParameterList(parameters.Select(p => new CSParameter(CSSimpleType.Void, new CSIdentifier(p)))), value) + { + } - public CSLambda (CSCodeBlock body, params string [] parameters) - : this (new CSParameterList (parameters.Select (p => new CSParameter (CSSimpleType.Void, new CSIdentifier (p)))), body) - { - } + public CSLambda(CSCodeBlock body, params string[] parameters) + : this(new CSParameterList(parameters.Select(p => new CSParameter(CSSimpleType.Void, new CSIdentifier(p)))), body) + { + } - public CSParameterList Parameters { get; private set; } - public ICSExpression Value { get; private set; } - public CSCodeBlock Body { get; private set; } + public CSParameterList Parameters { get; private set; } + public ICSExpression Value { get; private set; } + public CSCodeBlock Body { get; private set; } - #region implemented abstract members of DelegatedSimpleElem + #region implemented abstract members of DelegatedSimpleElem - protected override void LLWrite (ICodeWriter writer, object o) - { - // hack - Parameters really want types. If you set them to void, we'll consider them to be - // typeless. - bool allVoid = Parameters.All (p => p.CSType == CSSimpleType.Void); + protected override void LLWrite(ICodeWriter writer, object o) + { + // hack - Parameters really want types. If you set them to void, we'll consider them to be + // typeless. + bool allVoid = Parameters.All(p => p.CSType == CSSimpleType.Void); - writer.Write ('(', true); - if (allVoid) { - bool didFirst = false; - foreach (CSParameter p in Parameters) { - if (didFirst) { - writer.Write (", ", true); - } - p.Name.WriteAll (writer); - didFirst = true; - } - } else { - Parameters.WriteAll (writer); - } - writer.Write (") => ", true); - if (Value != null) { - Value.WriteAll (writer); - } else { - Body.WriteAll (writer); - } - } + writer.Write('(', true); + if (allVoid) + { + bool didFirst = false; + foreach (CSParameter p in Parameters) + { + if (didFirst) + { + writer.Write(", ", true); + } + p.Name.WriteAll(writer); + didFirst = true; + } + } + else + { + Parameters.WriteAll(writer); + } + writer.Write(") => ", true); + if (Value != null) + { + Value.WriteAll(writer); + } + else + { + Body.WriteAll(writer); + } + } - #endregion - } + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs index 64cc40603a4d..b76d4cc502df 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs @@ -4,27 +4,29 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSLine : DelegatedSimpleElement, ICSStatement { - public CSLine (ICodeElement contents, bool addSemicolon = true) - { - Contents = Exceptions.ThrowOnNull (contents, nameof(contents)); - if (!(contents is ICSLineable) && addSemicolon) - throw new ArgumentException ("contents must be ILineable", nameof (contents)); - AddSemicolon = addSemicolon; - } +namespace SyntaxDynamo.CSLang +{ + public class CSLine : DelegatedSimpleElement, ICSStatement + { + public CSLine(ICodeElement contents, bool addSemicolon = true) + { + Contents = Exceptions.ThrowOnNull(contents, nameof(contents)); + if (!(contents is ICSLineable) && addSemicolon) + throw new ArgumentException("contents must be ILineable", nameof(contents)); + AddSemicolon = addSemicolon; + } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - Contents.WriteAll (writer); - if (AddSemicolon) - writer.Write (';', false); - writer.EndLine (); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + Contents.WriteAll(writer); + if (AddSemicolon) + writer.Write(';', false); + writer.EndLine(); + } - public ICodeElement Contents { get; private set; } - public bool AddSemicolon { get; set; } - } + public ICodeElement Contents { get; private set; } + public bool AddSemicolon { get; set; } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs index ef23cc88a1e3..9377a859be0f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs @@ -6,226 +6,236 @@ using System.Linq; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSMethod : CodeElementCollection { - public CSMethod (CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, CSParameterList parms, CSCodeBlock body) - : this (vis, kind, type, name, parms, null, false, body) - { - - } - public CSMethod (CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, - CSParameterList parms, CSBaseExpression [] baseOrThisCallParms, bool callsBase, CSCodeBlock body, bool isSealed = false, - bool isAsync = false) - { - GenericParameters = new CSGenericTypeDeclarationCollection (); - GenericConstraints = new CSGenericConstraintCollection (); - Visibility = vis; - Kind = kind; - Type = type; // no throw on null - could be constructor - Name = Exceptions.ThrowOnNull (name, nameof (name)); - Parameters = Exceptions.ThrowOnNull (parms, nameof (parms)); - CallsBase = callsBase; - BaseOrThisCallParameters = baseOrThisCallParms; - - Body = body; // can be null - IsSealed = isSealed; - IsAsync = isAsync; - - LineCodeElementCollection lc = new LineCodeElementCollection (new ICodeElement [0], false, true); - if (vis != CSVisibility.None) { - lc.And (new SimpleElement (VisibilityToString (vis))).And (SimpleElement.Spacer); - } - - if (isSealed) { - lc.And (new SimpleElement ("sealed")).And (SimpleElement.Spacer); - } - - if (isAsync) { - lc.And (new SimpleElement ("async")).And (SimpleElement.Spacer); - } - - lc.And (new SimpleElement (MethodKindToString (kind))).And (SimpleElement.Spacer); - - if (type != null) { - lc.And (type).And (SimpleElement.Spacer); - } - - lc.And (name).And (GenericParameters).And (new SimpleElement ("(")).And (parms).And (new SimpleElement (")")).And (GenericConstraints); - if (body == null) { - if (!(kind == CSMethodKind.StaticExtern || kind == CSMethodKind.Interface)) - throw new ArgumentException ("Method body is only optional when method kind kind is either StaticExtern or Interface", - nameof (body)); - lc.Add (new SimpleElement (";")); - } - Add (lc); - if (BaseOrThisCallParameters != null) { - Add (new CSFunctionCall (CallsBase ? ": base" : ": this", false, BaseOrThisCallParameters)); - } - if (body != null) - Add (body); - } - - public CSVisibility Visibility { get; private set; } - public CSMethodKind Kind { get; private set; } - public CSType Type { get; private set; } - public CSIdentifier Name { get; private set; } - public CSParameterList Parameters { get; private set; } - public bool CallsBase { get; private set; } - public CSBaseExpression [] BaseOrThisCallParameters { get; private set; } - public CSCodeBlock Body { get; private set; } - public CSGenericTypeDeclarationCollection GenericParameters { get; private set; } - public CSGenericConstraintCollection GenericConstraints { get; private set; } - public bool IsSealed { get; private set; } - public bool IsAsync { get; private set; } - - public CSMethod AsSealed () - { - var sealedMethod = new CSMethod (Visibility, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, true); - return CopyGenerics (this, sealedMethod); - } - - public CSMethod AsOverride () - { - var overrideMethod = new CSMethod (Visibility, CSMethodKind.Override, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); - return CopyGenerics (this, overrideMethod); - } - - public CSMethod AsPrivate () - { - var privateMethod = new CSMethod (CSVisibility.None, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); - return CopyGenerics (this, privateMethod); - } - - public static CSMethod CopyGenerics (CSMethod from, CSMethod to) - { - to.GenericParameters.AddRange (from.GenericParameters); - to.GenericConstraints.AddRange (from.GenericConstraints); - return to; - } - - public static CSMethod RemoveGenerics (CSMethod from) - { - var newMethod = new CSMethod (from.Visibility, from.Kind, from.Type, from.Name, from.Parameters, from.Body); - return newMethod; - } - - public static string VisibilityToString (CSVisibility visibility) - { - switch (visibility) { - case CSVisibility.None: - return ""; - case CSVisibility.Internal: - return "internal"; - case CSVisibility.Private: - return "private"; - case CSVisibility.Public: - return "public"; - case CSVisibility.Protected: - return "protected"; - default: - throw new ArgumentOutOfRangeException ("vis"); - } - } - - public static string MethodKindToString (CSMethodKind kind) - { - switch (kind) { - case CSMethodKind.None: - case CSMethodKind.Interface: - return ""; - case CSMethodKind.Extern: - return "extern"; - case CSMethodKind.New: - return "new"; - case CSMethodKind.Override: - return "override"; - case CSMethodKind.Static: - return "static"; - case CSMethodKind.StaticExtern: - return "static extern"; - case CSMethodKind.StaticNew: - return "static new"; - case CSMethodKind.Virtual: - return "virtual"; - case CSMethodKind.Abstract: - return "abstract"; - case CSMethodKind.Unsafe: - return "unsafe"; - case CSMethodKind.StaticUnsafe: - return "static unsafe"; - default: - throw new ArgumentOutOfRangeException (nameof (kind)); - } - } - - public static CSMethod PublicMethod (CSType type, string name, CSParameterList parms, CSCodeBlock body) - { - return new CSMethod (CSVisibility.Public, CSMethodKind.None, type, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PublicMethod (CSMethodKind kind, CSType type, string name, CSParameterList parms, CSCodeBlock body) - { - return new CSMethod (CSVisibility.Public, kind, type, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PublicConstructor (string name, CSParameterList parms, CSCodeBlock body) - { - return new CSMethod (CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PublicConstructor (string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression [] baseParams) - { - return new CSMethod (CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier (name), parms, - baseParams, true, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PrivateConstructor (string name, CSParameterList parms, CSCodeBlock body) - { - return new CSMethod (CSVisibility.None, CSMethodKind.None, null, new CSIdentifier (name), parms, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PrivateConstructor (string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression [] baseParams) - { - return new CSMethod (CSVisibility.None, CSMethodKind.None, null, new CSIdentifier (name), parms, - baseParams, true, Exceptions.ThrowOnNull (body, "body")); - } - - public static CSMethod PInvoke (CSVisibility vis, CSType type, string name, string dllName, string externName, CSParameterList parms) - { - CSMethod method = new CSMethod (vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull (type, "type"), - new CSIdentifier (name), parms, null); - - CSAttribute.DllImport (dllName, externName).AttachBefore (method); - - return method; - } - - public static CSMethod PInvoke (CSVisibility vis, CSType type, string name, CSBaseExpression dllName, string externName, CSParameterList parms) - { - CSMethod method = new CSMethod (vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull (type, "type"), - new CSIdentifier (name), parms, null); - - CSAttribute.DllImport (dllName, externName).AttachBefore (method); - - return method; - } - - public static CSMethod PublicPInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) - { - return PInvoke (CSVisibility.Public, type, name, dllName, externName, parms); - } - - public static CSMethod PrivatePInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) - { - return PInvoke (CSVisibility.None, type, name, dllName, externName, parms); - } - - public static CSMethod InternalPInvoke (CSType type, string name, string dllName, string externName, CSParameterList parms) - { - return PInvoke (CSVisibility.Internal, type, name, dllName, externName, parms); - } - - - } +namespace SyntaxDynamo.CSLang +{ + public class CSMethod : CodeElementCollection + { + public CSMethod(CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, CSParameterList parms, CSCodeBlock body) + : this(vis, kind, type, name, parms, null, false, body) + { + + } + public CSMethod(CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier name, + CSParameterList parms, CSBaseExpression[] baseOrThisCallParms, bool callsBase, CSCodeBlock body, bool isSealed = false, + bool isAsync = false) + { + GenericParameters = new CSGenericTypeDeclarationCollection(); + GenericConstraints = new CSGenericConstraintCollection(); + Visibility = vis; + Kind = kind; + Type = type; // no throw on null - could be constructor + Name = Exceptions.ThrowOnNull(name, nameof(name)); + Parameters = Exceptions.ThrowOnNull(parms, nameof(parms)); + CallsBase = callsBase; + BaseOrThisCallParameters = baseOrThisCallParms; + + Body = body; // can be null + IsSealed = isSealed; + IsAsync = isAsync; + + LineCodeElementCollection lc = new LineCodeElementCollection(new ICodeElement[0], false, true); + if (vis != CSVisibility.None) + { + lc.And(new SimpleElement(VisibilityToString(vis))).And(SimpleElement.Spacer); + } + + if (isSealed) + { + lc.And(new SimpleElement("sealed")).And(SimpleElement.Spacer); + } + + if (isAsync) + { + lc.And(new SimpleElement("async")).And(SimpleElement.Spacer); + } + + lc.And(new SimpleElement(MethodKindToString(kind))).And(SimpleElement.Spacer); + + if (type != null) + { + lc.And(type).And(SimpleElement.Spacer); + } + + lc.And(name).And(GenericParameters).And(new SimpleElement("(")).And(parms).And(new SimpleElement(")")).And(GenericConstraints); + if (body == null) + { + if (!(kind == CSMethodKind.StaticExtern || kind == CSMethodKind.Interface)) + throw new ArgumentException("Method body is only optional when method kind kind is either StaticExtern or Interface", + nameof(body)); + lc.Add(new SimpleElement(";")); + } + Add(lc); + if (BaseOrThisCallParameters != null) + { + Add(new CSFunctionCall(CallsBase ? ": base" : ": this", false, BaseOrThisCallParameters)); + } + if (body != null) + Add(body); + } + + public CSVisibility Visibility { get; private set; } + public CSMethodKind Kind { get; private set; } + public CSType Type { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList Parameters { get; private set; } + public bool CallsBase { get; private set; } + public CSBaseExpression[] BaseOrThisCallParameters { get; private set; } + public CSCodeBlock Body { get; private set; } + public CSGenericTypeDeclarationCollection GenericParameters { get; private set; } + public CSGenericConstraintCollection GenericConstraints { get; private set; } + public bool IsSealed { get; private set; } + public bool IsAsync { get; private set; } + + public CSMethod AsSealed() + { + var sealedMethod = new CSMethod(Visibility, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, true); + return CopyGenerics(this, sealedMethod); + } + + public CSMethod AsOverride() + { + var overrideMethod = new CSMethod(Visibility, CSMethodKind.Override, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); + return CopyGenerics(this, overrideMethod); + } + + public CSMethod AsPrivate() + { + var privateMethod = new CSMethod(CSVisibility.None, Kind, Type, Name, Parameters, BaseOrThisCallParameters, CallsBase, Body, IsSealed); + return CopyGenerics(this, privateMethod); + } + + public static CSMethod CopyGenerics(CSMethod from, CSMethod to) + { + to.GenericParameters.AddRange(from.GenericParameters); + to.GenericConstraints.AddRange(from.GenericConstraints); + return to; + } + + public static CSMethod RemoveGenerics(CSMethod from) + { + var newMethod = new CSMethod(from.Visibility, from.Kind, from.Type, from.Name, from.Parameters, from.Body); + return newMethod; + } + + public static string VisibilityToString(CSVisibility visibility) + { + switch (visibility) + { + case CSVisibility.None: + return ""; + case CSVisibility.Internal: + return "internal"; + case CSVisibility.Private: + return "private"; + case CSVisibility.Public: + return "public"; + case CSVisibility.Protected: + return "protected"; + default: + throw new ArgumentOutOfRangeException("vis"); + } + } + + public static string MethodKindToString(CSMethodKind kind) + { + switch (kind) + { + case CSMethodKind.None: + case CSMethodKind.Interface: + return ""; + case CSMethodKind.Extern: + return "extern"; + case CSMethodKind.New: + return "new"; + case CSMethodKind.Override: + return "override"; + case CSMethodKind.Static: + return "static"; + case CSMethodKind.StaticExtern: + return "static extern"; + case CSMethodKind.StaticNew: + return "static new"; + case CSMethodKind.Virtual: + return "virtual"; + case CSMethodKind.Abstract: + return "abstract"; + case CSMethodKind.Unsafe: + return "unsafe"; + case CSMethodKind.StaticUnsafe: + return "static unsafe"; + default: + throw new ArgumentOutOfRangeException(nameof(kind)); + } + } + + public static CSMethod PublicMethod(CSType type, string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod(CSVisibility.Public, CSMethodKind.None, type, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PublicMethod(CSMethodKind kind, CSType type, string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod(CSVisibility.Public, kind, type, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PublicConstructor(string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PublicConstructor(string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression[] baseParams) + { + return new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier(name), parms, + baseParams, true, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PrivateConstructor(string name, CSParameterList parms, CSCodeBlock body) + { + return new CSMethod(CSVisibility.None, CSMethodKind.None, null, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PrivateConstructor(string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression[] baseParams) + { + return new CSMethod(CSVisibility.None, CSMethodKind.None, null, new CSIdentifier(name), parms, + baseParams, true, Exceptions.ThrowOnNull(body, "body")); + } + + public static CSMethod PInvoke(CSVisibility vis, CSType type, string name, string dllName, string externName, CSParameterList parms) + { + CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull(type, "type"), + new CSIdentifier(name), parms, null); + + CSAttribute.DllImport(dllName, externName).AttachBefore(method); + + return method; + } + + public static CSMethod PInvoke(CSVisibility vis, CSType type, string name, CSBaseExpression dllName, string externName, CSParameterList parms) + { + CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull(type, "type"), + new CSIdentifier(name), parms, null); + + CSAttribute.DllImport(dllName, externName).AttachBefore(method); + + return method; + } + + public static CSMethod PublicPInvoke(CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke(CSVisibility.Public, type, name, dllName, externName, parms); + } + + public static CSMethod PrivatePInvoke(CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke(CSVisibility.None, type, name, dllName, externName, parms); + } + + public static CSMethod InternalPInvoke(CSType type, string name, string dllName, string externName, CSParameterList parms) + { + return PInvoke(CSVisibility.Internal, type, name, dllName, externName, parms); + } + + + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs index 6e5620c60844..d3bd9241e9da 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs @@ -6,46 +6,49 @@ using System.Linq; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public class CSNamespace : LabeledCodeElementCollection { - public CSNamespace () - : base (new SimpleLineElement (string.Empty, false, false, false), - new DecoratedCodeElementCollection (string.Empty, string.Empty, false, false, false)) - { - } - - public CSNamespace (string nameSpace) - : base (new SimpleLineElement (string.Format ("namespace {0}", Exceptions.ThrowOnNull (nameSpace, nameof (nameSpace))), - false, true, false), - new DecoratedCodeElementCollection ("{", "}", true, true, true)) - { - } - - } - - public class CSNamespaceBlock : CodeElementCollection { - public CSNamespaceBlock (params string [] nameSpaces) - : base () - { - this.AddRange (nameSpaces.Select (s => new CSNamespace (s))); - } - - public CSNamespaceBlock (IEnumerable nameSpaces) - : base () - { - this.AddRange (nameSpaces); - } - - public CSNamespaceBlock And (string s) - { - return And (new CSNamespace (s)); - } - - public CSNamespaceBlock And (CSNamespace ns) - { - Add (Exceptions.ThrowOnNull (ns, "ns")); - return this; - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSNamespace : LabeledCodeElementCollection + { + public CSNamespace() + : base(new SimpleLineElement(string.Empty, false, false, false), + new DecoratedCodeElementCollection(string.Empty, string.Empty, false, false, false)) + { + } + + public CSNamespace(string nameSpace) + : base(new SimpleLineElement(string.Format("namespace {0}", Exceptions.ThrowOnNull(nameSpace, nameof(nameSpace))), + false, true, false), + new DecoratedCodeElementCollection("{", "}", true, true, true)) + { + } + + } + + public class CSNamespaceBlock : CodeElementCollection + { + public CSNamespaceBlock(params string[] nameSpaces) + : base() + { + this.AddRange(nameSpaces.Select(s => new CSNamespace(s))); + } + + public CSNamespaceBlock(IEnumerable nameSpaces) + : base() + { + this.AddRange(nameSpaces); + } + + public CSNamespaceBlock And(string s) + { + return And(new CSNamespace(s)); + } + + public CSNamespaceBlock And(CSNamespace ns) + { + Add(Exceptions.ThrowOnNull(ns, "ns")); + return this; + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs index 4d56a09f621c..7307d025a33b 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs @@ -7,103 +7,109 @@ using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSParameter : DelegatedSimpleElement { - public CSParameter (CSType type, CSIdentifier name, - CSParameterKind parameterKind = CSParameterKind.None, - CSConstant defaultValue = null) - { - CSType = Exceptions.ThrowOnNull (type, nameof(type)); - Name = Exceptions.ThrowOnNull (name, nameof(name)); - ParameterKind = parameterKind; - DefaultValue = defaultValue; - } +namespace SyntaxDynamo.CSLang +{ + public class CSParameter : DelegatedSimpleElement + { + public CSParameter(CSType type, CSIdentifier name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + { + CSType = Exceptions.ThrowOnNull(type, nameof(type)); + Name = Exceptions.ThrowOnNull(name, nameof(name)); + ParameterKind = parameterKind; + DefaultValue = defaultValue; + } - public CSParameter (CSType type, string name, - CSParameterKind parameterKind = CSParameterKind.None, - CSConstant defaultValue = null) - : this (type, new CSIdentifier (name), parameterKind, defaultValue) - { - } + public CSParameter(CSType type, string name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + : this(type, new CSIdentifier(name), parameterKind, defaultValue) + { + } - public CSParameter (string type, string name, - CSParameterKind parameterKind = CSParameterKind.None, - CSConstant defaultValue = null) - : this (new CSSimpleType (type), new CSIdentifier (name), parameterKind, defaultValue) - { - } + public CSParameter(string type, string name, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + : this(new CSSimpleType(type), new CSIdentifier(name), parameterKind, defaultValue) + { + } - protected override void LLWrite (ICodeWriter writer, object o) - { - if (this.ParameterKind != CSParameterKind.None) { - writer.Write (ToParameterKindString (this.ParameterKind), false); - writer.Write (' ', false); - } - this.CSType.WriteAll (writer); - writer.Write (' ', true); - Name.WriteAll (writer); - if ((Object)DefaultValue != null) { - writer.Write (" = ", true); - DefaultValue.WriteAll (writer); - } - } + protected override void LLWrite(ICodeWriter writer, object o) + { + if (this.ParameterKind != CSParameterKind.None) + { + writer.Write(ToParameterKindString(this.ParameterKind), false); + writer.Write(' ', false); + } + this.CSType.WriteAll(writer); + writer.Write(' ', true); + Name.WriteAll(writer); + if ((Object)DefaultValue != null) + { + writer.Write(" = ", true); + DefaultValue.WriteAll(writer); + } + } - static string ToParameterKindString (CSParameterKind parameterKind) - { - switch (parameterKind) { - case CSParameterKind.None: - return ""; - case CSParameterKind.Out: - return "out"; - case CSParameterKind.Ref: - return "ref"; - case CSParameterKind.This: - return "this"; - case CSParameterKind.Params: - return "params"; - default: - throw new ArgumentOutOfRangeException (nameof(parameterKind), "unexpected parameter kind " + parameterKind.ToString ()); - } - } + static string ToParameterKindString(CSParameterKind parameterKind) + { + switch (parameterKind) + { + case CSParameterKind.None: + return ""; + case CSParameterKind.Out: + return "out"; + case CSParameterKind.Ref: + return "ref"; + case CSParameterKind.This: + return "this"; + case CSParameterKind.Params: + return "params"; + default: + throw new ArgumentOutOfRangeException(nameof(parameterKind), "unexpected parameter kind " + parameterKind.ToString()); + } + } - public CSType CSType { get; private set; } - public CSIdentifier Name { get; private set; } - public CSConstant DefaultValue { get; private set; } - public CSParameterKind ParameterKind { get; private set; } - } + public CSType CSType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSConstant DefaultValue { get; private set; } + public CSParameterKind ParameterKind { get; private set; } + } - public class CSParameterList : CommaListElementCollection { - public CSParameterList (IEnumerable parameters) - : base () - { - if (parameters != null) - AddRange (parameters); - } - public CSParameterList (params CSParameter[] parameters) - : base () - { - if (parameters != null) - AddRange (parameters); - } + public class CSParameterList : CommaListElementCollection + { + public CSParameterList(IEnumerable parameters) + : base() + { + if (parameters != null) + AddRange(parameters); + } + public CSParameterList(params CSParameter[] parameters) + : base() + { + if (parameters != null) + AddRange(parameters); + } - public CSParameterList () : this ((IEnumerable)null) { } + public CSParameterList() : this((IEnumerable)null) { } - public CSParameterList (CSParameter parameter) : this (new CSParameter [] { parameter }) { } + public CSParameterList(CSParameter parameter) : this(new CSParameter[] { parameter }) { } - public CSParameterList And (CSParameter parameter) - { - Add (Exceptions.ThrowOnNull (parameter, nameof(parameter))); - return this; - } + public CSParameterList And(CSParameter parameter) + { + Add(Exceptions.ThrowOnNull(parameter, nameof(parameter))); + return this; + } - public CSParameterList And (string type, string identifier, - CSParameterKind parameterKind = CSParameterKind.None, - CSConstant defaultValue = null) - { - return And (new CSParameter (new CSSimpleType (Exceptions.ThrowOnNull (type, nameof(type))), - new CSIdentifier (Exceptions.ThrowOnNull (identifier, nameof(identifier))), parameterKind, defaultValue)); - } - } + public CSParameterList And(string type, string identifier, + CSParameterKind parameterKind = CSParameterKind.None, + CSConstant defaultValue = null) + { + return And(new CSParameter(new CSSimpleType(Exceptions.ThrowOnNull(type, nameof(type))), + new CSIdentifier(Exceptions.ThrowOnNull(identifier, nameof(identifier))), parameterKind, defaultValue)); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs index d9caf746e3df..c732cc0b1a54 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs @@ -3,45 +3,48 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSParenthesisExpression : CSBaseExpression { - public CSParenthesisExpression (ICSExpression within) - { - Within = Exceptions.ThrowOnNull (within, "within"); - } - - public ICSExpression Within { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ('(', true); - Within.WriteAll (writer); - writer.Write (')', true); - } - } - - public class CSCastExpression : CSBaseExpression, ICSLineable { - public CSCastExpression (string type, ICSExpression toCast) - : this (new CSSimpleType (type), toCast) - { - } - - public CSCastExpression (CSType type, ICSExpression toCast) - { - Type = Exceptions.ThrowOnNull (type, "type"); - ToCast = Exceptions.ThrowOnNull (toCast, "toCast"); - } - - public CSType Type { get; private set; } - public ICSExpression ToCast { get; private set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("(", true); - Type.WriteAll (writer); - writer.Write (')', true); - ToCast.WriteAll (writer); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSParenthesisExpression : CSBaseExpression + { + public CSParenthesisExpression(ICSExpression within) + { + Within = Exceptions.ThrowOnNull(within, "within"); + } + + public ICSExpression Within { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write('(', true); + Within.WriteAll(writer); + writer.Write(')', true); + } + } + + public class CSCastExpression : CSBaseExpression, ICSLineable + { + public CSCastExpression(string type, ICSExpression toCast) + : this(new CSSimpleType(type), toCast) + { + } + + public CSCastExpression(CSType type, ICSExpression toCast) + { + Type = Exceptions.ThrowOnNull(type, "type"); + ToCast = Exceptions.ThrowOnNull(toCast, "toCast"); + } + + public CSType Type { get; private set; } + public ICSExpression ToCast { get; private set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("(", true); + Type.WriteAll(writer); + writer.Write(')', true); + ToCast.WriteAll(writer); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs index c1d9e0fd5539..47620400afe8 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs @@ -7,184 +7,195 @@ using System.Linq; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSProperty : CodeElementCollection { - public CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, - CSVisibility getVis, IEnumerable getter, - CSVisibility setVis, IEnumerable setter) - : this (type, kind, name, - getVis, getter != null ? new CSCodeBlock (getter) : null, - setVis, setter != null ? new CSCodeBlock (setter) : null) - { - } - - - public CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, - CSVisibility getVis, CSCodeBlock getter, - CSVisibility setVis, CSCodeBlock setter) - : this (type, kind, name, getVis, getter, setVis, setter, null) - { - } - - public CSProperty (CSType type, CSMethodKind kind, - CSVisibility getVis, CSCodeBlock getter, - CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) - : this (type, kind, new CSIdentifier ("this"), getVis, getter, setVis, setter, - Exceptions.ThrowOnNull (parms, nameof (parms))) - { - } - - CSProperty (CSType type, CSMethodKind kind, CSIdentifier name, - CSVisibility getVis, CSCodeBlock getter, - CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) - { - bool unifiedVis = getVis == setVis; - IndexerParameters = parms; - - LineCodeElementCollection decl = new LineCodeElementCollection (null, false, true); - - GetterVisibility = getVis; - SetterVisibility = setVis; - CSVisibility bestVis = (CSVisibility)Math.Min ((int)getVis, (int)setVis); - decl.And (new SimpleElement (CSMethod.VisibilityToString (bestVis))).And (SimpleElement.Spacer); - if (kind != CSMethodKind.None) - decl.And (new SimpleElement (CSMethod.MethodKindToString (kind))).And (SimpleElement.Spacer); - - PropType = type; - Name = name; - - decl.And (Exceptions.ThrowOnNull (type, "type")).And (SimpleElement.Spacer) - .And (Exceptions.ThrowOnNull (name, nameof (name))); - if (parms != null) { - decl.And (new SimpleElement ("[", true)).And (parms).And (new SimpleElement ("]")); - } - Add (decl); - - - CSCodeBlock cb = new CSCodeBlock (null); - - if (getter != null) { - Getter = getter; - LineCodeElementCollection getLine = MakeEtter (getVis, "get", unifiedVis, getVis > setVis); - cb.Add (getLine); - if (getter.Count () == 0) { - getLine.Add (new SimpleElement (";")); - } else { - cb.Add (getter); - } - } - if (setter != null) { - Setter = setter; - LineCodeElementCollection setLine = MakeEtter (setVis, "set", unifiedVis, setVis > getVis); - cb.Add (setLine); - if (setter.Count () == 0) { - setLine.Add (new SimpleElement (";")); - } else { - cb.Add (setter); - } - } - - Add (cb); - } - public CSType PropType { get; private set; } - public CSIdentifier Name { get; private set; } - public CSParameterList IndexerParameters { get; private set; } - public CSVisibility GetterVisibility { get; private set; } - public CSVisibility SetterVisibility { get; private set; } - - public CSCodeBlock Getter { get; private set; } - - public CSCodeBlock Setter { get; private set; } - - static LineCodeElementCollection MakeEtter (CSVisibility vis, string getset, - bool unifiedVis, bool moreRestrictiveVis) - { - LineCodeElementCollection getLine = new LineCodeElementCollection (null, false, true); - if (!unifiedVis && vis != CSVisibility.None && moreRestrictiveVis) - getLine.And (new SimpleElement (CSMethod.VisibilityToString (vis))).And (SimpleElement.Spacer); - return getLine.And (new SimpleElement (getset, false)); - } - - public static CSProperty PublicGetSet (CSType type, string name) - { - return new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), - CSVisibility.Public, new CSCodeBlock (), CSVisibility.Public, new CSCodeBlock ()); - } - - public static CSProperty PublicGetPrivateSet (CSType type, string name) - { - return new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), - CSVisibility.Public, new CSCodeBlock (), CSVisibility.Private, new CSCodeBlock ()); - } - - static CSProperty PublicGetPubPrivSetBacking (CSType type, string name, bool declareField, bool setIsPublic, string backingFieldName = null) - { - if (!declareField && backingFieldName == null) - throw new ArgumentException ("declareField must be true if there is no supplied field name", nameof (declareField)); - backingFieldName = backingFieldName ?? MassageName (Exceptions.ThrowOnNull (name, nameof (name))); - - - CSIdentifier backingIdent = new CSIdentifier (backingFieldName); - LineCodeElementCollection getCode = - new LineCodeElementCollection (new ICodeElement [] { CSReturn.ReturnLine (backingIdent) }, false, true); - LineCodeElementCollection setCode = - new LineCodeElementCollection ( - new ICodeElement [] { - CSAssignment.Assign (backingFieldName, new CSIdentifier ("value")) - }, false, true); - CSProperty prop = new CSProperty (type, CSMethodKind.None, new CSIdentifier (name), CSVisibility.Public, - new CSCodeBlock (getCode), - (setIsPublic ? CSVisibility.Public : CSVisibility.Private), new CSCodeBlock (setCode)); - if (declareField) - prop.Insert (0, CSFieldDeclaration.FieldLine (type, backingFieldName)); - return prop; - } - - - public static CSProperty PublicGetSetBacking (CSType type, string name, bool declareField, string backingFieldName = null) - { - return PublicGetPubPrivSetBacking (type, name, true, declareField, backingFieldName); - } - - public static CSProperty PublicGetPrivateSetBacking (CSType type, string name, bool declareField, string backingFieldName = null) - { - return PublicGetPubPrivSetBacking (type, name, false, declareField, backingFieldName); - } - - public static CSProperty PublicGetBacking (CSType type, CSIdentifier name, CSIdentifier backingFieldName, - bool includeBackingFieldDeclaration = false, CSMethodKind methodKind = CSMethodKind.None) - { - LineCodeElementCollection getCode = - new LineCodeElementCollection ( - new ICodeElement [] { - CSReturn.ReturnLine (Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))) - }, false, true); - CSProperty prop = new CSProperty (type, methodKind, Exceptions.ThrowOnNull (name, nameof (name)), - CSVisibility.Public, new CSCodeBlock (getCode), - CSVisibility.Public, null); - if (includeBackingFieldDeclaration) - prop.Insert (0, CSFieldDeclaration.FieldLine (type, backingFieldName)); - return prop; - } - - - public static CSProperty PublicGetBacking (CSType type, string name, string backingFieldName, bool includeBackingFieldDeclaration = false) - { - return PublicGetBacking (type, - new CSIdentifier (Exceptions.ThrowOnNull (name, nameof (name))), - new CSIdentifier (Exceptions.ThrowOnNull (backingFieldName, nameof (backingFieldName))), - includeBackingFieldDeclaration); - } - - static string MassageName (string name) - { - StringBuilder sb = new StringBuilder (); - sb.Append ("_"); - sb.Append (Char.ToLowerInvariant (name [0])); - if (name.Length > 0) - sb.Append (name.Substring (1)); - return sb.ToString (); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSProperty : CodeElementCollection + { + public CSProperty(CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, IEnumerable getter, + CSVisibility setVis, IEnumerable setter) + : this(type, kind, name, + getVis, getter != null ? new CSCodeBlock(getter) : null, + setVis, setter != null ? new CSCodeBlock(setter) : null) + { + } + + + public CSProperty(CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter) + : this(type, kind, name, getVis, getter, setVis, setter, null) + { + } + + public CSProperty(CSType type, CSMethodKind kind, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) + : this(type, kind, new CSIdentifier("this"), getVis, getter, setVis, setter, + Exceptions.ThrowOnNull(parms, nameof(parms))) + { + } + + CSProperty(CSType type, CSMethodKind kind, CSIdentifier name, + CSVisibility getVis, CSCodeBlock getter, + CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) + { + bool unifiedVis = getVis == setVis; + IndexerParameters = parms; + + LineCodeElementCollection decl = new LineCodeElementCollection(null, false, true); + + GetterVisibility = getVis; + SetterVisibility = setVis; + CSVisibility bestVis = (CSVisibility)Math.Min((int)getVis, (int)setVis); + decl.And(new SimpleElement(CSMethod.VisibilityToString(bestVis))).And(SimpleElement.Spacer); + if (kind != CSMethodKind.None) + decl.And(new SimpleElement(CSMethod.MethodKindToString(kind))).And(SimpleElement.Spacer); + + PropType = type; + Name = name; + + decl.And(Exceptions.ThrowOnNull(type, "type")).And(SimpleElement.Spacer) + .And(Exceptions.ThrowOnNull(name, nameof(name))); + if (parms != null) + { + decl.And(new SimpleElement("[", true)).And(parms).And(new SimpleElement("]")); + } + Add(decl); + + + CSCodeBlock cb = new CSCodeBlock(null); + + if (getter != null) + { + Getter = getter; + LineCodeElementCollection getLine = MakeEtter(getVis, "get", unifiedVis, getVis > setVis); + cb.Add(getLine); + if (getter.Count() == 0) + { + getLine.Add(new SimpleElement(";")); + } + else + { + cb.Add(getter); + } + } + if (setter != null) + { + Setter = setter; + LineCodeElementCollection setLine = MakeEtter(setVis, "set", unifiedVis, setVis > getVis); + cb.Add(setLine); + if (setter.Count() == 0) + { + setLine.Add(new SimpleElement(";")); + } + else + { + cb.Add(setter); + } + } + + Add(cb); + } + public CSType PropType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSParameterList IndexerParameters { get; private set; } + public CSVisibility GetterVisibility { get; private set; } + public CSVisibility SetterVisibility { get; private set; } + + public CSCodeBlock Getter { get; private set; } + + public CSCodeBlock Setter { get; private set; } + + static LineCodeElementCollection MakeEtter(CSVisibility vis, string getset, + bool unifiedVis, bool moreRestrictiveVis) + { + LineCodeElementCollection getLine = new LineCodeElementCollection(null, false, true); + if (!unifiedVis && vis != CSVisibility.None && moreRestrictiveVis) + getLine.And(new SimpleElement(CSMethod.VisibilityToString(vis))).And(SimpleElement.Spacer); + return getLine.And(new SimpleElement(getset, false)); + } + + public static CSProperty PublicGetSet(CSType type, string name) + { + return new CSProperty(type, CSMethodKind.None, new CSIdentifier(name), + CSVisibility.Public, new CSCodeBlock(), CSVisibility.Public, new CSCodeBlock()); + } + + public static CSProperty PublicGetPrivateSet(CSType type, string name) + { + return new CSProperty(type, CSMethodKind.None, new CSIdentifier(name), + CSVisibility.Public, new CSCodeBlock(), CSVisibility.Private, new CSCodeBlock()); + } + + static CSProperty PublicGetPubPrivSetBacking(CSType type, string name, bool declareField, bool setIsPublic, string backingFieldName = null) + { + if (!declareField && backingFieldName == null) + throw new ArgumentException("declareField must be true if there is no supplied field name", nameof(declareField)); + backingFieldName = backingFieldName ?? MassageName(Exceptions.ThrowOnNull(name, nameof(name))); + + + CSIdentifier backingIdent = new CSIdentifier(backingFieldName); + LineCodeElementCollection getCode = + new LineCodeElementCollection(new ICodeElement[] { CSReturn.ReturnLine(backingIdent) }, false, true); + LineCodeElementCollection setCode = + new LineCodeElementCollection( + new ICodeElement[] { + CSAssignment.Assign (backingFieldName, new CSIdentifier ("value")) + }, false, true); + CSProperty prop = new CSProperty(type, CSMethodKind.None, new CSIdentifier(name), CSVisibility.Public, + new CSCodeBlock(getCode), + (setIsPublic ? CSVisibility.Public : CSVisibility.Private), new CSCodeBlock(setCode)); + if (declareField) + prop.Insert(0, CSFieldDeclaration.FieldLine(type, backingFieldName)); + return prop; + } + + + public static CSProperty PublicGetSetBacking(CSType type, string name, bool declareField, string backingFieldName = null) + { + return PublicGetPubPrivSetBacking(type, name, true, declareField, backingFieldName); + } + + public static CSProperty PublicGetPrivateSetBacking(CSType type, string name, bool declareField, string backingFieldName = null) + { + return PublicGetPubPrivSetBacking(type, name, false, declareField, backingFieldName); + } + + public static CSProperty PublicGetBacking(CSType type, CSIdentifier name, CSIdentifier backingFieldName, + bool includeBackingFieldDeclaration = false, CSMethodKind methodKind = CSMethodKind.None) + { + LineCodeElementCollection getCode = + new LineCodeElementCollection( + new ICodeElement[] { + CSReturn.ReturnLine (Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))) + }, false, true); + CSProperty prop = new CSProperty(type, methodKind, Exceptions.ThrowOnNull(name, nameof(name)), + CSVisibility.Public, new CSCodeBlock(getCode), + CSVisibility.Public, null); + if (includeBackingFieldDeclaration) + prop.Insert(0, CSFieldDeclaration.FieldLine(type, backingFieldName)); + return prop; + } + + + public static CSProperty PublicGetBacking(CSType type, string name, string backingFieldName, bool includeBackingFieldDeclaration = false) + { + return PublicGetBacking(type, + new CSIdentifier(Exceptions.ThrowOnNull(name, nameof(name))), + new CSIdentifier(Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))), + includeBackingFieldDeclaration); + } + + static string MassageName(string name) + { + StringBuilder sb = new StringBuilder(); + sb.Append("_"); + sb.Append(Char.ToLowerInvariant(name[0])); + if (name.Length > 0) + sb.Append(name.Substring(1)); + return sb.ToString(); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs index 514546f580da..2bf81720aab2 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs @@ -1,26 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SyntaxDynamo.CSLang { - public class CSReturn : DelegatedSimpleElement, ICSExpression, ICSLineable { - public CSReturn (ICSExpression expr) - { - Value = expr; - } +namespace SyntaxDynamo.CSLang +{ + public class CSReturn : DelegatedSimpleElement, ICSExpression, ICSLineable + { + public CSReturn(ICSExpression expr) + { + Value = expr; + } - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("return ", true); - if (Value != null) - Value.WriteAll (writer); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("return ", true); + if (Value != null) + Value.WriteAll(writer); + } - public ICSExpression Value { get; private set; } + public ICSExpression Value { get; private set; } - public static CSLine ReturnLine (ICSExpression expr) - { - return new CSLine (new CSReturn (expr)); - } - } + public static CSLine ReturnLine(ICSExpression expr) + { + return new CSLine(new CSReturn(expr)); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs index ee756b4e8401..a5b80fd321d7 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs @@ -1,32 +1,34 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSShortCircuit : DelegatedSimpleElement, ICSLineable { - public CSShortCircuit (CSShortCircuitKind kind) - { - Kind = kind; - } +namespace SyntaxDynamo.CSLang +{ + public class CSShortCircuit : DelegatedSimpleElement, ICSLineable + { + public CSShortCircuit(CSShortCircuitKind kind) + { + Kind = kind; + } - public CSShortCircuitKind Kind { get; private set; } + public CSShortCircuitKind Kind { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { - var keyword = Kind == CSShortCircuitKind.Break ? "break" : "continue"; - writer.Write (keyword, false); - } + protected override void LLWrite(ICodeWriter writer, object o) + { + var keyword = Kind == CSShortCircuitKind.Break ? "break" : "continue"; + writer.Write(keyword, false); + } - public static CSLine ShortCircuit (CSShortCircuitKind kind) - { - return new CSLine (new CSShortCircuit (kind)); - } + public static CSLine ShortCircuit(CSShortCircuitKind kind) + { + return new CSLine(new CSShortCircuit(kind)); + } - public static CSLine Continue () - { - return ShortCircuit (CSShortCircuitKind.Continue); - } + public static CSLine Continue() + { + return ShortCircuit(CSShortCircuitKind.Continue); + } - public static CSLine Break () - { - return ShortCircuit (CSShortCircuitKind.Break); - } - } + public static CSLine Break() + { + return ShortCircuit(CSShortCircuitKind.Break); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs index 67f3a406b9c6..cf4fb47dc11c 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs @@ -3,38 +3,42 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSTernary : CSBaseExpression { - public CSTernary (CSBaseExpression predicate, CSBaseExpression onTrue, CSBaseExpression onFalse, bool addParentheses) - { - Predicate = Exceptions.ThrowOnNull (predicate, "predicate"); - OnTrue = Exceptions.ThrowOnNull (onTrue, "onTrue"); - OnFalse = Exceptions.ThrowOnNull (onFalse, "onFalse"); - AddParentheses = addParentheses; - } - public CSBaseExpression Predicate { get; private set; } - public CSBaseExpression OnTrue { get; private set; } - public CSBaseExpression OnFalse { get; private set; } - public bool AddParentheses { get; set; } +namespace SyntaxDynamo.CSLang +{ + public class CSTernary : CSBaseExpression + { + public CSTernary(CSBaseExpression predicate, CSBaseExpression onTrue, CSBaseExpression onFalse, bool addParentheses) + { + Predicate = Exceptions.ThrowOnNull(predicate, "predicate"); + OnTrue = Exceptions.ThrowOnNull(onTrue, "onTrue"); + OnFalse = Exceptions.ThrowOnNull(onFalse, "onFalse"); + AddParentheses = addParentheses; + } + public CSBaseExpression Predicate { get; private set; } + public CSBaseExpression OnTrue { get; private set; } + public CSBaseExpression OnFalse { get; private set; } + public bool AddParentheses { get; set; } - #region implemented abstract members of DelegatedSimpleElem + #region implemented abstract members of DelegatedSimpleElem - protected override void LLWrite (ICodeWriter writer, object o) - { - if (AddParentheses) { - writer.Write ('(', true); - } - Predicate.WriteAll (writer); - writer.Write (" ? ", true); - OnTrue.WriteAll (writer); - writer.Write (" : ", true); - OnFalse.WriteAll (writer); - if (AddParentheses) { - writer.Write (')', true); - } - } + protected override void LLWrite(ICodeWriter writer, object o) + { + if (AddParentheses) + { + writer.Write('(', true); + } + Predicate.WriteAll(writer); + writer.Write(" ? ", true); + OnTrue.WriteAll(writer); + writer.Write(" : ", true); + OnFalse.WriteAll(writer); + if (AddParentheses) + { + writer.Write(')', true); + } + } - #endregion - } + #endregion + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs index 0021aa15d4a9..91a880271cc8 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs @@ -3,44 +3,46 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSThrow : CSBaseExpression, ICSStatement, ICSLineable { - public CSThrow (CSBaseExpression expr) - { - Expr = Exceptions.ThrowOnNull (expr, "expr"); - } - - public CSBaseExpression Expr { get; private set; } - - #region implemented abstract members of DelegatedSimpleElem - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write ("throw ", true); - Expr.WriteAll (writer); - } - - #endregion - - public static CSLine ThrowLine (T exType, CommaListElementCollection args) where T : Exception - { - return new CSLine (new CSThrow (new CSFunctionCall (new CSIdentifier (exType.GetType ().Name), args, true))); - } - - public static CSLine ThrowLine (T exType, string message) where T : Exception - { - CommaListElementCollection args = new CommaListElementCollection (); - if (message != null) - args.Add (CSConstant.Val (message)); - return ThrowLine (exType, args); - } - - public static CSLine ThrowLine(T exType, CSBaseExpression expr) where T : Exception - { - CommaListElementCollection args = new CommaListElementCollection (); - args.Add (Exceptions.ThrowOnNull (expr, nameof (expr))); - return ThrowLine (exType, args); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSThrow : CSBaseExpression, ICSStatement, ICSLineable + { + public CSThrow(CSBaseExpression expr) + { + Expr = Exceptions.ThrowOnNull(expr, "expr"); + } + + public CSBaseExpression Expr { get; private set; } + + #region implemented abstract members of DelegatedSimpleElem + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write("throw ", true); + Expr.WriteAll(writer); + } + + #endregion + + public static CSLine ThrowLine(T exType, CommaListElementCollection args) where T : Exception + { + return new CSLine(new CSThrow(new CSFunctionCall(new CSIdentifier(exType.GetType().Name), args, true))); + } + + public static CSLine ThrowLine(T exType, string message) where T : Exception + { + CommaListElementCollection args = new CommaListElementCollection(); + if (message != null) + args.Add(CSConstant.Val(message)); + return ThrowLine(exType, args); + } + + public static CSLine ThrowLine(T exType, CSBaseExpression expr) where T : Exception + { + CommaListElementCollection args = new CommaListElementCollection(); + args.Add(Exceptions.ThrowOnNull(expr, nameof(expr))); + return ThrowLine(exType, args); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs index dae057dbc005..1b4329f853d6 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs @@ -2,77 +2,82 @@ // Licensed under the MIT License. using System; -namespace SyntaxDynamo.CSLang { - public class CSCatch : DelegatedSimpleElement, ICSStatement { - public CSCatch (CSType catchType, CSIdentifier name, CSCodeBlock body) - { - CatchType = catchType; - Name = name; - Body = body ?? new CSCodeBlock (); - } +namespace SyntaxDynamo.CSLang +{ + public class CSCatch : DelegatedSimpleElement, ICSStatement + { + public CSCatch(CSType catchType, CSIdentifier name, CSCodeBlock body) + { + CatchType = catchType; + Name = name; + Body = body ?? new CSCodeBlock(); + } - public CSCatch (string catchType, string name, CSCodeBlock body) - : this (new CSSimpleType (catchType), name != null ? new CSIdentifier (name) : null, body) - { - } + public CSCatch(string catchType, string name, CSCodeBlock body) + : this(new CSSimpleType(catchType), name != null ? new CSIdentifier(name) : null, body) + { + } - public CSCatch (Type catchType, string name, CSCodeBlock body) - : this (new CSSimpleType (catchType), name != null ? new CSIdentifier (name) : null, body) - { - } + public CSCatch(Type catchType, string name, CSCodeBlock body) + : this(new CSSimpleType(catchType), name != null ? new CSIdentifier(name) : null, body) + { + } - public CSCatch (CSCodeBlock body) - : this ((CSType)null, null, body) - { - } + public CSCatch(CSCodeBlock body) + : this((CSType)null, null, body) + { + } - public CSType CatchType { get; private set; } - public CSIdentifier Name { get; private set; } - public CSCodeBlock Body { get; private set; } - protected override void LLWrite (ICodeWriter writer, object o) - { + public CSType CatchType { get; private set; } + public CSIdentifier Name { get; private set; } + public CSCodeBlock Body { get; private set; } + protected override void LLWrite(ICodeWriter writer, object o) + { - writer.BeginNewLine (true); - writer.Write ("catch ", false); - if ((object)CatchType != null) { - writer.Write ("(", false); - CatchType.WriteAll (writer); - if ((object)Name != null) { - SimpleElement.Spacer.WriteAll (writer); - Name.WriteAll (writer); - } - writer.Write (")", false); - } - writer.EndLine (); - Body.WriteAll (writer); - writer.EndLine (); - } - } + writer.BeginNewLine(true); + writer.Write("catch ", false); + if ((object)CatchType != null) + { + writer.Write("(", false); + CatchType.WriteAll(writer); + if ((object)Name != null) + { + SimpleElement.Spacer.WriteAll(writer); + Name.WriteAll(writer); + } + writer.Write(")", false); + } + writer.EndLine(); + Body.WriteAll(writer); + writer.EndLine(); + } + } - public class CSTryCatch : CodeElementCollection, ICSStatement { - public CSTryCatch (CSCodeBlock tryBlock, params CSCatch [] catchBlocks) - { - TryBlock = tryBlock ?? new CSCodeBlock (); - CatchBlocks = new CodeElementCollection (); - CatchBlocks.AddRange (catchBlocks); + public class CSTryCatch : CodeElementCollection, ICSStatement + { + public CSTryCatch(CSCodeBlock tryBlock, params CSCatch[] catchBlocks) + { + TryBlock = tryBlock ?? new CSCodeBlock(); + CatchBlocks = new CodeElementCollection(); + CatchBlocks.AddRange(catchBlocks); - Add (new SimpleElement ("try ", true)); - Add (TryBlock); - Add (CatchBlocks); - } + Add(new SimpleElement("try ", true)); + Add(TryBlock); + Add(CatchBlocks); + } - public CSTryCatch (CSCodeBlock tryBlock, Type catchType, string name, CSCodeBlock catchBlock) - : this (tryBlock, new CSCatch (catchType, name, catchBlock)) - { - } + public CSTryCatch(CSCodeBlock tryBlock, Type catchType, string name, CSCodeBlock catchBlock) + : this(tryBlock, new CSCatch(catchType, name, catchBlock)) + { + } - public override void Write (ICodeWriter writer, object o) - { - writer.BeginNewLine (true); - base.Write (writer, o); - } + public override void Write(ICodeWriter writer, object o) + { + writer.BeginNewLine(true); + base.Write(writer, o); + } - public CSCodeBlock TryBlock { get; private set; } - public CodeElementCollection CatchBlocks { get; private set; } - } + public CSCodeBlock TryBlock { get; private set; } + public CodeElementCollection CatchBlocks { get; private set; } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs index 5708dbce1a13..92d226624160 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs @@ -8,249 +8,269 @@ using System.Linq; using System.Collections.Generic; -namespace SyntaxDynamo.CSLang { - public abstract class CSType : DelegatedSimpleElement { - public override string ToString () => CodeWriter.WriteToString (this); - - public abstract CSFunctionCall Typeof (); - public abstract CSFunctionCall Default (); - public abstract CSFunctionCall Ctor (); - - public static CSType Copy (CSType csType) - { - if (csType is CSSimpleType csSimpleType) { - return new CSSimpleType (csSimpleType); - } - if (csType is CSGenericReferenceType csGen) { - return new CSGenericReferenceType (csGen); - } - throw new NotImplementedException ($"Type {csType.GetType ().Name} needs a copy constructor"); - } - } - - public class CSSimpleType : CSType { - public CSSimpleType (Type t) - : this (t.Name) - { - } - public CSSimpleType (string name) - : this (name, false) - { - } - - public CSSimpleType (CSSimpleType csSimpleType) - : this (csSimpleType.Name, csSimpleType.IsArray) - { - if (csSimpleType.GenericTypes != null) { - GenericTypes = new CSType [csSimpleType.GenericTypes.Length]; - for (int i = 0; i < GenericTypes.Length; i++) { - GenericTypes [i] = CSType.Copy (csSimpleType.GenericTypes [i]); - } - } - } - - public CSSimpleType (string name, bool isArray) - { - hiddenName = Exceptions.ThrowOnNull (name, "name") + (isArray ? "[]" : ""); - } - - public static explicit operator CSSimpleType (string name) - { - return new CSSimpleType (name); - } - - public static CSSimpleType CreateArray (string name) - { - return new CSSimpleType (name, true); - } - - public CSSimpleType (string name, bool isArray, params CSType [] genericSpecialization) - { - IsGeneric = genericSpecialization != null && genericSpecialization.Length > 0; - GenericTypes = genericSpecialization; - GenericTypeName = Exceptions.ThrowOnNull (name, nameof (name)); - IsArray = isArray; - } - - public CSSimpleType (string name, bool isArray, params string [] genericSpecialization) - : this (name, isArray, genericSpecialization.Select (s => new CSSimpleType (s)).ToArray ()) - { - } - - string hiddenName; - public string Name { - get { - return hiddenName ?? GenerateName (); - } - } - public bool IsGeneric { get; private set; } - public string GenericTypeName { get; private set; } - public CSType [] GenericTypes { get; private set; } - public bool IsArray { get; private set; } - public bool IsPointer { get; private set; } - - string GenerateName () - { - StringBuilder sb = new StringBuilder (); - sb.Append (GenericTypeName); - if (GenericTypes != null && GenericTypes.Length > 0) { - sb.Append ("<"); - int i = 0; - foreach (CSType type in GenericTypes) { - if (i > 0) - sb.Append (", "); - sb.Append (type.ToString ()); - i++; - } - sb.Append (">"); - } - if (IsArray) - sb.Append ("[]"); - return sb.ToString (); - } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Name, false); - } - - public override CSFunctionCall Typeof () - { - return new CSFunctionCall ("typeof", false, new CSIdentifier (Name)); - } - - public override CSFunctionCall Default () - { - return new CSFunctionCall ("default", false, new CSIdentifier (Name)); - } - - public override CSFunctionCall Ctor () - { - return new CSFunctionCall (Name, true); - } - - static CSSimpleType - tBool = new CSSimpleType ("bool"), - tChar = new CSSimpleType ("char"), - tSbyte = new CSSimpleType ("sbyte"), - tShort = new CSSimpleType ("short"), - tInt = new CSSimpleType ("int"), - tLong = new CSSimpleType ("long"), - tFloat = new CSSimpleType ("float"), - tByte = new CSSimpleType ("byte"), - tUshort = new CSSimpleType ("ushort"), - tUint = new CSSimpleType ("uint"), - tUlong = new CSSimpleType ("ulong"), - tDouble = new CSSimpleType ("double"), - tString = new CSSimpleType ("string"), - tObject = new CSSimpleType ("object"), - tIntPtr = new CSSimpleType ("IntPtr"), - tVoid = new CSSimpleType ("void"), - tByteStar = new CSSimpleType ("byte").Star, - tType = new CSSimpleType ("Type"), - tVar = new CSSimpleType ("var"), - tNfloat = new CSSimpleType ("nfloat"), - tNint = new CSSimpleType ("nint"), - tNUint = new CSSimpleType ("nuint") - ; - - public CSSimpleType Star { - get { - if (Name.EndsWith ("[]")) { - throw new NotImplementedException ("Blindly making an array a pointer doesn't do what you think."); - } else { - var ptrType = new CSSimpleType (Name + " *", false); - ptrType.IsPointer = true; - return ptrType; - } - } - } - - public static CSSimpleType Bool { get { return tBool; } } - public static CSSimpleType Char { get { return tChar; } } - public static CSSimpleType SByte { get { return tSbyte; } } - public static CSSimpleType Short { get { return tShort; } } - public static CSSimpleType Int { get { return tInt; } } - public static CSSimpleType Long { get { return tLong; } } - public static CSSimpleType Float { get { return tFloat; } } - public static CSSimpleType Byte { get { return tByte; } } - public static CSSimpleType UShort { get { return tUshort; } } - public static CSSimpleType UInt { get { return tUint; } } - public static CSSimpleType ULong { get { return tUlong; } } - public static CSSimpleType Double { get { return tDouble; } } - public static CSSimpleType String { get { return tString; } } - public static CSSimpleType Object { get { return tObject; } } - public static CSSimpleType IntPtr { get { return tIntPtr; } } - public static CSSimpleType Void { get { return tVoid; } } - public static CSSimpleType ByteStar { get { return tByteStar; } } - public static CSSimpleType Type { get { return tType; } } - public static CSSimpleType Var { get { return tVar; } } - public static CSSimpleType NFloat { get { return tNfloat; } } - public static CSSimpleType NInt => tNint; - public static CSSimpleType NUInt => tNUint; - } - - public class CSGenericReferenceType : CSType { - public CSGenericReferenceType (int depth, int index) - { - Depth = depth; - Index = index; - InterfaceConstraints = new List (); - } - - public CSGenericReferenceType (CSGenericReferenceType csGeneric) - : this (csGeneric.Depth, csGeneric.Index) - { - foreach (var elem in csGeneric.InterfaceConstraints) { - InterfaceConstraints.Add (CSType.Copy (elem)); - } - ReferenceNamer = csGeneric.ReferenceNamer; - } - - // this doesn't really belong here, but I'm going to need it. - public List InterfaceConstraints { get; private set; } - - public int Depth { get; private set; } - public int Index { get; private set; } - public Func ReferenceNamer { get; set; } - - protected override void LLWrite (ICodeWriter writer, object o) - { - writer.Write (Name, true); - } - - public string Name { - get { - Func namer = ReferenceNamer ?? DefaultNamer; - return namer (Depth, Index); - } - } - - const string kNames = "TUVWABCDEFGHIJKLMN"; - - public static string DefaultNamer (int depth, int index) - { - if (depth < 0 || depth >= kNames.Length) - throw new ArgumentOutOfRangeException (nameof (depth)); - if (index < 0) - throw new ArgumentOutOfRangeException (nameof (index)); - return String.Format ("{0}{1}", kNames [depth], index); - } - - public override CSFunctionCall Typeof () - { - return new CSFunctionCall ("typeof", false, new CSIdentifier (Name)); - } - - public override CSFunctionCall Default () - { - return new CSFunctionCall ("default", false, new CSIdentifier (Name)); - } - - public override CSFunctionCall Ctor () - { - return new CSFunctionCall (Name, true); - } - } +namespace SyntaxDynamo.CSLang +{ + public abstract class CSType : DelegatedSimpleElement + { + public override string ToString() => CodeWriter.WriteToString(this); + + public abstract CSFunctionCall Typeof(); + public abstract CSFunctionCall Default(); + public abstract CSFunctionCall Ctor(); + + public static CSType Copy(CSType csType) + { + if (csType is CSSimpleType csSimpleType) + { + return new CSSimpleType(csSimpleType); + } + if (csType is CSGenericReferenceType csGen) + { + return new CSGenericReferenceType(csGen); + } + throw new NotImplementedException($"Type {csType.GetType().Name} needs a copy constructor"); + } + } + + public class CSSimpleType : CSType + { + public CSSimpleType(Type t) + : this(t.Name) + { + } + public CSSimpleType(string name) + : this(name, false) + { + } + + public CSSimpleType(CSSimpleType csSimpleType) + : this(csSimpleType.Name, csSimpleType.IsArray) + { + if (csSimpleType.GenericTypes != null) + { + GenericTypes = new CSType[csSimpleType.GenericTypes.Length]; + for (int i = 0; i < GenericTypes.Length; i++) + { + GenericTypes[i] = CSType.Copy(csSimpleType.GenericTypes[i]); + } + } + } + + public CSSimpleType(string name, bool isArray) + { + hiddenName = Exceptions.ThrowOnNull(name, "name") + (isArray ? "[]" : ""); + } + + public static explicit operator CSSimpleType(string name) + { + return new CSSimpleType(name); + } + + public static CSSimpleType CreateArray(string name) + { + return new CSSimpleType(name, true); + } + + public CSSimpleType(string name, bool isArray, params CSType[] genericSpecialization) + { + IsGeneric = genericSpecialization != null && genericSpecialization.Length > 0; + GenericTypes = genericSpecialization; + GenericTypeName = Exceptions.ThrowOnNull(name, nameof(name)); + IsArray = isArray; + } + + public CSSimpleType(string name, bool isArray, params string[] genericSpecialization) + : this(name, isArray, genericSpecialization.Select(s => new CSSimpleType(s)).ToArray()) + { + } + + string hiddenName; + public string Name + { + get + { + return hiddenName ?? GenerateName(); + } + } + public bool IsGeneric { get; private set; } + public string GenericTypeName { get; private set; } + public CSType[] GenericTypes { get; private set; } + public bool IsArray { get; private set; } + public bool IsPointer { get; private set; } + + string GenerateName() + { + StringBuilder sb = new StringBuilder(); + sb.Append(GenericTypeName); + if (GenericTypes != null && GenericTypes.Length > 0) + { + sb.Append("<"); + int i = 0; + foreach (CSType type in GenericTypes) + { + if (i > 0) + sb.Append(", "); + sb.Append(type.ToString()); + i++; + } + sb.Append(">"); + } + if (IsArray) + sb.Append("[]"); + return sb.ToString(); + } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write(Name, false); + } + + public override CSFunctionCall Typeof() + { + return new CSFunctionCall("typeof", false, new CSIdentifier(Name)); + } + + public override CSFunctionCall Default() + { + return new CSFunctionCall("default", false, new CSIdentifier(Name)); + } + + public override CSFunctionCall Ctor() + { + return new CSFunctionCall(Name, true); + } + + static CSSimpleType + tBool = new CSSimpleType("bool"), + tChar = new CSSimpleType("char"), + tSbyte = new CSSimpleType("sbyte"), + tShort = new CSSimpleType("short"), + tInt = new CSSimpleType("int"), + tLong = new CSSimpleType("long"), + tFloat = new CSSimpleType("float"), + tByte = new CSSimpleType("byte"), + tUshort = new CSSimpleType("ushort"), + tUint = new CSSimpleType("uint"), + tUlong = new CSSimpleType("ulong"), + tDouble = new CSSimpleType("double"), + tString = new CSSimpleType("string"), + tObject = new CSSimpleType("object"), + tIntPtr = new CSSimpleType("IntPtr"), + tVoid = new CSSimpleType("void"), + tByteStar = new CSSimpleType("byte").Star, + tType = new CSSimpleType("Type"), + tVar = new CSSimpleType("var"), + tNfloat = new CSSimpleType("nfloat"), + tNint = new CSSimpleType("nint"), + tNUint = new CSSimpleType("nuint") + ; + + public CSSimpleType Star + { + get + { + if (Name.EndsWith("[]")) + { + throw new NotImplementedException("Blindly making an array a pointer doesn't do what you think."); + } + else + { + var ptrType = new CSSimpleType(Name + " *", false); + ptrType.IsPointer = true; + return ptrType; + } + } + } + + public static CSSimpleType Bool { get { return tBool; } } + public static CSSimpleType Char { get { return tChar; } } + public static CSSimpleType SByte { get { return tSbyte; } } + public static CSSimpleType Short { get { return tShort; } } + public static CSSimpleType Int { get { return tInt; } } + public static CSSimpleType Long { get { return tLong; } } + public static CSSimpleType Float { get { return tFloat; } } + public static CSSimpleType Byte { get { return tByte; } } + public static CSSimpleType UShort { get { return tUshort; } } + public static CSSimpleType UInt { get { return tUint; } } + public static CSSimpleType ULong { get { return tUlong; } } + public static CSSimpleType Double { get { return tDouble; } } + public static CSSimpleType String { get { return tString; } } + public static CSSimpleType Object { get { return tObject; } } + public static CSSimpleType IntPtr { get { return tIntPtr; } } + public static CSSimpleType Void { get { return tVoid; } } + public static CSSimpleType ByteStar { get { return tByteStar; } } + public static CSSimpleType Type { get { return tType; } } + public static CSSimpleType Var { get { return tVar; } } + public static CSSimpleType NFloat { get { return tNfloat; } } + public static CSSimpleType NInt => tNint; + public static CSSimpleType NUInt => tNUint; + } + + public class CSGenericReferenceType : CSType + { + public CSGenericReferenceType(int depth, int index) + { + Depth = depth; + Index = index; + InterfaceConstraints = new List(); + } + + public CSGenericReferenceType(CSGenericReferenceType csGeneric) + : this(csGeneric.Depth, csGeneric.Index) + { + foreach (var elem in csGeneric.InterfaceConstraints) + { + InterfaceConstraints.Add(CSType.Copy(elem)); + } + ReferenceNamer = csGeneric.ReferenceNamer; + } + + // this doesn't really belong here, but I'm going to need it. + public List InterfaceConstraints { get; private set; } + + public int Depth { get; private set; } + public int Index { get; private set; } + public Func ReferenceNamer { get; set; } + + protected override void LLWrite(ICodeWriter writer, object o) + { + writer.Write(Name, true); + } + + public string Name + { + get + { + Func namer = ReferenceNamer ?? DefaultNamer; + return namer(Depth, Index); + } + } + + const string kNames = "TUVWABCDEFGHIJKLMN"; + + public static string DefaultNamer(int depth, int index) + { + if (depth < 0 || depth >= kNames.Length) + throw new ArgumentOutOfRangeException(nameof(depth)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + return String.Format("{0}{1}", kNames[depth], index); + } + + public override CSFunctionCall Typeof() + { + return new CSFunctionCall("typeof", false, new CSIdentifier(Name)); + } + + public override CSFunctionCall Default() + { + return new CSFunctionCall("default", false, new CSIdentifier(Name)); + } + + public override CSFunctionCall Ctor() + { + return new CSFunctionCall(Name, true); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs index 70305c76a982..a05e0e33a3a9 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs @@ -3,108 +3,114 @@ using System; -namespace SyntaxDynamo.CSLang { - public class CSUnaryExpression : CSBaseExpression { - public CSUnaryExpression (CSUnaryOperator op, ICSExpression expr) - { - Operation = op; - Expr = Exceptions.ThrowOnNull (expr, nameof(expr)); - } - protected override void LLWrite (ICodeWriter writer, object o) - { - if (IsPostfix (Operation)) { - Expr.WriteAll (writer); - writer.Write (OperatorToString (Operation), true); - } else { - writer.Write (OperatorToString (Operation), true); - Expr.WriteAll (writer); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSUnaryExpression : CSBaseExpression + { + public CSUnaryExpression(CSUnaryOperator op, ICSExpression expr) + { + Operation = op; + Expr = Exceptions.ThrowOnNull(expr, nameof(expr)); + } + protected override void LLWrite(ICodeWriter writer, object o) + { + if (IsPostfix(Operation)) + { + Expr.WriteAll(writer); + writer.Write(OperatorToString(Operation), true); + } + else + { + writer.Write(OperatorToString(Operation), true); + Expr.WriteAll(writer); + } + } - public CSUnaryOperator Operation { get; private set; } - public ICSExpression Expr { get; private set; } + public CSUnaryOperator Operation { get; private set; } + public ICSExpression Expr { get; private set; } - static string OperatorToString (CSUnaryOperator op) - { - switch (op) { - case CSUnaryOperator.At: - return "@"; - case CSUnaryOperator.BitNot: - return "~"; - case CSUnaryOperator.Neg: - return "-"; - case CSUnaryOperator.Not: - return "!"; - case CSUnaryOperator.Out: - return "out "; - case CSUnaryOperator.Pos: - return "+"; - case CSUnaryOperator.Ref: - return "ref "; - case CSUnaryOperator.AddressOf: - return "&"; - case CSUnaryOperator.Indirection: - return "*"; - case CSUnaryOperator.Await: - return "await "; - case CSUnaryOperator.PostBang: - return "!"; - case CSUnaryOperator.Question: - return "?"; - default: - throw new ArgumentOutOfRangeException (nameof(op)); - } - } + static string OperatorToString(CSUnaryOperator op) + { + switch (op) + { + case CSUnaryOperator.At: + return "@"; + case CSUnaryOperator.BitNot: + return "~"; + case CSUnaryOperator.Neg: + return "-"; + case CSUnaryOperator.Not: + return "!"; + case CSUnaryOperator.Out: + return "out "; + case CSUnaryOperator.Pos: + return "+"; + case CSUnaryOperator.Ref: + return "ref "; + case CSUnaryOperator.AddressOf: + return "&"; + case CSUnaryOperator.Indirection: + return "*"; + case CSUnaryOperator.Await: + return "await "; + case CSUnaryOperator.PostBang: + return "!"; + case CSUnaryOperator.Question: + return "?"; + default: + throw new ArgumentOutOfRangeException(nameof(op)); + } + } - static bool IsPostfix (CSUnaryOperator op) - { - return op == CSUnaryOperator.PostBang || op == CSUnaryOperator.Question; - } + static bool IsPostfix(CSUnaryOperator op) + { + return op == CSUnaryOperator.PostBang || op == CSUnaryOperator.Question; + } - public static CSUnaryExpression AddressOf (ICSExpression expr) - { - return new CSUnaryExpression (CSUnaryOperator.AddressOf, expr); - } + public static CSUnaryExpression AddressOf(ICSExpression expr) + { + return new CSUnaryExpression(CSUnaryOperator.AddressOf, expr); + } - public static CSUnaryExpression Star (ICSExpression expr) - { - return new CSUnaryExpression (CSUnaryOperator.Indirection, expr); - } + public static CSUnaryExpression Star(ICSExpression expr) + { + return new CSUnaryExpression(CSUnaryOperator.Indirection, expr); + } - public static CSUnaryExpression Out (CSIdentifier id) - { - return new CSUnaryExpression (CSUnaryOperator.Out, id); - } + public static CSUnaryExpression Out(CSIdentifier id) + { + return new CSUnaryExpression(CSUnaryOperator.Out, id); + } - public static CSUnaryExpression Out (string id) - { - return Out (new CSIdentifier (id)); - } + public static CSUnaryExpression Out(string id) + { + return Out(new CSIdentifier(id)); + } - public static CSUnaryExpression Ref (CSIdentifier id) - { - return new CSUnaryExpression (CSUnaryOperator.Ref, id); - } + public static CSUnaryExpression Ref(CSIdentifier id) + { + return new CSUnaryExpression(CSUnaryOperator.Ref, id); + } - public static CSUnaryExpression Ref (string id) - { - return Ref (new CSIdentifier (id)); - } + public static CSUnaryExpression Ref(string id) + { + return Ref(new CSIdentifier(id)); + } - public static CSUnaryExpression Await (ICSExpression expr) - { - return new CSUnaryExpression (CSUnaryOperator.Await, expr); - } + public static CSUnaryExpression Await(ICSExpression expr) + { + return new CSUnaryExpression(CSUnaryOperator.Await, expr); + } - public static CSUnaryExpression PostBang (ICSExpression expr) - { - return new CSUnaryExpression (CSUnaryOperator.PostBang, expr); - } + public static CSUnaryExpression PostBang(ICSExpression expr) + { + return new CSUnaryExpression(CSUnaryOperator.PostBang, expr); + } - public static CSUnaryExpression Question (ICSExpression expr) - { - return new CSUnaryExpression (CSUnaryOperator.Question, expr); - } - } + public static CSUnaryExpression Question(ICSExpression expr) + { + return new CSUnaryExpression(CSUnaryOperator.Question, expr); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs index ebe9966ad8dd..359f0d1fc6a9 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs @@ -6,55 +6,60 @@ using System.Collections.Generic; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public class CSUsing : SimpleLineElement { - public CSUsing (string package) - : base (string.Format ("using {0};", Exceptions.ThrowOnNull (package, nameof(package))), false, false, false) - { - Package = package; - } - - public string Package { get; private set; } - } - - public class CSUsingPackages : CodeElementCollection { - public CSUsingPackages () : base () { } - public CSUsingPackages (params CSUsing [] use) - : this () - { - AddRange (use); - } - public CSUsingPackages (params string [] use) - : this () - { - AddRange (use.Select (s => new CSUsing (s))); - } - - public CSUsingPackages And (CSUsing use) - { - Add (use); - return this; - } - - public CSUsingPackages And (string package) { return And (new CSUsing (package)); } - - public void AddIfNotPresent (string package, CSIdentifier protectedBy = null) - { - if (String.IsNullOrEmpty (package)) - return; - CSUsing target = new CSUsing (package); - if (!this.Exists (use => use.Contents == target.Contents)) { - if ((object)protectedBy != null) { - CSConditionalCompilation.ProtectWithIfEndif (protectedBy, target); - } - Add (target); - } - } - - public void AddIfNotPresent (Type t, CSIdentifier protectedBy = null) - { - AddIfNotPresent (t.Namespace, protectedBy); - } - } +namespace SyntaxDynamo.CSLang +{ + public class CSUsing : SimpleLineElement + { + public CSUsing(string package) + : base(string.Format("using {0};", Exceptions.ThrowOnNull(package, nameof(package))), false, false, false) + { + Package = package; + } + + public string Package { get; private set; } + } + + public class CSUsingPackages : CodeElementCollection + { + public CSUsingPackages() : base() { } + public CSUsingPackages(params CSUsing[] use) + : this() + { + AddRange(use); + } + public CSUsingPackages(params string[] use) + : this() + { + AddRange(use.Select(s => new CSUsing(s))); + } + + public CSUsingPackages And(CSUsing use) + { + Add(use); + return this; + } + + public CSUsingPackages And(string package) { return And(new CSUsing(package)); } + + public void AddIfNotPresent(string package, CSIdentifier protectedBy = null) + { + if (String.IsNullOrEmpty(package)) + return; + CSUsing target = new CSUsing(package); + if (!this.Exists(use => use.Contents == target.Contents)) + { + if ((object)protectedBy != null) + { + CSConditionalCompilation.ProtectWithIfEndif(protectedBy, target); + } + Add(target); + } + } + + public void AddIfNotPresent(Type t, CSIdentifier protectedBy = null) + { + AddIfNotPresent(t.Namespace, protectedBy); + } + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs index 8b993f4e2ad8..ce005aff06dd 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs @@ -1,93 +1,101 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SyntaxDynamo.CSLang { - public enum CSVisibility { - None = 0, - Public, - Internal, - Protected, - Private, - } +namespace SyntaxDynamo.CSLang +{ + public enum CSVisibility + { + None = 0, + Public, + Internal, + Protected, + Private, + } - public enum CSMethodKind { - None = 0, - Static, - StaticExtern, - StaticNew, - Virtual, - Override, - Extern, - New, - Abstract, - Interface, - Unsafe, - StaticUnsafe, - } + public enum CSMethodKind + { + None = 0, + Static, + StaticExtern, + StaticNew, + Virtual, + Override, + Extern, + New, + Abstract, + Interface, + Unsafe, + StaticUnsafe, + } - public enum CSBinaryOperator { - Add = 0, - Sub, - Mul, - Div, - Mod, - And, - Or, - Less, - Greater, - Equal, - NotEqual, - LessEqual, - GreaterEqual, - BitAnd, - BitOr, - BitXor, - LeftShift, - RightShift, - Dot, - Is, - As, - NullCoalesce, - } + public enum CSBinaryOperator + { + Add = 0, + Sub, + Mul, + Div, + Mod, + And, + Or, + Less, + Greater, + Equal, + NotEqual, + LessEqual, + GreaterEqual, + BitAnd, + BitOr, + BitXor, + LeftShift, + RightShift, + Dot, + Is, + As, + NullCoalesce, + } - public enum CSUnaryOperator { - Neg = 0, - Pos, - At, - Not, - BitNot, - Ref, - Out, - AddressOf, - Indirection, - Await, - PostBang, - Question, - } + public enum CSUnaryOperator + { + Neg = 0, + Pos, + At, + Not, + BitNot, + Ref, + Out, + AddressOf, + Indirection, + Await, + PostBang, + Question, + } - public enum CSAssignmentOperator { - Assign, - AddAssign, - SubAssign, - MulAssign, - DivAssign, - ModAssign, - AndAssign, - OrAssign, - XorAssign - } + public enum CSAssignmentOperator + { + Assign, + AddAssign, + SubAssign, + MulAssign, + DivAssign, + ModAssign, + AndAssign, + OrAssign, + XorAssign + } - public enum CSParameterKind { - None, - Ref, - Out, - Params, - This - } + public enum CSParameterKind + { + None, + Ref, + Out, + Params, + This + } - public enum CSShortCircuitKind { - Break, - Continue, - } + public enum CSShortCircuitKind + { + Break, + Continue, + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs index a6c2d21ff57f..9a5ec0708627 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs @@ -4,11 +4,14 @@ using System; using SyntaxDynamo; -namespace SyntaxDynamo.CSLang { - public interface ICSExpression : ICodeElement { - } +namespace SyntaxDynamo.CSLang +{ + public interface ICSExpression : ICodeElement + { + } - public interface ICSExpressionList : ICodeElementSet { - } + public interface ICSExpressionList : ICodeElementSet + { + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs index 82f3eabaa15c..791674cfd022 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs @@ -3,8 +3,10 @@ using System; -namespace SyntaxDynamo.CSLang { - public interface ICSLineable { - } +namespace SyntaxDynamo.CSLang +{ + public interface ICSLineable + { + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs index d876d1ed14f8..19e78407deb1 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs @@ -3,8 +3,10 @@ using System; -namespace SyntaxDynamo.CSLang { - public interface ICSStatement { - } +namespace SyntaxDynamo.CSLang +{ + public interface ICSStatement + { + } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs index a3fcc27e140d..c7b2459a5d93 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs @@ -1,18 +1,21 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -namespace SyntaxDynamo.CSLang { - public interface ICSTopLevelDeclaration : ICodeElement { - } +namespace SyntaxDynamo.CSLang +{ + public interface ICSTopLevelDeclaration : ICodeElement + { + } - public class CSTopLevelDeclations : CodeElementCollection { - public CSTopLevelDeclations (params ICSTopLevelDeclaration [] decls) - : base () - { - AddRange (Exceptions.ThrowOnNull (decls, "decls")); - } + public class CSTopLevelDeclations : CodeElementCollection + { + public CSTopLevelDeclations(params ICSTopLevelDeclaration[] decls) + : base() + { + AddRange(Exceptions.ThrowOnNull(decls, "decls")); + } - } + } } diff --git a/src/SyntaxDynamo/WriteEventArgs.cs b/src/SyntaxDynamo/WriteEventArgs.cs index 4b501a14df6f..d87a8a42c9f0 100644 --- a/src/SyntaxDynamo/WriteEventArgs.cs +++ b/src/SyntaxDynamo/WriteEventArgs.cs @@ -3,16 +3,18 @@ using System; -namespace SyntaxDynamo { - public class WriteEventArgs : EventArgs { - public WriteEventArgs (ICodeWriter writer) - { - if (writer == null) - throw new ArgumentNullException (nameof(writer)); - Writer = writer; - } +namespace SyntaxDynamo +{ + public class WriteEventArgs : EventArgs + { + public WriteEventArgs(ICodeWriter writer) + { + if (writer == null) + throw new ArgumentNullException(nameof(writer)); + Writer = writer; + } - public ICodeWriter Writer { get; private set; } - } + public ICodeWriter Writer { get; private set; } + } } From 1da30bdb9e7b2a0d027dcbbdc65c6e4ac0c16513 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 19:46:01 +0100 Subject: [PATCH 16/37] Update bindings compiler to use a module name and emit pinvokes and static functions within the same class --- src/SwiftBindings/tests/SmokeTests.cs | 6 +++--- src/SwiftReflector/BindingsCompiler.cs | 24 ++++++++++++------------ src/samples/HelloWorld/Program.cs | 4 ++-- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/SwiftBindings/tests/SmokeTests.cs b/src/SwiftBindings/tests/SmokeTests.cs index c90077403f81..2fe72491ae45 100644 --- a/src/SwiftBindings/tests/SmokeTests.cs +++ b/src/SwiftBindings/tests/SmokeTests.cs @@ -17,20 +17,20 @@ public void DirectPInvokeVoidVoid() // Licensed under the MIT License. using System; - using SmokeTests; + using SmokeTestsBindings; namespace Hello { class MainClass { public static int Main(string[] args) { - TopLevelEntities.SimplePinvokeVoidVoid(); + SmokeTests.SimplePinvokeVoidVoid(); return 42; } } } """; - int result = TestsHelper.CompileAndExecuteFromFileAndString("TopLevelEntitiesSmokeTests.cs", sourceCode); + int result = TestsHelper.CompileAndExecuteFromFileAndString("SmokeTestsBindings.cs", sourceCode); Assert.Equal(42, result); } } diff --git a/src/SwiftReflector/BindingsCompiler.cs b/src/SwiftReflector/BindingsCompiler.cs index 380cedcd4a63..9171f39604d2 100644 --- a/src/SwiftReflector/BindingsCompiler.cs +++ b/src/SwiftReflector/BindingsCompiler.cs @@ -81,7 +81,7 @@ public List GetModuleDeclarations(string swiftinterfacePath) { var use = new CSUsingPackages("System", "System.Runtime.InteropServices"); - var picl = new CSClass(CSVisibility.Internal, PIClassName(module.Name + "." + "TopLevelEntities")); + var picl = new CSClass(CSVisibility.Public, PIClassName(module.Name+"Bindings."+module.Name)); var usedPinvokes = new List(); var cl = CompileTLFuncs(module.TopLevelFunctions, module, moduleInventory, @@ -91,15 +91,15 @@ public List GetModuleDeclarations(string swiftinterfacePath) swiftLibPath, outputDirectory, errors, use, cl, picl, usedPinvokes); - if (cl != null) + if (picl != null) { - string nameSpace = TypeMapper.MapModuleToNamespace(module.Name); + string nameSpace = TypeMapper.MapModuleToNamespace(module.Name+"Bindings"); var nm = new CSNamespace(nameSpace); var csfile = new CSFile(use, new CSNamespace[] { nm }); - nm.Block.Add(cl); + // nm.Block.Add(cl); nm.Block.Add(picl); - string csOutputFileName = string.Format("{1}{0}.cs", nameSpace, cl.Name.Name); + string csOutputFileName = string.Format("{0}.cs", nameSpace); string csOutputPath = Path.Combine(outputDirectory, csOutputFileName); CodeWriter.WriteToFile(csOutputPath, csfile); @@ -131,7 +131,7 @@ public List GetModuleDeclarations(string swiftinterfacePath) continue; var tlf = XmlToTLFunctionMapper.ToTLFunction(func, moduleInventory, TypeMapper); - CompileToDirectFunction(func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames); + CompileToDirectFunction(func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames, module); } catch (Exception e) { @@ -141,15 +141,15 @@ public List GetModuleDeclarations(string swiftinterfacePath) if (methods.Count > 0) { - cl = cl ?? new CSClass(CSVisibility.Public, "TopLevelEntities"); - cl.Methods.AddRange(methods); + // cl = cl ?? new CSClass(CSVisibility.Public, module.Name); + picl.Methods.AddRange(methods); } return cl; } void CompileToDirectFunction(FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context, CSUsingPackages use, string swiftLibPath, List methods, CSClass picl, - List usedPinvokeNames) + List usedPinvokeNames, ModuleDeclaration module) { // FIXME - need to do operators if (tlf.Operator != OperatorType.None) @@ -160,7 +160,7 @@ public List GetModuleDeclarations(string swiftinterfacePath) pinvokeMethodName = Uniqueify(pinvokeMethodName, usedPinvokeNames); usedPinvokeNames.Add(pinvokeMethodName); - var pinvokeMethodRef = PIClassName($"{func.Module.Name}.TopLevelEntities") + "." + pinvokeMethodName; + var pinvokeMethodRef = PIClassName($"{func.Module.Name}.{module.Name}") + "." + pinvokeMethodName; var piMethod = TLFCompiler.CompileMethod(func, use, PInvokeName(swiftLibPath), tlf.MangledName, pinvokeMethodName, true, true, false); @@ -204,7 +204,7 @@ public List GetModuleDeclarations(string swiftinterfacePath) continue; try { - cl = cl ?? new CSClass(CSVisibility.Public, "TopLevelEntities"); + cl = cl ?? new CSClass(CSVisibility.Public, module.Name); // Calculated properties have a matching __method string backingMethodName = ("__" + prop.Name); @@ -228,7 +228,7 @@ string PIClassName(string fullClassName) if (!fullClassName.Contains('.')) throw new ArgumentOutOfRangeException(nameof(fullClassName), String.Format("Class name {0} should be a full class name.", fullClassName)); fullClassName = fullClassName.Substring(fullClassName.IndexOf('.') + 1).Replace('.', '_'); - return "NativeMethodsFor" + fullClassName; + return fullClassName; } string PIClassName(DotNetName fullClassName) diff --git a/src/samples/HelloWorld/Program.cs b/src/samples/HelloWorld/Program.cs index 21a0e34b01d4..b85e031f1e9f 100644 --- a/src/samples/HelloWorld/Program.cs +++ b/src/samples/HelloWorld/Program.cs @@ -2,7 +2,7 @@ // Licensed under the MIT License. using System; -using HelloLibrary; +using HelloLibraryBindings; namespace HelloWorld { @@ -10,7 +10,7 @@ public class Program { public static void Main(string[] args) { - TopLevelEntities.SayHello(); + HelloLibrary.SayHello(); } } } From 283938ae0f2dac7de06d8bafa00c508f61e95d88 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Fri, 16 Feb 2024 21:00:40 +0100 Subject: [PATCH 17/37] Update Microsoft.DotNet.Arcade.Sdk version --- global.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/global.json b/global.json index 2e4a95fa688a..e62916b1b7c8 100644 --- a/global.json +++ b/global.json @@ -8,6 +8,6 @@ "dotnet": "7.0.100" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.24102.4" + "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.22430.3" } } From 726240110574e1189dacc030a4369072204a4d2b Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 15:12:16 +0100 Subject: [PATCH 18/37] Add .sln file --- SwiftBindings.sln | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 SwiftBindings.sln diff --git a/SwiftBindings.sln b/SwiftBindings.sln new file mode 100644 index 000000000000..b9fbbaacd06f --- /dev/null +++ b/SwiftBindings.sln @@ -0,0 +1,48 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings", "src\SwiftBindings\src\SwiftBindings.csproj", "{B7977360-6671-4707-9A1C-1C29D5BE2674}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings.Tests", "src\SwiftBindings\tests\SwiftBindings.Tests.csproj", "{CE81B6BD-CCCC-4223-9069-B28435A4A5C1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x64.ActiveCfg = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x64.Build.0 = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x86.ActiveCfg = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x86.Build.0 = Debug|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|Any CPU.Build.0 = Release|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x64.ActiveCfg = Release|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x64.Build.0 = Release|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x86.ActiveCfg = Release|Any CPU + {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x86.Build.0 = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x64.ActiveCfg = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x64.Build.0 = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x86.ActiveCfg = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x86.Build.0 = Debug|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|Any CPU.Build.0 = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x64.ActiveCfg = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x64.Build.0 = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.ActiveCfg = Release|Any CPU + {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal From aef5b026572839e46d5fc6e24e4e20884952765d Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 16:04:42 +0100 Subject: [PATCH 19/37] Add nuget.org as package source --- NuGet.config | 1 + 1 file changed, 1 insertion(+) diff --git a/NuGet.config b/NuGet.config index 8fd81cd51c15..cc08b44fbdc9 100644 --- a/NuGet.config +++ b/NuGet.config @@ -9,6 +9,7 @@ + From 75879080108bfdcdde5dea7249c62cf49fd08274 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 16:15:45 +0100 Subject: [PATCH 20/37] Remove ninja generator to test the CI --- src/SwiftBindings/tests/CMakeLists.txt | 2 +- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index 54874c422d04..ad95d4b52694 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests Swift) +project(SmokeTests) set(SOURCE SmokeTests) diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index d862a01349b1..e9bedd90a5dc 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja + cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make From 799187f1e0a367de5c3392439590e8f75c670d61 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 16:22:50 +0100 Subject: [PATCH 21/37] Revert temporary changes --- NuGet.config | 1 - src/SwiftBindings/tests/CMakeLists.txt | 2 +- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/NuGet.config b/NuGet.config index cc08b44fbdc9..8fd81cd51c15 100644 --- a/NuGet.config +++ b/NuGet.config @@ -9,7 +9,6 @@ - diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index ad95d4b52694..54874c422d04 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests) +project(SmokeTests Swift) set(SOURCE SmokeTests) diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index e9bedd90a5dc..d862a01349b1 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make + cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja From d23735adc6ca83736c366debc176f6137bb49207 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 18:08:33 +0100 Subject: [PATCH 22/37] Update .gitignore --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 0f6b076f2389..dbcf980bff27 100644 --- a/.gitignore +++ b/.gitignore @@ -197,4 +197,7 @@ launchSettings.json *.swiftmodule* *.abi* *.swiftsourceinfo* -*.dylib \ No newline at end of file +*.dylib + +# Testing artifacts +testing/ \ No newline at end of file From b8457c98f47ee14aebc7e274e859613a8716257f Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 20:43:18 +0100 Subject: [PATCH 23/37] Use cmake instead of ninja --- src/SwiftBindings/tests/CMakeLists.txt | 2 +- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index 54874c422d04..ad95d4b52694 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests Swift) +project(SmokeTests) set(SOURCE SmokeTests) diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index d862a01349b1..e9bedd90a5dc 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja + cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make From 59a5a656aa84eb64833e25534ec9103d15fb154f Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 21:06:58 +0100 Subject: [PATCH 24/37] Use macOS vmImage --- eng/pipelines/runtimelab.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/eng/pipelines/runtimelab.yml b/eng/pipelines/runtimelab.yml index a2d5f7dda0f4..4cf1d529d10a 100644 --- a/eng/pipelines/runtimelab.yml +++ b/eng/pipelines/runtimelab.yml @@ -53,11 +53,11 @@ stages: parameters: osGroup: OSX archType: x64 - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - isOfficialBuild: true - runTests: false - pool: - vmImage: 'macOS-latest' + # ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + # isOfficialBuild: true + runTests: true + pool: + vmImage: 'macOS-latest' # Publish and validation steps. Only run in official builds - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: From 2866a2e7a5836f63da70bddcf7add5b896db4c41 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 21:16:04 +0100 Subject: [PATCH 25/37] Don't override SWIFT_PLATFORM_SUFFIX if set --- eng/pipelines/runtimelab.yml | 2 -- src/SwiftBindings/tests/CMakeLists.txt | 4 +++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/pipelines/runtimelab.yml b/eng/pipelines/runtimelab.yml index 4cf1d529d10a..2a99576a961e 100644 --- a/eng/pipelines/runtimelab.yml +++ b/eng/pipelines/runtimelab.yml @@ -53,8 +53,6 @@ stages: parameters: osGroup: OSX archType: x64 - # ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - # isOfficialBuild: true runTests: true pool: vmImage: 'macOS-latest' diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index ad95d4b52694..5342b1e599ba 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -9,7 +9,9 @@ if (NOT SWIFT_COMPILER_TARGET) if (NOT DEFINED CMAKE_OSX_ARCHITECTURES OR CMAKE_OSX_ARCHITECTURES STREQUAL "") set(CMAKE_OSX_ARCHITECTURES "arm64") endif() - set(SWIFT_PLATFORM_SUFFIX "11") + if (NOT DEFINED SWIFT_PLATFORM_SUFFIX OR SWIFT_PLATFORM_SUFFIX STREQUAL "") + set(SWIFT_PLATFORM_SUFFIX "11") + endif() set(SWIFT_DEPLOYMENT_TARGET ${CMAKE_OSX_DEPLOYMENT_TARGET}) set(SWIFT_COMPILER_TARGET "${CMAKE_OSX_ARCHITECTURES}-apple-${SWIFT_PLATFORM}${SWIFT_DEPLOYMENT_TARGET}${SWIFT_PLATFORM_SUFFIX}") endif() From ac3f569f28c07e3f9b30c87c637d493f2eb25f65 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 21:48:22 +0100 Subject: [PATCH 26/37] Fix SWIFT_COMPILER_TARGET variable --- src/SwiftBindings/tests/CMakeLists.txt | 12 ++++++------ src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index 5342b1e599ba..abb89e30e21d 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,19 +1,19 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests) +project(SmokeTests Swift) set(SOURCE SmokeTests) if (NOT SWIFT_COMPILER_TARGET) set(SWIFT_PLATFORM "macosx") if (NOT DEFINED CMAKE_OSX_ARCHITECTURES OR CMAKE_OSX_ARCHITECTURES STREQUAL "") - set(CMAKE_OSX_ARCHITECTURES "arm64") - endif() - if (NOT DEFINED SWIFT_PLATFORM_SUFFIX OR SWIFT_PLATFORM_SUFFIX STREQUAL "") - set(SWIFT_PLATFORM_SUFFIX "11") + set(CMAKE_OSX_ARCHITECTURES "${CMAKE_SYSTEM_PROCESSOR}") endif() set(SWIFT_DEPLOYMENT_TARGET ${CMAKE_OSX_DEPLOYMENT_TARGET}) - set(SWIFT_COMPILER_TARGET "${CMAKE_OSX_ARCHITECTURES}-apple-${SWIFT_PLATFORM}${SWIFT_DEPLOYMENT_TARGET}${SWIFT_PLATFORM_SUFFIX}") + if (NOT DEFINED SWIFT_DEPLOYMENT_TARGET OR SWIFT_DEPLOYMENT_TARGET STREQUAL "") + set(SWIFT_DEPLOYMENT_TARGET "11") + endif() + set(SWIFT_COMPILER_TARGET "${CMAKE_OSX_ARCHITECTURES}-apple-${SWIFT_PLATFORM}${SWIFT_DEPLOYMENT_TARGET}") endif() add_custom_target(${SOURCE} ALL diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index e9bedd90a5dc..d862a01349b1 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make + cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja From 62b93c7ec0d1f6898f0902a493536d6113abee03 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 21:53:31 +0100 Subject: [PATCH 27/37] Use cmake instead of ninja --- src/SwiftBindings/tests/CMakeLists.txt | 2 +- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index abb89e30e21d..eb0b3634345e 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests Swift) +project(SmokeTests) set(SOURCE SmokeTests) diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index d862a01349b1..e9bedd90a5dc 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,7 +1,7 @@ net7.0 - cd $(OutputPath)$(TargetFramework) && cmake -G Ninja $(MSBuildThisFileDirectory) && ninja + cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make From 69ef2e5cf1c7946a9cd60bdd1daff4496d05a758 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Mon, 19 Feb 2024 22:47:22 +0100 Subject: [PATCH 28/37] Introduce Swift types database --- src/SwiftReflector/MarshalEngine.cs | 27 +++ src/SwiftReflector/TypeMapping/TypeMapper.cs | 4 + src/SwiftRuntimeLibrary/SwiftCore.xml | 223 ++++++++++++++++++ .../SwiftRuntimeLibrary.csproj | 5 + 4 files changed, 259 insertions(+) create mode 100644 src/SwiftRuntimeLibrary/SwiftCore.xml diff --git a/src/SwiftReflector/MarshalEngine.cs b/src/SwiftReflector/MarshalEngine.cs index 74db006bfe8d..e85e1abd52e2 100644 --- a/src/SwiftReflector/MarshalEngine.cs +++ b/src/SwiftReflector/MarshalEngine.cs @@ -265,6 +265,7 @@ CSType ReworkTypeWithNamer(CSType ty) switch (entityType) { case EntityType.Scalar: + return MarshalScalar (p); case EntityType.Tuple: case EntityType.None: // Add more types @@ -273,6 +274,32 @@ CSType ReworkTypeWithNamer(CSType ty) throw new NotImplementedException($"Uh-oh - not ready for {swiftType.ToString()}, a {entityType}."); } + CSBaseExpression MarshalScalar (CSParameter p) + { + return ParmName (p); + } + + static CSIdentifier ParmName (CSParameter parm) + { + return ParmName (parm.Name.Name, parm.ParameterKind); + } + + static CSIdentifier ParmName (string ident, CSParameterKind parmKind) + { + string prefix = ""; + switch (parmKind) { + case CSParameterKind.Out: + prefix = "out "; + break; + case CSParameterKind.Ref: + prefix = "ref "; + break; + default: + break; + } + return new CSIdentifier (String.Format ("{0}{1}", prefix, ident)); + } + public static string Uniqueify(string name, IEnumerable names) { int thisTime = 0; diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/TypeMapping/TypeMapper.cs index 93ff0946706f..30b147a7d236 100644 --- a/src/SwiftReflector/TypeMapping/TypeMapper.cs +++ b/src/SwiftReflector/TypeMapping/TypeMapper.cs @@ -25,6 +25,10 @@ public TypeMapper(List typeDatabasePaths, UnicodeMapper unicodeMapper) { TypeDatabase = new TypeDatabase(); this.unicodeMapper = unicodeMapper; + + string basePath = AppDomain.CurrentDomain.BaseDirectory; + string xmlFilePath = Path.Combine(basePath, "SwiftCore.xml"); + AddTypeDatabase(xmlFilePath); } public void AddTypeDatabase(string fileName) diff --git a/src/SwiftRuntimeLibrary/SwiftCore.xml b/src/SwiftRuntimeLibrary/SwiftCore.xml new file mode 100644 index 000000000000..d7085bb6d412 --- /dev/null +++ b/src/SwiftRuntimeLibrary/SwiftCore.xml @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj index a71289817ef0..de826e1d007c 100644 --- a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj +++ b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj @@ -6,4 +6,9 @@ disable true + + + PreserveNewest + + From 99834f5b8b33b4bdc953e46ba20cca10ac319467 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 21 Feb 2024 15:48:10 +0100 Subject: [PATCH 29/37] Temporarily remove SwiftInterfaceReflector from the project This change removes SwiftInterfaceReflector and its dependencies to simplify code review. Temporarily, the tooling will consume the ABI interface instead of swiftinterface. The code has been reorganized into components: SwiftBindings, which generates C# bindings, and SwiftReflector, which contains type system ABI aggregation logic. The ISwiftParser interface has been introduced to facilitate modularization within the project, and ABI aggregators are expected to implement this interface. --- src/SwiftBindings/src/BindingsCompiler.cs | 59 + src/SwiftBindings/src/FunctionCompiler.cs | 58 + src/SwiftBindings/src/MarshalEngine.cs | 146 + src/SwiftBindings/src/Program.cs | 119 +- src/SwiftBindings/tests/SmokeTests.cs | 2 +- src/SwiftReflector/BindingsCompiler.cs | 289 - src/SwiftReflector/CSKeywords.cs | 47 - .../Demangling/ContextAttribute.cs | 11 - src/SwiftReflector/Demangling/Decomposer.cs | 1262 -- src/SwiftReflector/Demangling/Enums.cs | 381 - src/SwiftReflector/Demangling/MatchRule.cs | 99 - src/SwiftReflector/Demangling/Node.cs | 262 - src/SwiftReflector/Demangling/RuleRunner.cs | 25 - .../Demangling/Swift5Demangler.cs | 3231 ---- .../Demangling/Swift5NodeToTLDefinition.cs | 2138 --- src/SwiftReflector/Demangling/TLDefinition.cs | 295 - src/SwiftReflector/ErrorHandling.cs | 6 - src/SwiftReflector/Extensions.cs | 196 +- src/SwiftReflector/IOUtils/ExecAndCollect.cs | 131 - src/SwiftReflector/IOUtils/IFileProvider.cs | 12 - src/SwiftReflector/IOUtils/OffsetStream.cs | 173 - src/SwiftReflector/Inventory/ClassContents.cs | 355 - .../Inventory/ClassInventory.cs | 74 - .../Inventory/FunctionInventory.cs | 119 - src/SwiftReflector/Inventory/Inventory.cs | 47 - .../Inventory/ModuleContents.cs | 122 - .../Inventory/ModuleInventory.cs | 194 - .../Inventory/OverloadInventory.cs | 48 - .../Inventory/PropertyContents.cs | 219 - .../Inventory/PropertyInventory.cs | 58 - .../Inventory/ProtocolContents.cs | 96 - .../Inventory/ProtocolInventory.cs | 35 - .../Inventory/VariableContents.cs | 25 - .../Inventory/VariableInventory.cs | 57 - .../Inventory/WitnessInventory.cs | 71 - src/SwiftReflector/MachOHawley.cs | 1434 -- src/SwiftReflector/MarshalEngine.cs | 340 - src/SwiftReflector/Parser/ISwiftParser.cs | 13 + .../Parser/SwiftABIParser/SwiftABIParser.cs | 116 + .../Parser/SwiftInterfaceParser/.gitkeep | 0 src/SwiftReflector/PunyCode.cs | 173 - src/SwiftReflector/StringSlice.cs | 233 - src/SwiftReflector/SwiftClassName.cs | 21 - .../SwiftInterfaceBaseListener.cs | 2131 --- .../GeneratedParser/SwiftInterfaceLexer.cs | 1395 -- .../GeneratedParser/SwiftInterfaceListener.cs | 1771 --- .../GeneratedParser/SwiftInterfaceParser.cs | 13120 ---------------- .../SwiftInterfaceReflector/IModuleLoader.cs | 30 - .../ObjCSelectorFactory.cs | 345 - .../SwiftInterfaceReflector/ParseException.cs | 20 - .../SwiftInterfaceReflector.cs | 2468 --- .../SyntaxDesugaringParser.cs | 124 - src/SwiftReflector/SwiftName.cs | 3 +- src/SwiftReflector/SwiftReflector.csproj | 1 + src/SwiftReflector/SwiftType.cs | 881 -- .../SwiftXmlReflection/BaseConstraint.cs | 3 +- .../SwiftXmlReflection/EnumElement.cs | 1 - .../ExtensionDeclaration.cs | 1 - .../SwiftXmlReflection/FunctionDeclaration.cs | 5 +- .../GenericDeclarationCollection.cs | 1 - .../IXElementConvertible.cs | 3 +- .../SwiftXmlReflection/Inheritance.cs | 1 - .../SwiftXmlReflection/Member.cs | 1 - .../SwiftXmlReflection/ModuleDeclaration.cs | 2 +- .../SwiftXmlReflection/ParameterItem.cs | 2 - .../SwiftXmlReflection/Reflector.cs | 134 - .../SwiftXmlReflection/TypeDeclaration.cs | 2 - .../SwiftXmlReflection/TypeSpec.cs | 2 +- .../TopLevelFunctionCompiler.cs | 379 - src/SwiftReflector/TypeMapping/Entity.cs | 1 - .../TypeMapping/TypeDatabase.cs | 126 +- src/SwiftReflector/TypeMapping/TypeMapper.cs | 979 +- src/SwiftReflector/ValueWitnessTable.cs | 131 - src/SwiftReflector/XmlToTLFunctionMapper.cs | 548 - .../SyntaxDynamo.CSLang/CSAttribute.cs | 8 + src/samples/HelloWorld/Program.cs | 2 +- src/samples/HelloWorld/build.sh | 2 +- 77 files changed, 512 insertions(+), 36903 deletions(-) create mode 100644 src/SwiftBindings/src/BindingsCompiler.cs create mode 100644 src/SwiftBindings/src/FunctionCompiler.cs create mode 100644 src/SwiftBindings/src/MarshalEngine.cs delete mode 100644 src/SwiftReflector/BindingsCompiler.cs delete mode 100644 src/SwiftReflector/CSKeywords.cs delete mode 100644 src/SwiftReflector/Demangling/ContextAttribute.cs delete mode 100644 src/SwiftReflector/Demangling/Decomposer.cs delete mode 100644 src/SwiftReflector/Demangling/Enums.cs delete mode 100644 src/SwiftReflector/Demangling/MatchRule.cs delete mode 100644 src/SwiftReflector/Demangling/Node.cs delete mode 100644 src/SwiftReflector/Demangling/RuleRunner.cs delete mode 100644 src/SwiftReflector/Demangling/Swift5Demangler.cs delete mode 100644 src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs delete mode 100644 src/SwiftReflector/Demangling/TLDefinition.cs delete mode 100644 src/SwiftReflector/IOUtils/ExecAndCollect.cs delete mode 100644 src/SwiftReflector/IOUtils/IFileProvider.cs delete mode 100644 src/SwiftReflector/IOUtils/OffsetStream.cs delete mode 100644 src/SwiftReflector/Inventory/ClassContents.cs delete mode 100644 src/SwiftReflector/Inventory/ClassInventory.cs delete mode 100644 src/SwiftReflector/Inventory/FunctionInventory.cs delete mode 100644 src/SwiftReflector/Inventory/Inventory.cs delete mode 100644 src/SwiftReflector/Inventory/ModuleContents.cs delete mode 100644 src/SwiftReflector/Inventory/ModuleInventory.cs delete mode 100644 src/SwiftReflector/Inventory/OverloadInventory.cs delete mode 100644 src/SwiftReflector/Inventory/PropertyContents.cs delete mode 100644 src/SwiftReflector/Inventory/PropertyInventory.cs delete mode 100644 src/SwiftReflector/Inventory/ProtocolContents.cs delete mode 100644 src/SwiftReflector/Inventory/ProtocolInventory.cs delete mode 100644 src/SwiftReflector/Inventory/VariableContents.cs delete mode 100644 src/SwiftReflector/Inventory/VariableInventory.cs delete mode 100644 src/SwiftReflector/Inventory/WitnessInventory.cs delete mode 100644 src/SwiftReflector/MachOHawley.cs delete mode 100644 src/SwiftReflector/MarshalEngine.cs create mode 100644 src/SwiftReflector/Parser/ISwiftParser.cs create mode 100644 src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs create mode 100644 src/SwiftReflector/Parser/SwiftInterfaceParser/.gitkeep delete mode 100644 src/SwiftReflector/PunyCode.cs delete mode 100644 src/SwiftReflector/StringSlice.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs delete mode 100644 src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs rename src/SwiftReflector/{IOUtils => SwiftXmlReflection}/IXElementConvertible.cs (84%) delete mode 100644 src/SwiftReflector/SwiftXmlReflection/Reflector.cs delete mode 100644 src/SwiftReflector/TopLevelFunctionCompiler.cs delete mode 100644 src/SwiftReflector/ValueWitnessTable.cs delete mode 100644 src/SwiftReflector/XmlToTLFunctionMapper.cs diff --git a/src/SwiftBindings/src/BindingsCompiler.cs b/src/SwiftBindings/src/BindingsCompiler.cs new file mode 100644 index 000000000000..f39034012665 --- /dev/null +++ b/src/SwiftBindings/src/BindingsCompiler.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo; +using SyntaxDynamo.CSLang; +using SwiftReflector.SwiftXmlReflection; +using SwiftReflector.TypeMapping; + +namespace SwiftReflector +{ + public class BindingsCompiler + { + UnicodeMapper UnicodeMapper; + TypeMapper TypeMapper; + FunctionCompiler TLFCompiler; + + public BindingsCompiler() + { + UnicodeMapper = new UnicodeMapper(); + TypeMapper = new TypeMapper(null, UnicodeMapper); + TLFCompiler = new FunctionCompiler(TypeMapper); + } + + public void CompileModule(ModuleDeclaration decl, string outputDirectory, ErrorHandling errors) + { + var namespaceName = $"{decl.Name}Bindings"; + var csNamespace = new CSNamespace(namespaceName); + var csUsingPackages = new CSUsingPackages("System", "System.Runtime.InteropServices"); + var csClass = new CSClass(CSVisibility.Public, decl.Name); + + var csFile = new CSFile(csUsingPackages, new CSNamespace[] { csNamespace }); + csNamespace.Block.Add(csClass); + IEnumerable methods = CompileFunctions(decl.Functions, errors); + csClass.Methods.AddRange(methods); + + string csOutputPath = Path.Combine(outputDirectory, string.Format("{0}.cs", namespaceName)); + CodeWriter.WriteToFile(csOutputPath, csFile); + } + + IEnumerable CompileFunctions(IEnumerable decls, ErrorHandling errors) + { + List methods = new List(); + foreach (FunctionDeclaration decl in decls) + { + var piMethod = TLFCompiler.CompileMethod(decl, true); + methods.Add(piMethod); + var publicMethod = TLFCompiler.CompileMethod(decl, false); + methods.Add(publicMethod); + + var marshaler = new MarshalEngine(null, null, TypeMapper, null); + var lines = marshaler.MarshalFunctionCall(decl, publicMethod, piMethod); + publicMethod.Body.AddRange(lines); + } + + return methods; + } + } +} diff --git a/src/SwiftBindings/src/FunctionCompiler.cs b/src/SwiftBindings/src/FunctionCompiler.cs new file mode 100644 index 000000000000..9282ed340cb2 --- /dev/null +++ b/src/SwiftBindings/src/FunctionCompiler.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo.CSLang; +using SwiftReflector.TypeMapping; +using SwiftReflector.SwiftXmlReflection; + +namespace SwiftReflector +{ + public class FunctionCompiler + { + TypeMapper typeMap; + public FunctionCompiler(TypeMapper typeMap) + { + this.typeMap = typeMap; + } + + public CSMethod CompileMethod(FunctionDeclaration func, bool isPinvoke) + { + string funcName = func.Name; + if (isPinvoke) { + funcName = string.Format("PIfunc_{0}", funcName); + } + + NetTypeBundle returnType = typeMap.MapType(func, func.ReturnTypeSpec, isPinvoke, true); + CSUsingPackages packs = new CSUsingPackages(); + CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType(packs); + + var csParams = new CSParameterList(); + if (func.ParameterLists.Count > 0){ + var args = typeMap.MapParameterList(func, func.ParameterLists.Last(), isPinvoke, false, null, null, packs); + foreach (var arg in args) + { + var csType = arg.Type.ToCSType(packs); + csParams.Add(new CSParameter(csType, new CSIdentifier(arg.Name), arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)); + } + } + + if (isPinvoke) + { + return CSMethod.InternalPInvoke(csReturnType, funcName, $"lib{func.Module.Name}.dylib", func.MangledName, csParams); + } + else + { + return new CSMethod(CSVisibility.Public, func.IsStatic ? CSMethodKind.Static : CSMethodKind.Virtual, csReturnType, new CSIdentifier(funcName), csParams, new CSCodeBlock()); + } + } + + static void AddUsingBlock(CSUsingPackages packs, NetTypeBundle type) + { + if (type.IsVoid || String.IsNullOrEmpty(type.NameSpace)) + return; + packs.AddIfNotPresent(type.NameSpace); + } + } +} + diff --git a/src/SwiftBindings/src/MarshalEngine.cs b/src/SwiftBindings/src/MarshalEngine.cs new file mode 100644 index 000000000000..924ee17e921e --- /dev/null +++ b/src/SwiftBindings/src/MarshalEngine.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SyntaxDynamo.CSLang; +using SwiftReflector.TypeMapping; +using SyntaxDynamo; +using SwiftReflector.SwiftXmlReflection; + +namespace SwiftReflector +{ + public class MarshalEngine + { + CSUsingPackages use; + TypeMapper typeMapper; + public bool skipThisParameterPremarshal = false; + List fixedChain = new List(); + Version swiftLangVersion; + public Func genericReferenceNamer = null; + public Func GenericReferenceNamer { get; set; } + + public MarshalEngine(CSUsingPackages use, List identifiersUsed, TypeMapper typeMapper, Version swiftLangVersion) + { + this.use = use; + + this.typeMapper = typeMapper; + this.swiftLangVersion = swiftLangVersion; + } + + public IEnumerable MarshalFunctionCall(FunctionDeclaration decl, CSMethod caller, CSMethod callee) + { + ICodeElement functionCall; + var parms = new CSParameterList(caller.Parameters); + var callParameters = new List(parms.Count); + if (parms.Count > 0) { + var filteredTypeSpec = FilterParams (parms, decl); + for (int i = 0; i < parms.Count; i++) + { + var p = parms[i]; + var originalParm = decl.ParameterLists.Last()[i].TypeSpec; + callParameters.Add(Marshal(null, decl, p, filteredTypeSpec[i], false, + false, originalParm)); + } + } + + var call = new CSFunctionCall(callee.Name.ToString(), false, callParameters.ToArray()); + if (decl.ReturnTypeSpec.Kind != TypeSpecKind.Tuple) + functionCall = CSReturn.ReturnLine((ICSExpression)call); + else + functionCall = new CSLine(call); + + yield return functionCall; + } + + CSParameter ReworkParameterWithNamer(CSParameter p) + { + if (GenericReferenceNamer == null) + return p; + var pClone = ReworkTypeWithNamer(p.CSType); + return new CSParameter(pClone, p.Name, p.ParameterKind, p.DefaultValue); + } + + CSType ReworkTypeWithNamer(CSType ty) + { + if (ty is CSGenericReferenceType genRef) + { + var newGen = new CSGenericReferenceType(genRef.Depth, genRef.Index); + newGen.ReferenceNamer = GenericReferenceNamer; + return newGen; + } + else if (ty is CSSimpleType simple) + { + if (simple.GenericTypes == null) + return simple; + var genSubTypes = new CSType[simple.GenericTypes.Length]; + for (int i = 0; i < genSubTypes.Length; i++) + { + genSubTypes[i] = ReworkTypeWithNamer(simple.GenericTypes[i]); + } + var simpleClone = new CSSimpleType(simple.GenericTypeName, simple.IsArray, genSubTypes); + return simpleClone; + } + else + { + throw new NotImplementedException($"Unable to rework type {ty.GetType().Name} {ty.ToString()} as generic reference"); + } + } + + CSBaseExpression Marshal(BaseDeclaration typeContext, FunctionDeclaration funcDecl, CSParameter p, TypeSpec swiftType, + bool marshalProtocolAsValueType, bool isReturnVariable, TypeSpec originalType) + { + p = ReworkParameterWithNamer(p); + + var entityType = typeMapper.GetEntityTypeForTypeSpec(swiftType); + switch (entityType) + { + case EntityType.Scalar: + return MarshalScalar (p); + case EntityType.Tuple: + case EntityType.None: + // Add more types + break; + } + throw new NotImplementedException($"Uh-oh - not ready for {swiftType.ToString()}, a {entityType}."); + } + + CSBaseExpression MarshalScalar (CSParameter p) + { + return ParmName (p); + } + + static CSIdentifier ParmName (CSParameter parm) + { + return ParmName (parm.Name.Name, parm.ParameterKind); + } + + static CSIdentifier ParmName (string ident, CSParameterKind parmKind) + { + string prefix = ""; + switch (parmKind) { + case CSParameterKind.Out: + prefix = "out "; + break; + case CSParameterKind.Ref: + prefix = "ref "; + break; + default: + break; + } + return new CSIdentifier (String.Format ("{0}{1}", prefix, ident)); + } + + TypeSpec[] FilterParams(CSParameterList parms, FunctionDeclaration decl) + { + var results = new TypeSpec[parms.Count]; + var parameterList = decl.ParameterLists.Last(); + for (int i = 0; i < parms.Count; i++) + { + var currType = parameterList[i].TypeSpec; + results[i] = currType; + } + return results; + } + } +} + diff --git a/src/SwiftBindings/src/Program.cs b/src/SwiftBindings/src/Program.cs index cfd6a7eea70c..c26cd8fc0f0d 100644 --- a/src/SwiftBindings/src/Program.cs +++ b/src/SwiftBindings/src/Program.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.IO; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; using System.CommandLine; -using System.CommandLine.Invocation; -using System.Linq; using SwiftReflector; +using SwiftReflector.Parser; namespace SwiftBindings { @@ -12,96 +12,77 @@ public class BindingsTool { public static void Main(string[] args) { - Option> dylibOption = new(aliases: new[] { "-d", "--dylib" }, description: "Path to the dynamic library.") { AllowMultipleArgumentsPerToken = true, IsRequired = true }; - Option> swiftinterfaceOption = new(aliases: new[] { "-s", "--swiftinterface" }, "Path to the Swift interface file.") { AllowMultipleArgumentsPerToken = true, IsRequired = true }; + Option> swiftAbiOption = new(aliases: new[] { "-a", "--swiftabi" }, "Path to the Swift ABI file.") { AllowMultipleArgumentsPerToken = true, IsRequired = true }; Option outputDirectoryOption = new(aliases: new[] { "-o", "--output" }, "Output directory for generated bindings.") { IsRequired = true }; Option verboseOption = new(aliases: new[] { "-v", "--verbose" }, "Prints information about work in process."); Option helpOption = new(aliases: new[] { "-h", "--help" }, "Display a help message."); RootCommand rootCommand = new(description: "Swift bindings generator.") { - dylibOption, - swiftinterfaceOption, + swiftAbiOption, outputDirectoryOption, verboseOption, helpOption, }; - rootCommand.SetHandler((IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory, int verbose, bool help) => + rootCommand.SetHandler((IEnumerable swiftAbiPaths, string outputDirectory, int verbose, bool help) => + { + if (help) { - if (help) - { - Console.WriteLine("Usage:"); - Console.WriteLine(" -d, --dylib Required. Path to the dynamic library."); - Console.WriteLine(" -s, --swiftinterface Required. Path to the Swift interface file."); - Console.WriteLine(" -o, --output Required. Output directory for generated bindings."); - Console.WriteLine(" -v, --verbose Information about work in process."); - return; - } - - if (ValidateOptions(dylibPaths, swiftinterfacePaths, outputDirectory)) - { - for (int i = 0; i < dylibPaths.Count(); i++) - { - string dylibPath = dylibPaths.ElementAt(i); - string swiftInterfacePath = swiftinterfacePaths.ElementAt(i); + Console.WriteLine("Usage:"); + Console.WriteLine(" -a, --swiftabi Required. Path to the Swift ABI file."); + Console.WriteLine(" -o, --output Required. Output directory for generated bindings."); + Console.WriteLine(" -v, --verbose nformation about work in process."); + return; + } - if (!File.Exists(dylibPath)) - { - Console.Error.WriteLine($"Error: Dynamic library not found at path '{dylibPath}'."); - return; - } + if (outputDirectory == string.Empty) + { + Console.Error.WriteLine("Error: Missing required argument(s)."); + return; + } - if (!File.Exists(swiftInterfacePath)) - { - Console.Error.WriteLine($"Error: Swift interface file not found at path '{swiftInterfacePath}'."); - return; - } + for (int i = 0; i < swiftAbiPaths.Count(); i++) + { + string swiftAbiPath = swiftAbiPaths.ElementAt(i); - GenerateBindings(dylibPath, swiftInterfacePath, outputDirectory, verbose); - } + if (!File.Exists(swiftAbiPath)) + { + Console.Error.WriteLine($"Error: Swift ABI file not found at path '{swiftAbiPath}'."); + return; } - }, - dylibOption, - swiftinterfaceOption, - outputDirectoryOption, - verboseOption, - helpOption + if (verbose > 0) + Console.WriteLine($"Processing Swift ABI file: {swiftAbiPath}"); + + GenerateBindings(swiftAbiPath, outputDirectory, verbose); + } + }, + swiftAbiOption, + outputDirectoryOption, + verboseOption, + helpOption ); rootCommand.Invoke(args); } - private static bool ValidateOptions(IEnumerable dylibPaths, IEnumerable swiftinterfacePaths, string outputDirectory) + public static void GenerateBindings(string swiftAbiPath, string outputDirectory, int verbose = 0) { - if (dylibPaths == null || swiftinterfacePaths == null || outputDirectory == string.Empty) - { - Console.Error.WriteLine("Error: Missing required argument(s)."); - return false; - } + if (verbose > 0) + Console.WriteLine("Starting bindings generation..."); - if (dylibPaths.Count() != swiftinterfacePaths.Count()) - { - Console.Error.WriteLine("Error: Number of dylib and interface files must match."); - return false; - } + BindingsCompiler bindingsCompiler = new BindingsCompiler(); + ISwiftParser swiftParser = new SwiftABIParser(); + var errors = new ErrorHandling(); + var decl = swiftParser.GetModuleDeclaration(swiftAbiPath, errors); - if (!Directory.Exists(outputDirectory)) - { - Console.Error.WriteLine($"Error: Directory '{outputDirectory}' doesn't exist."); - return false; - } + if (verbose > 1) + Console.WriteLine("Parsed Swift ABI file successfully."); - return true; - } + bindingsCompiler.CompileModule(decl, outputDirectory, errors); - public static void GenerateBindings(string dylibPath, string swiftInterfacePath, string outputDirectory, int verbose = 0) - { - BindingsCompiler bindingsCompiler = new BindingsCompiler(); - var errors = new ErrorHandling(); - var moduleInventory = bindingsCompiler.GetModuleInventory(dylibPath, errors); - var moduleDeclarations = bindingsCompiler.GetModuleDeclarations(swiftInterfacePath); - bindingsCompiler.CompileModules(moduleDeclarations, moduleInventory, dylibPath, outputDirectory, errors); + if (verbose > 0) + Console.WriteLine("Bindings generation completed."); } } } diff --git a/src/SwiftBindings/tests/SmokeTests.cs b/src/SwiftBindings/tests/SmokeTests.cs index 2fe72491ae45..29ee18d55d1e 100644 --- a/src/SwiftBindings/tests/SmokeTests.cs +++ b/src/SwiftBindings/tests/SmokeTests.cs @@ -11,7 +11,7 @@ public class SmokeTests [Fact] public void DirectPInvokeVoidVoid() { - BindingsTool.GenerateBindings("libSmokeTests.dylib", "SmokeTests.swiftinterface", ""); + BindingsTool.GenerateBindings("SmokeTests.abi.json", ""); var sourceCode = """ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. diff --git a/src/SwiftReflector/BindingsCompiler.cs b/src/SwiftReflector/BindingsCompiler.cs deleted file mode 100644 index 9171f39604d2..000000000000 --- a/src/SwiftReflector/BindingsCompiler.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Xml; -using System.Xml.Linq; - -using SyntaxDynamo; -using SyntaxDynamo.CSLang; -using SwiftRuntimeLibrary; -using System.Threading.Tasks; -using System.Runtime.InteropServices; - -using SwiftReflector.Inventory; -using SwiftReflector.SwiftXmlReflection; -using SwiftReflector.TypeMapping; - -using SwiftReflector.Demangling; -using SwiftReflector.ExceptionTools; -using SwiftReflector.SwiftInterfaceReflector; - -namespace SwiftReflector -{ - public class BindingsCompiler - { - UnicodeMapper UnicodeMapper; - TypeMapper TypeMapper; - TopLevelFunctionCompiler TLFCompiler; - SwiftInterfaceReflector.SwiftInterfaceReflector Reflector; - - public BindingsCompiler() - { - UnicodeMapper = new UnicodeMapper(); - TypeMapper = new TypeMapper(null, UnicodeMapper); - - TLFCompiler = new TopLevelFunctionCompiler(TypeMapper); - Reflector = new SwiftInterfaceReflector.SwiftInterfaceReflector(null, null); - } - - public ModuleInventory GetModuleInventory(string dylibPath, ErrorHandling errors) - { - var moduleInventory = ModuleInventory.FromFile(dylibPath, errors); - return moduleInventory; - } - - public List GetModuleDeclarations(string swiftinterfacePath) - { - var xdoc = Reflector.Reflect(swiftinterfacePath); - - var outputFile = System.IO.Path.GetTempPath() + Path.GetFileName(swiftinterfacePath) + ".xml"; - xdoc.Save(outputFile); - var moduleDeclarations = SwiftXmlReflection.Reflector.FromXmlFile(outputFile, null); - return moduleDeclarations; - } - - public void CompileModules(List moduleDeclarations, ModuleInventory moduleInventory, - string swiftLibPath, string outputDirectory, - ErrorHandling errors) - { - foreach (ModuleDeclaration module in moduleDeclarations) - { - bool successfulOutput = false; - successfulOutput |= CompileTopLevelEntities(module, moduleInventory, swiftLibPath, outputDirectory, errors); - // successfulOutput |= CompileProtocols (module.Protocols, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileClasses (module.Classes, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileStructs (module.Structs, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileEnums (module.Enums, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - // successfulOutput |= CompileExtensions (module.Extensions, provider, module, moduleInventory, swiftLibPath, outputDirectory, wrapper, errors); - if (!successfulOutput) - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 16, "binding-tools-for-swift could not generate any output. Check the logs and consider using '--verbose' for more information."); - } - } - - bool CompileTopLevelEntities(ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors) - { - var use = new CSUsingPackages("System", "System.Runtime.InteropServices"); - - var picl = new CSClass(CSVisibility.Public, PIClassName(module.Name+"Bindings."+module.Name)); - var usedPinvokes = new List(); - - var cl = CompileTLFuncs(module.TopLevelFunctions, module, moduleInventory, - swiftLibPath, outputDirectory, errors, use, null, picl, usedPinvokes); - - cl = CompileTLProps(module.TopLevelProperties, module, moduleInventory, - swiftLibPath, outputDirectory, errors, use, cl, picl, usedPinvokes); - - - if (picl != null) - { - string nameSpace = TypeMapper.MapModuleToNamespace(module.Name+"Bindings"); - var nm = new CSNamespace(nameSpace); - - var csfile = new CSFile(use, new CSNamespace[] { nm }); - // nm.Block.Add(cl); - nm.Block.Add(picl); - string csOutputFileName = string.Format("{0}.cs", nameSpace); - string csOutputPath = Path.Combine(outputDirectory, csOutputFileName); - - CodeWriter.WriteToFile(csOutputPath, csfile); - - } - else - { - Console.WriteLine("No top-level entities"); - return false; - } - return true; - } - - CSClass CompileTLFuncs(IEnumerable funcs, - ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors, - CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokeNames) - { - var methods = new List(); - - foreach (FunctionDeclaration func in funcs) - { - try - { - if (func.IsProperty) - continue; - - if (func.IsDeprecated || func.IsUnavailable) - continue; - - var tlf = XmlToTLFunctionMapper.ToTLFunction(func, moduleInventory, TypeMapper); - CompileToDirectFunction(func, tlf, "", func.Parent, use, swiftLibPath, methods, picl, usedPinvokeNames, module); - } - catch (Exception e) - { - errors.Add(e); - } - } - - if (methods.Count > 0) - { - // cl = cl ?? new CSClass(CSVisibility.Public, module.Name); - picl.Methods.AddRange(methods); - } - return cl; - } - - void CompileToDirectFunction(FunctionDeclaration func, TLFunction tlf, string homonymSuffix, BaseDeclaration context, - CSUsingPackages use, string swiftLibPath, List methods, CSClass picl, - List usedPinvokeNames, ModuleDeclaration module) - { - // FIXME - need to do operators - if (tlf.Operator != OperatorType.None) - return; - - var baseName = TypeMapper.SanitizeIdentifier(tlf.Name.Name); - var pinvokeMethodName = PIFuncName(baseName + homonymSuffix); - pinvokeMethodName = Uniqueify(pinvokeMethodName, usedPinvokeNames); - usedPinvokeNames.Add(pinvokeMethodName); - - var pinvokeMethodRef = PIClassName($"{func.Module.Name}.{module.Name}") + "." + pinvokeMethodName; - - var piMethod = TLFCompiler.CompileMethod(func, use, PInvokeName(swiftLibPath), - tlf.MangledName, pinvokeMethodName, true, true, false); - picl.Methods.Add(piMethod); - - var publicMethodOrig = TLFCompiler.CompileMethod(func, use, PInvokeName(swiftLibPath), - tlf.MangledName, null, false, false, false); - - CSIdentifier wrapperName = GetMethodWrapperName(func, publicMethodOrig, homonymSuffix); - CSVisibility visibility = GetMethodWrapperVisibility(func, publicMethodOrig); - - // rebuild the method as static - var publicMethod = new CSMethod(visibility, CSMethodKind.Static, publicMethodOrig.Type, - wrapperName, publicMethodOrig.Parameters, publicMethodOrig.Body); - publicMethod.GenericParameters.AddRange(publicMethodOrig.GenericParameters); - publicMethod.GenericConstraints.AddRange(publicMethodOrig.GenericConstraints); - - var localIdents = new List { - publicMethod.Name.Name, pinvokeMethodName - }; - localIdents.AddRange(publicMethod.Parameters.Select(p => p.Name.Name)); - - var marshaler = new MarshalEngine(use, localIdents, TypeMapper, null); - var lines = marshaler.MarshalFunctionCall(func, false, pinvokeMethodRef, publicMethod.Parameters, - func, func.ReturnTypeSpec, publicMethod.Type, null, null, false, func, - false, -1, func.HasThrows); - publicMethod.Body.AddRange(lines); - methods.Add(publicMethod); - } - - CSClass CompileTLProps(IEnumerable props, - ModuleDeclaration module, ModuleInventory moduleInventory, string swiftLibPath, - string outputDirectory, ErrorHandling errors, - CSUsingPackages use, CSClass cl, CSClass picl, List usedPinvokes) - { - var properties = new List(); - - foreach (PropertyDeclaration prop in props) - { - if (prop.IsDeprecated || prop.IsUnavailable) - continue; - try - { - cl = cl ?? new CSClass(CSVisibility.Public, module.Name); - - // Calculated properties have a matching __method - string backingMethodName = ("__" + prop.Name); - CSMethod backingMethod = cl.Methods.FirstOrDefault(x => x.Name.Name == backingMethodName); - } - catch (Exception e) - { - errors.Add(e); - } - } - - if (properties.Count > 0) - { - cl.Properties.AddRange(properties); - } - return cl; - } - - string PIClassName(string fullClassName) - { - if (!fullClassName.Contains('.')) - throw new ArgumentOutOfRangeException(nameof(fullClassName), String.Format("Class name {0} should be a full class name.", fullClassName)); - fullClassName = fullClassName.Substring(fullClassName.IndexOf('.') + 1).Replace('.', '_'); - return fullClassName; - } - - string PIClassName(DotNetName fullClassName) - { - return PIClassName(fullClassName.Namespace + "." + fullClassName.TypeName); - } - - string PIClassName(SwiftClassName name) - { - return PIClassName(TypeMapper.GetDotNetNameForSwiftClassName(name)); - } - - string PIFuncName(SwiftName functionName) - { - return String.Format("PIfunc_{0}", functionName.Name); - } - - string PIFuncName(string functionName) - { - return $"PIfunc_{functionName}"; - } - - CSIdentifier GetMethodWrapperName(FunctionDeclaration func, CSMethod method, string homonymSuffix) - { - string prefix = func.IsProperty ? "__" : ""; - return new CSIdentifier(prefix + method.Name.Name + homonymSuffix); - } - - - CSVisibility GetMethodWrapperVisibility(FunctionDeclaration func, CSMethod method) - { - return func.IsProperty ? CSVisibility.Private : method.Visibility; - } - - static string PInvokeName(string libFullPath, string originalLibrary = null) - { - return LibOrFrameworkFromPath(libFullPath); - } - - static string LibOrFrameworkFromPath(string libFullPath) - { - string directory = Path.GetDirectoryName(libFullPath); - string file = Path.GetFileName(libFullPath); - return file; - } - - public static string Uniqueify(string name, IEnumerable names) - { - int thisTime = 0; - var sb = new StringBuilder(name); - while (names.Contains(sb.ToString())) - { - sb.Clear().Append(name).Append(thisTime++); - } - return sb.ToString(); - } - } -} diff --git a/src/SwiftReflector/CSKeywords.cs b/src/SwiftReflector/CSKeywords.cs deleted file mode 100644 index 1fb7dd374c4e..000000000000 --- a/src/SwiftReflector/CSKeywords.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SwiftRuntimeLibrary; - -namespace SwiftReflector -{ - public class CSKeywords - { - static HashSet keyWords; - static string[] keyArr = new string[] { - "abstract", "as", "base", "bool", "break", "byte", - "case", "catch", "char", "checked", "class", "const", - "continue", "decimal", "default", "delegate", "do", - "double", "else", "enum", "event", "explicit", "extern", - "false", "finally", "fixed", "float", "for", "foreach", - "goto", "if", "implicit", "in", "int", "interface", "internal", - "is", "lock", "long", "namespace", "new", "null", "object", - "operator", "out", "override", "params", "private", "protected", - "public", "readonly", "ref", "return", "sbyte", "sealed", "short", - "sizeof", "stackalloc", "static", "string", "struct", "switch", - "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", - "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", - "add", "alias", "ascending", "async", "await", "descending", "dynamic", - "from", "get", "global", "group", "into", "join", "let", "orderby", - "partial", "remove", "select", "set", "value", "var", "where", "yield" - }; - static CSKeywords() - { - keyWords = new HashSet(); - foreach (string s in keyArr) - { - keyWords.Add(s); - } - } - - public static bool IsKeyword(string s) - { - Exceptions.ThrowOnNull(s, "s"); - return keyWords.Contains(s); - } - } -} - diff --git a/src/SwiftReflector/Demangling/ContextAttribute.cs b/src/SwiftReflector/Demangling/ContextAttribute.cs deleted file mode 100644 index 1cda5d13a059..000000000000 --- a/src/SwiftReflector/Demangling/ContextAttribute.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SwiftReflector.Demangling -{ - [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] - public class ContextAttribute : Attribute - { - } -} diff --git a/src/SwiftReflector/Demangling/Decomposer.cs b/src/SwiftReflector/Demangling/Decomposer.cs deleted file mode 100644 index 8cbb9750c46b..000000000000 --- a/src/SwiftReflector/Demangling/Decomposer.cs +++ /dev/null @@ -1,1262 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SwiftReflector.ExceptionTools; -using System.Text; - -namespace SwiftReflector.Demangling -{ - public class Decomposer - { - const string kSwiftID = "__T"; - public const string kSwift4xID = "_$s"; - public const string kSwift5ID = "_$S"; - public static SwiftName kSwiftAllocatingConstructorName = new SwiftName(".ctor", false); - public static SwiftName kSwiftNonAllocatingConstructorName = new SwiftName(".nctor", false); - public static SwiftName kSwiftClassConstructorName = new SwiftName(".cctor", false); - public static SwiftName kSwiftDeallocatingDestructorName = new SwiftName(".dtor", false); - public static SwiftName kSwiftNonDeallocatingDestructorName = new SwiftName(".ndtor", false); - public static SwiftName kSwiftWitnessTableName = new SwiftName(".wtable", false); - public static SwiftName kSwiftValueWitnessTableName = new SwiftName(".vwtable", false); - public static SwiftName kSwiftProtocolWitnessTableName = new SwiftName(".pwtable", false); - public static SwiftName kSwiftProtocolWitnessTableAccessorName = new SwiftName(".pwtablea", false); - - List subs = new List(); - - List classes = new List(); - int position; - StringSlice slice; - string originalID; - SwiftName thisModule; - bool isOldVersion; - ulong offset; - - - Decomposer(string swiftIdentifier, bool isOldVersion, ulong offset) - { - if (swiftIdentifier == null) - throw new ArgumentNullException(nameof(swiftIdentifier)); - if (swiftIdentifier.Length == 0) - throw new ArgumentException("swiftname is empty", nameof(swiftIdentifier)); - originalID = swiftIdentifier; - this.isOldVersion = isOldVersion; - this.offset = offset; - } - - int MarkOperatorPosition() - { - position = slice.Position; - return position; - } - - void Fail(string expected, string butGot = null) - { - if (butGot == null) - { - butGot = slice.IsAtEnd ? "nothing at end of string" : slice.Current.ToString(); - } - var message = $"Error decomposing {slice.Original} at position {slice.Position}: expected {expected}, but got {butGot}"; - throw ErrorHelper.CreateError(ReflectorError.kDecomposeBase + 1, message); - } - - void Initialize() - { - thisModule = null; - classes.Clear(); - slice = new StringSlice(originalID); - MarkOperatorPosition(); - } - - public static TLDefinition Decompose(string swiftIdentifier, bool isOldVersion, ulong offset = 0) - { - if (swiftIdentifier.StartsWith(kSwift4xID, StringComparison.Ordinal) || - swiftIdentifier.StartsWith(kSwift5ID, StringComparison.Ordinal)) - { - var demangler5 = new Swift5Demangler(swiftIdentifier, offset); - return demangler5.Run(); - } - else - { - Decomposer decomp = new Decomposer(swiftIdentifier, isOldVersion, offset); - return decomp.Run(); - } - } - - public TLDefinition Run() - { - Initialize(); - - RemoveSwiftID(); - - char c = slice.Advance(); - switch (c) - { - case 'Z': - if (slice.AdvanceIfEquals('F')) - { - return ToFunction(true, false); - } - else if (slice.AdvanceIfEquals('v')) - { - return ToVariable(true); - } - else - { - Fail("a static function (F)"); - } - break; - case 'F': - return ToFunction(false, false); - case 'M': - return ToMetadata(); - case 'W': - return ToWitnessTable(); - case 'v': - return ToVariable(false); - case 'T': - return ToThunk(); - case 'I': - return ToInitializer(); - default: - Fail("one of Z, F, M, v, T, I or W", c.ToString()); - break; - } - return null; - } - - void RemoveSwiftID() - { - if (!slice.StartsWith(kSwiftID)) - Fail("Swift symbol (__T)", slice.Original.Substring(0, Math.Min(3, slice.Original.Length))); - slice.Advance(kSwiftID.Length); - } - - SwiftName GetModule() - { - return slice.ExtractSwiftName(); - } - - public static MemberNesting? ToMaybeMemberNesting(char c, bool throwOnFail) - { - switch (c) - { - case 'C': - return MemberNesting.Class; - case 'V': - return MemberNesting.Struct; - case 'O': - return MemberNesting.Enum; - case 'P': - return MemberNesting.Protocol; - default: - if (throwOnFail) - throw new ArgumentOutOfRangeException(nameof(c)); - return null; - } - } - - MemberNesting ToMemberNesting(char c) - { - MemberNesting? nesting = ToMaybeMemberNesting(c, false); - if (!nesting.HasValue) - { - Fail("either a struct, class, enum, or protocol nesting marker (C, V, O, or P)"); - } - return nesting.Value; - } - - MemberType ToMemberType(char c) - { - switch (c) - { - case 'C': - return MemberType.Allocator; - case 'c': - return MemberType.Constructor; - case 'D': - return MemberType.Deallocator; - case 'd': - return MemberType.Destructor; - case 'f': - return MemberType.UncurriedFunction; - case 'F': - return MemberType.Function; - case 'g': - return MemberType.Getter; - case 's': - return MemberType.Setter; - default: - Fail("a member type marker (one of C, c, D, d, F, f, g, or s"); - return MemberType.Allocator; // never hit, thanks C#, you're the best - } - } - - CoreBuiltInType ToCoreScalar(char c) - { - switch (c) - { - case 'b': - return CoreBuiltInType.Bool; - case 'd': - return CoreBuiltInType.Double; - case 'f': - return CoreBuiltInType.Float; - case 'i': - return CoreBuiltInType.Int; - case 'u': - return CoreBuiltInType.UInt; - default: - Fail("a core type marker (one of b, d, f, i, or u)"); - return CoreBuiltInType.Bool; // never hit, thanks C#, you're the best - } - } - - IList GetNesting() - { - Stack st = new Stack(); - while (!Char.IsDigit(slice.Current)) - { - MarkOperatorPosition(); - st.Push(ToMemberNesting(slice.Advance())); - } - return st.ToList(); - } - - IList GetNestingAlt() - { - Stack st = new Stack(); - while (!slice.StartsWith('S') && !slice.StartsWith('s') && !Char.IsDigit(slice.Current)) - { - MarkOperatorPosition(); - st.Push(ToMemberNesting(slice.Advance())); - } - return st.ToList(); - } - - IList GetNestingNames(int expected) - { - List names = new List(expected); - for (int i = 0; i < expected; i++) - { - MarkOperatorPosition(); - SwiftName sw = slice.ExtractSwiftName(); - if (sw == null) - Fail(String.Format("{0} nested class names", expected)); - names.Add(sw); - } - return names; - } - - SwiftClassName ReadProtocolName() - { - MarkOperatorPosition(); - // module? - IList nesting = new List { MemberNesting.Protocol }; - - SwiftType st = ReadContext(); - SwiftClassType ct = st as SwiftClassType; - if (ct == null) - { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail("SwiftModuleNameType", st.GetType().Name); - ct = new SwiftClassType(new SwiftClassName(mod.Name, new List(), new List()), false, null); - } - - - IList nestingNames = GetNestingNames(nesting.Count); - return new SwiftClassName(ct.ClassName.Module, nesting, nestingNames); - } - - SwiftClassName CombineContextAndName(SwiftType context, SwiftName terminus, MemberNesting nesting, OperatorType oper) - { - if (context is SwiftModuleNameType) - { - return new SwiftClassName(context.Name, new List { nesting }, - new List { terminus }); - } - if (context is SwiftClassType) - { - SwiftClassType ct = context as SwiftClassType; - List newnesting = new List(); - newnesting.AddRange(ct.ClassName.Nesting); - newnesting.Add(nesting); - List newnames = new List(); - newnames.AddRange(ct.ClassName.NestingNames); - newnames.Add(terminus); - return new SwiftClassName(ct.ClassName.Module, newnesting, newnames, oper); - } - Fail("a SwiftModuleNameType or a SwiftClassType", context.GetType().Name); - return null; // never reached - thanks C# - } - - SwiftClassName ReadClassStructEnumNameAlt() - { - if (!slice.StartsWith('C') && !slice.StartsWith('V') && !slice.StartsWith('O')) - Fail("class, struct, or enum markers (C, V, or O)"); - MarkOperatorPosition(); - - MemberNesting nesting = ToMemberNesting(slice.Advance()); - SwiftType context = ReadContext(); - OperatorType oper = OperatorType.None; - SwiftName name = slice.ExtractSwiftNameMaybeOperator(out oper); - SwiftClassName className = CombineContextAndName(context, name, nesting, oper); - return className; - } - - public SwiftClassType ReadClassStructOrEnum(SwiftName name, bool isReference) - { - if (!slice.StartsWith('C') && !slice.StartsWith('V') && !slice.StartsWith('O')) - Fail("class, struct, or enum markers (C, V, or O)"); - MarkOperatorPosition(); - SwiftClassName cn = ReadClassStructEnumNameAlt(); - SwiftClassType ct = new SwiftClassType(cn, isReference, name); - subs.Add(ct); - return ct; - } - - - SwiftType ReadContext() - { - if (slice.Current == 'S') - { - return DemangleSubstitution(null, false); - } - if (slice.AdvanceIfEquals('s')) - { - return new SwiftModuleNameType(new SwiftName("Swift", false), false); - } - if (slice.StartsWith('C') || slice.StartsWith('V') || slice.StartsWith('O')) - { - return ReadClassStructOrEnum(null, false); - } - SwiftName module = GetModule(); - SwiftModuleNameType modName = new SwiftModuleNameType(module, false); - subs.Add(modName); - return modName; - } - - - TLDefinition ToMetadata() - { - MarkOperatorPosition(); - // current version doesn't use 'd', but is implicit - - - char c = (slice.Current == 'C' || slice.Current == 'V' || slice.Current == 'O') ? 'd' : slice.Advance(); - SwiftClassName className = c != 'p' ? ReadClassStructEnumNameAlt() : ReadProtocolName(); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType(className, false); - subs.Add(cl); - - switch (c) - { - case 'a': - return new TLFunction(slice.Original, thisModule, kSwiftClassConstructorName, cl, - new SwiftClassConstructorType(new SwiftMetaClassType(cl, false), false), offset); - case 'L': - return new TLLazyCacheVariable(slice.Original, thisModule, cl, offset); - case 'd': - return new TLDirectMetadata(slice.Original, thisModule, cl, offset); - case 'm': - return new TLMetaclass(slice.Original, thisModule, cl, offset); - case 'n': - return new TLNominalTypeDescriptor(slice.Original, thisModule, cl, offset); - case 'p': - return new TLProtocolTypeDescriptor(slice.Original, thisModule, cl, offset); - case 'P': - return new TLGenericMetadataPattern(slice.Original, thisModule, cl, offset); - default: - Fail("a metaclass descriptor (a, L, d, m, or n, p)", c.ToString()); - return null; - } - } - - TLVariable ToVariable(bool isStatic) - { - MarkOperatorPosition(); - SwiftType st = ReadContext(); - SwiftClassType cl = st as SwiftClassType; - if (cl == null) - { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail("a SwiftModuleType", st.GetType().Name); - cl = new SwiftClassType(new SwiftClassName(mod.Name, new List(), - new List()), false); - } - SwiftName module = cl.ClassName.Module; - if (cl.ClassName.Nesting.Count == 0) - cl = null; - SwiftName varName = slice.ExtractSwiftName(); - SwiftType ofType = ReadType(false); - return new TLVariable(slice.Original, module, cl, varName, ofType, isStatic, offset); - } - - TLThunk ToThunk() - { - MarkOperatorPosition(); - ThunkType thunkType = ToThunkType(); - SwiftClassName className = ReadClassStructEnumNameAlt(); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType(className, false); - return new TLThunk(thunkType, slice.Original, thisModule, cl, offset); - } - - ThunkType ToThunkType() - { - char c = slice.Advance(); - switch (c) - { - case 'R': - return ThunkType.ReabstractionHelper; - case 'r': - return ThunkType.Reabstraction; - case 'W': - return ThunkType.ProtocolWitness; - default: - Fail("a thunk type marker, one of R, r, or W", c.ToString()); - return ThunkType.ProtocolWitness; // can't happen - } - } - - TLDefinition ToInitializer() - { - MarkOperatorPosition(); - if (slice.AdvanceIfEquals('v')) - { - return ToInitializer(InitializerType.Variable); - } - else - { - Fail("expected a variable initializer marker (v)"); - return null; // stupid compile - } - } - - TLDefinition ToInitializer(InitializerType type) - { - SwiftType readType = ReadContext(); - SwiftClassType owner = readType as SwiftClassType; - if (owner == null) - Fail("SwiftClassType", readType.GetType().Name); - thisModule = owner.ClassName.Module; - - SwiftName varName = slice.ExtractSwiftName(); - SwiftType varType = ReadType(false); - return new TLFunction(slice.Original, thisModule, - varName, owner, - new SwiftInitializerType(InitializerType.Variable, varType, owner, varName), - offset); - } - - - TLDefinition ToWitnessTable() - { - MarkOperatorPosition(); - if (slice.StartsWith('v')) - return ToFieldOffset(); - if (slice.StartsWith('V')) - return ToValueWitnessTable(); - if (slice.StartsWith('P')) - return ToProtocolWitnessTable(); - if (slice.StartsWith('a')) - return ToProtocolWitnessTableAccessor(); - if (!slice.AdvanceIfEquals('o')) - Fail("expected witness table offset marker (o)"); - if (!slice.AdvanceIfEquals('F')) - Fail("expected a function marker (F) after witness table offset"); - - SwiftClassName className = ReadClassStructEnumNameAlt(); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType(className, false); - subs.Add(cl); - - MarkOperatorPosition(); - - // A witness table is not strictly a function, but the overall structure of its descriptor - // matches an uncurried function closely enough that we can make it pass for one. - // The consuming code doesn't care and pulls it out as is. - SwiftWitnessTableType wit = new SwiftWitnessTableType(WitnessType.Class); - - TLFunction func = new TLFunction(slice.Original, thisModule, null, cl, wit, offset); - return func; - } - - TLDefinition ToValueWitnessTable() - { - return ToWitnessFoo('V', "value witness table", WitnessType.Value); - } - - TLDefinition ToProtocolWitnessTable() - { - return ToWitnessFoo('P', "protocol witness table", WitnessType.Protocol); - } - - TLDefinition ToProtocolWitnessTableAccessor() - { - return ToWitnessFoo('a', "protocol witness table accessor", WitnessType.ProtocolAccessor); - } - - TLDefinition ToWitnessFoo(char marker, string descriptor, WitnessType witnessType) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals(marker)) - Fail(String.Format("{0} marker ({1})", descriptor, marker)); - - SwiftClassName className = ReadClassStructEnumNameAlt(); - if (className.Module != null && thisModule == null) - thisModule = className.Module; - - SwiftClassType cl = new SwiftClassType(className, false); - subs.Add(cl); - - - SwiftClassName protoName = witnessType == WitnessType.Protocol ? ReadProtocolName() : null; - SwiftClassType proto = protoName != null ? new SwiftClassType(protoName, false) : null; - - MarkOperatorPosition(); - // this is likely wrong, but it's less wrong than it was - SwiftWitnessTableType witf = new SwiftWitnessTableType(witnessType, proto); - TLFunction func = new TLFunction(slice.Original, thisModule, null, cl, witf, offset); - return func; - } - - TLDefinition ToFieldOffset() - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('v')) - Fail("a field offset marker (v)"); - if (!(slice.StartsWith('d') || slice.StartsWith('i'))) - Fail("a direct or indirect marker (d, i)"); - bool direct = slice.StartsWith('d'); - slice.Advance(); - - slice.Advance(); - - SwiftClassType cl = ReadType(false) as SwiftClassType; - if (cl == null) - Fail("a class descriptor"); - thisModule = cl.ClassName.Module; - - SwiftName ident = slice.ExtractSwiftName(); - SwiftType type = ReadType(false); - - return new TLFieldOffset(slice.Original, thisModule, cl, direct, ident, type, offset); - } - - - TLFunction ToFunction(bool isStatic, bool isReference) - { - MarkOperatorPosition(); - if (slice.StartsWith('F')) - { - return ReadExplicitClosure(isReference); - } - - SwiftType st = ReadContext(); - SwiftClassType cl = st as SwiftClassType; - if (cl == null) - { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail("a SwiftModuleType", st.GetType().Name); - cl = new SwiftClassType(new SwiftClassName(mod.Name, new List(), - new List()), false); - } - - MarkOperatorPosition(); - OperatorType oper = OperatorType.None; - SwiftName functionName = slice.ExtractSwiftNameMaybeOperator(out oper); - - - SwiftBaseFunctionType baseFunc = null; - - switch (slice.Current) - { - case 'C': - baseFunc = ReadAllocatorType(isReference); - break; - case 'c': - baseFunc = ReadConstructorType(isReference); - break; - case 'D': - baseFunc = new SwiftDestructorType(true, cl, isReference, false); - break; - case 'd': - baseFunc = new SwiftDestructorType(false, cl, isReference, false); - break; - case 'g': - baseFunc = ReadGetter(cl, isStatic, isReference); - break; - case 's': - baseFunc = ReadSetter(cl, isStatic, isReference); - break; - case 'm': - baseFunc = ReadMaterializer(cl, isStatic, isReference); - break; - case 'a': - baseFunc = ReadAddressorMutable(cl, isReference); - break; - case 'l': - baseFunc = ReadAddressor(cl, isReference); - break; - default: - baseFunc = ReadType(isReference) as SwiftBaseFunctionType; - if (isStatic && baseFunc is SwiftUncurriedFunctionType) - { - SwiftUncurriedFunctionType ucf = baseFunc as SwiftUncurriedFunctionType; - baseFunc = new SwiftStaticFunctionType(ucf.Parameters, ucf.ReturnType, ucf.IsReference, ucf.CanThrow, ucf.UncurriedParameter as SwiftClassType, ucf.Name); - } - break; - } - - - if (baseFunc == null) - Fail("a function"); - - functionName = functionName ?? baseFunc.Name; - - if (functionName == null) - throw new ArgumentNullException("blah"); - - return new TLFunction(slice.Original, cl.ClassName.Module, functionName, cl, baseFunc, offset, oper); - } - - SwiftType ReadType(bool isReference, SwiftName name = null) - { - name = slice.IsNameNext ? slice.ExtractSwiftName() : name; - char t = slice.Current; - MarkOperatorPosition(); - switch (t) - { - case 'f': - return ReadUncurriedFunctionType(name, isReference, subs.Last() as SwiftClassType); - - case 'F': - return ReadFunctionType(name, isReference); - case 'c': - return ReadCFunctionType(name, isReference); - case 'G': - return ReadBoundGenericType(name, isReference); - case 'S': - return DemangleSubstitution(name, isReference); - case 'V': - case 'C': - case 'O': - return ReadClassOrStructOrEnum(name, isReference); - case 'P': - return ReadProtocolList(name, isReference); - case 'M': - return ReadMetaClassType(name, isReference); - case 'R': - slice.Advance(); - return ReadType(true, name); - case 'T': - return ReadTupleType(name, isReference); - case 'u': - return ReadUnboundGenericType(name, isReference); - case 'x': - slice.Advance(); - return new SwiftGenericArgReferenceType(0, 0, isReference, name); - case 'q': - return ReadGenericReferenceType(name, isReference); - default: - Fail("a type marker (one of F, G, S, V, C, O, M, R, T, u, x, or q)"); - return null; - } - } - - TLFunction ReadExplicitClosure(bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('F')) - Fail("an explicit closure marker (F)"); - - SwiftClassType st = ReadType(isReference) as SwiftClassType; - if (st == null) - Fail("a class type"); - return new TLFunction(slice.Original, st.ClassName.Module, st.Name, st, new SwiftExplicitClosureType(isReference), offset); - } - - SwiftUncurriedFunctionType ReadUncurriedFunctionType(SwiftName name, bool isReference, SwiftType implicitType) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('f')) - Fail("an uncurried function type (f)"); - bool canThrow = slice.AdvanceIfEquals('z'); - if (isOldVersion) - { - SwiftType uncurriedParamType = ReadType(false); - SwiftFunctionType func = ReadFunctionType(null, false); - return new SwiftUncurriedFunctionType(uncurriedParamType, func.Parameters, func.ReturnType, isReference, canThrow, name); - } - else - { - SwiftType args = ReadType(false); - SwiftType ret = ReadType(false); - return new SwiftUncurriedFunctionType(implicitType, args, ret, isReference, canThrow, name); - } - } - - SwiftConstructorType ReadAllocOrCons(bool isAllocator, char advanceOn, string expected, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals(advanceOn)) - Fail(expected); - SwiftUncurriedFunctionType ucf = ReadUncurriedFunctionType(null, false, new SwiftMetaClassType(subs.Last() as SwiftClassType, false, null)); - return new SwiftConstructorType(isAllocator, ucf.UncurriedParameter, ucf.Parameters, ucf.ReturnType, isReference, ucf.CanThrow); - } - - SwiftAddressorType ReadAddressorMutable(SwiftClassType cl, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('a')) - Fail("an addressor"); - AddressorType theType = AddressorType.UnsafeMutable; - char c = slice.Advance(); - switch (c) - { - case 'O': - theType = AddressorType.OwningMutable; - break; - case 'o': - theType = AddressorType.NativeOwningMutable; - break; - case 'p': - theType = AddressorType.NativePinningMutable; - break; - case 'u': - theType = AddressorType.UnsafeMutable; - break; - default: - Fail("one of O, o, p, or u", c.ToString()); - break; - } - if (!slice.IsNameNext) - Fail("a swift name"); - SwiftName addressorName = slice.ExtractSwiftName(); - SwiftType ofType = ReadType(true); // addressors return the address of the entity - return new SwiftAddressorType(theType, ofType, isReference, addressorName); - } - - SwiftAddressorType ReadAddressor(SwiftClassType cl, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('l')) - Fail("an addressor"); - AddressorType theType = AddressorType.UnsafeMutable; - char c = slice.Advance(); - switch (c) - { - case 'O': - theType = AddressorType.Owning; - break; - case 'o': - theType = AddressorType.NativeOwning; - break; - case 'p': - theType = AddressorType.NativePinning; - break; - case 'u': - theType = AddressorType.Unsafe; - break; - default: - Fail("one of O, o, p, or u", c.ToString()); - break; - } - if (!slice.IsNameNext) - Fail("a swift name"); - SwiftName addressorName = slice.ExtractSwiftName(); - SwiftType ofType = ReadType(true); // addressors return the address of the entity - return new SwiftAddressorType(theType, ofType, isReference, addressorName); - } - - SwiftPropertyType ReadGetter(SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('g')) - Fail("a property getter (g)"); - return ReadProperty(cl, PropertyType.Getter, isStatic, isReference); - } - - SwiftPropertyType ReadSetter(SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('s')) - Fail("a property setter"); - return ReadProperty(cl, PropertyType.Setter, isStatic, isReference); - } - - SwiftPropertyType ReadMaterializer(SwiftClassType cl, bool isStatic, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('m')) - Fail("a property materializer"); - return ReadProperty(cl, PropertyType.Materializer, isStatic, isReference); - } - - SwiftPropertyType ReadProperty(SwiftClassType cl, PropertyType propType, bool isStatic, bool isReference) - { - SwiftName privateName = null; - MarkOperatorPosition(); - if (slice.AdvanceIfEquals('P')) - privateName = slice.ExtractSwiftName(); - MarkOperatorPosition(); - if (!slice.IsNameNext) - Fail("a swift name"); - SwiftName propName = slice.ExtractSwiftName(); - - if (IsSubscript(propName)) - { - SwiftType subscriptType = ReadType(false); - SwiftBaseFunctionType subscriptFunc = subscriptType as SwiftBaseFunctionType; - if (subscriptFunc == null) - Fail("a function type in an indexed property", subscriptType.GetType().Name); - - if (propType == PropertyType.Setter && subscriptFunc.ReturnType != null && !subscriptFunc.ReturnType.IsEmptyTuple) - { - // oh hooray! - // If I define an indexer in swift like this: - // public subscript(T index) -> U { - // get { return getSomeUValue(index); } - // set (someUValue) { setSomeUValue(index, someUValue); } - // } - // This signature of the function attached to both properties is: - // T -> U - // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but - // the setter is (T, U) -> void - // - // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect - // what's really happening. - - // need to change this so that the tail parameters get names? Maybe just the head? - - SwiftTupleType newParameters = subscriptFunc.ParameterCount == 1 ? - new SwiftTupleType(false, null, subscriptFunc.ReturnType, - subscriptFunc.Parameters.RenamedCloneOf(new SwiftName(subscriptFunc.ReturnType.Name == null || - subscriptFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) - : new SwiftTupleType(Enumerable.Concat(subscriptFunc.ReturnType.Yield(), subscriptFunc.EachParameter), - false, null); - subscriptFunc = new SwiftFunctionType(newParameters, SwiftTupleType.Empty, false, subscriptFunc.CanThrow, subscriptFunc.Name); - } - return new SwiftPropertyType(cl, propType, propName, privateName, (SwiftFunctionType)subscriptFunc, isStatic, isReference); - - } - else - { - SwiftType ofType = ReadType(false); - - return new SwiftPropertyType(cl, propType, propName, privateName, ofType, isStatic, isReference); - } - } - - public static bool IsSubscript(SwiftName name) - { - return name.Name == "subscript"; - } - - SwiftConstructorType ReadAllocatorType(bool isReference) - { - return ReadAllocOrCons(true, 'C', "an allocating constructor (C)", isReference); - } - - SwiftConstructorType ReadConstructorType(bool isReference) - { - return ReadAllocOrCons(false, 'c', "a non-allocating constructor (c)", isReference); - } - - SwiftType ReadProtocolList(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('P')) - Fail("A protocol list marker ('P')"); - if (slice.Current == 'M') - { - return ReadExistentialMetatype(name, isReference); - } - List protocols = new List(); - while (slice.Current != '_') - { - SwiftClassName className = ReadProtocolName(); - SwiftClassType theProtocol = new SwiftClassType(className, false, null); - subs.Add(theProtocol); - protocols.Add(theProtocol); - } - slice.Advance(); - return new SwiftProtocolListType(protocols, isReference, name); - } - - SwiftClassType ReadClassOrStructOrEnum(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - SwiftClassName className = ReadClassStructEnumNameAlt(); - SwiftClassType clType = new SwiftClassType(className, isReference, name); - subs.Add(clType); - return clType; - } - - SwiftMetaClassType ReadMetaClassType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('M')) - Fail("a metaclass marker (M)"); - SwiftClassType cl = ReadType(false) as SwiftClassType; - if (cl == null) - Fail("a class type"); - return new SwiftMetaClassType(cl, isReference, name); - } - - SwiftExistentialMetaType ReadExistentialMetatype(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('M')) - Fail("a metaclass marker (M)"); - SwiftProtocolListType pl = ReadType(false) as SwiftProtocolListType; - if (pl == null) - Fail("a protocol list type"); - return new SwiftExistentialMetaType(pl, isReference, name); - } - - - SwiftType ReadUnboundGenericType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('u')) - Fail("an unbound generic type (u)"); - MarkOperatorPosition(); - List parms = ReadGenericArguments(); - SwiftType dependentType = ReadType(isReference, name); - SwiftBaseFunctionType bft = dependentType as SwiftBaseFunctionType; - if (bft != null) - { - bft.GenericArguments.AddRange(parms); - return bft; - } - return new SwiftUnboundGenericType(dependentType, parms, isReference, dependentType.Name); - } - - - List ReadGenericArguments() - { - int count = 0; - while (slice.Current != 'R' && slice.Current != 'r') - { - count = DemangleIndex(); - } - count += 1; - List args = new List(count); - for (int i = 0; i < count; i++) - { - args.Add(new GenericArgument(0, i)); - } - if (slice.AdvanceIfEquals('r')) - return args; - if (!slice.AdvanceIfEquals('R')) - Fail("A generic argument requirements marker (R)"); - while (!slice.AdvanceIfEquals('r')) - { - int depth = 0; - int index = 0; - if (slice.AdvanceIfEquals('d')) - { - depth = DemangleIndex(); - index = DemangleIndex(); - } - else if (slice.AdvanceIfEquals('x')) - { - // no change - } - else - { - index = DemangleIndex() + 1; - } - if (slice.StartsWith('C')) - { - SwiftType constraintType = ReadType(false, null); - args[index].Constraints.Add(constraintType); - } - else - { - SwiftClassName className = ReadProtocolName(); - SwiftClassType theProtocol = new SwiftClassType(className, false, null); - args[index].Constraints.Add(theProtocol); - } - args[index].Depth = depth; - } - // currently swift name mangling is done incorrectly to get the actual - // depth. In the case where there is a 'where' clause, we can figure it out - // and correct it. - int maxDepth = 0; - foreach (GenericArgument gen in args) - { - maxDepth = Math.Max(maxDepth, gen.Depth); - } - foreach (GenericArgument gen in args) - { - gen.Depth = maxDepth; - } - return args; - } - - SwiftGenericArgReferenceType ReadGenericReferenceType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('q')) - Fail("a generic argument reference"); - MarkOperatorPosition(); - int depth = 0; - int index = 0; - if (slice.AdvanceIfEquals('d')) - { - depth = DemangleIndex() + 1; - index = DemangleIndex() + 1; - } - else - { - index = DemangleIndex() + 1; - } - return new SwiftGenericArgReferenceType(depth, index, isReference, name); - } - - SwiftBoundGenericType ReadBoundGenericType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('G')) - Fail("a bound generic type (G)"); - MarkOperatorPosition(); - SwiftType baseType = ReadType(false); - - List generics = new List(); - while (!slice.AdvanceIfEquals('_')) - { - MarkOperatorPosition(); - SwiftType t = ReadType(false); - if (t != null) - generics.Add(t); - } - return new SwiftBoundGenericType(baseType, generics, isReference, name); - } - - SwiftArrayType ReadArrayType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('S') || !slice.AdvanceIfEquals('a')) - Fail("an Array type (Sa)"); - return new SwiftArrayType(isReference, name); - } - - SwiftFunctionType ReadFunctionType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('F')) - Fail("a function marker (F)"); - bool canThrow = slice.AdvanceIfEquals('z'); - SwiftType parms = ReadType(false); - SwiftType ret = ReadType(false); - return new SwiftFunctionType(parms, ret, isReference, canThrow, name); - } - - SwiftCFunctionType ReadCFunctionType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('c')) - Fail("a C function marker (c)"); - SwiftType parms = ReadType(false); - SwiftType ret = ReadType(false); - return new SwiftCFunctionType(parms, ret, isReference, name); - } - - SwiftType ReadScalarType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('S')) - Fail("a core built in type marker (S)"); - if (slice.Current == 'S') - { - slice.Advance(); - return ClassForBuiltInType(name, "String", MemberNesting.Struct, isReference); - } - else if (slice.Current == 'q') - { - slice.Advance(); - return ClassForBuiltInType(name, "Optional", MemberNesting.Enum, isReference); - } - else if (slice.Current == 'Q') - { - slice.Advance(); - return ClassForBuiltInType(name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); - } - else if (slice.Current == 'P') - { - slice.Advance(); - return ClassForBuiltInType(name, "UnsafePointer", MemberNesting.Struct, isReference); - } - else if (slice.Current == 'p') - { - slice.Advance(); - return ClassForBuiltInType(name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); - } - else if (slice.Current == 'R') - { - slice.Advance(); - return ClassForBuiltInType(name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); - } - else if (slice.Current == 'r') - { - slice.Advance(); - return ClassForBuiltInType(name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); - } - else - { - CoreBuiltInType scalarType = ToCoreScalar(slice.Advance()); - return new SwiftBuiltInType(scalarType, isReference, name); - } - } - - SwiftTupleType ReadTupleType(SwiftName name, bool isReference) - { - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('T')) - Fail("a tuple marker (T)"); - - List contents = new List(); - while (!slice.AdvanceIfEquals('_')) - { - MarkOperatorPosition(); - SwiftType ty = ReadType(false); - contents.Add(ty); - } - return new SwiftTupleType(contents, isReference, name); - } - - static SwiftClassType ClassForBuiltInType(SwiftName name, string className, MemberNesting nesting, bool isReference) - { - return new SwiftClassType(new SwiftClassName(new SwiftName("Swift", false), - new List { nesting }, - new List { new SwiftName(className, false) }), isReference, name); - } - - SwiftType DemangleSubstitution(SwiftName name, bool isReference) - { - if (!slice.AdvanceIfEquals('S')) - Fail("a core built in type marker (S)"); - if (slice.AdvanceIfEquals('a')) - { - return ClassForBuiltInType(name, "Array", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('c')) - { - return ClassForBuiltInType(name, "UnicodeScalar", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('S')) - { - return ClassForBuiltInType(name, "String", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('q')) - { - return ClassForBuiltInType(name, "Optional", MemberNesting.Enum, isReference); - } - if (slice.AdvanceIfEquals('Q')) - { - return ClassForBuiltInType(name, "ImplicitlyUnwrappedOptional", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('P')) - { - return ClassForBuiltInType(name, "UnsafePointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('p')) - { - return ClassForBuiltInType(name, "UnsafeMutablePointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('R')) - { - return ClassForBuiltInType(name, "UnsafeBufferPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('r')) - { - return ClassForBuiltInType(name, "UnsafeMutableBufferPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('V')) - { - return ClassForBuiltInType(name, "UnsafeRawPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('v')) - { - return ClassForBuiltInType(name, "UnsafeMutableRawPointer", MemberNesting.Struct, isReference); - } - if (slice.AdvanceIfEquals('b')) - { - return new SwiftBuiltInType(CoreBuiltInType.Bool, isReference, name); - } - if (slice.AdvanceIfEquals('d')) - { - return new SwiftBuiltInType(CoreBuiltInType.Double, isReference, name); - } - if (slice.AdvanceIfEquals('f')) - { - return new SwiftBuiltInType(CoreBuiltInType.Float, isReference, name); - } - if (slice.AdvanceIfEquals('i')) - { - return new SwiftBuiltInType(CoreBuiltInType.Int, isReference, name); - } - if (slice.AdvanceIfEquals('u')) - { - return new SwiftBuiltInType(CoreBuiltInType.UInt, isReference, name); - } - if (slice.AdvanceIfEquals('s')) - { - return new SwiftModuleNameType(new SwiftName("Swift", false), isReference); - } - int index = DemangleIndex(); - SwiftType st = subs[index]; - SwiftClassType sct = st as SwiftClassType; - if (sct == null) - { - SwiftModuleNameType mod = st as SwiftModuleNameType; - if (mod == null) - Fail("a SwiftModuleNameType", st.GetType().Name); - return mod; - } - return new SwiftClassType(sct.ClassName, isReference, name); - } - - int DemangleIndex() - { - if (slice.AdvanceIfEquals('_')) - { - return 0; - } - MarkOperatorPosition(); - if (!Char.IsDigit(slice.Current)) - Fail("a number", slice.Current.ToString()); - int index = ReadNumber(); - MarkOperatorPosition(); - if (!slice.AdvanceIfEquals('_')) - Fail("a macro terminator '-'", slice.Current.ToString()); - return index + 1; - } - - int ReadNumber() - { - int number = 0; - while (Char.IsDigit(slice.Current)) - { - number = 10 * number + slice.Current - '0'; - slice.Advance(); - } - return number; - } - } -} - diff --git a/src/SwiftReflector/Demangling/Enums.cs b/src/SwiftReflector/Demangling/Enums.cs deleted file mode 100644 index f6a630b886b4..000000000000 --- a/src/SwiftReflector/Demangling/Enums.cs +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -namespace SwiftReflector.Demangling -{ - public enum NodeKind - { - [Context] - Allocator, - [Context] - AnonymousContext, - AnyProtocolConformanceList, - ArgumentTuple, - AssociatedType, - AssociatedTypeRef, - AssociatedTypeMetadataAccessor, - DefaultAssociatedTypeMetadataAccessor, - AssociatedTypeWitnessTableAccessor, - BaseWitnessTableAccessor, - AutoClosureType, - BoundGenericClass, - BoundGenericEnum, - BoundGenericStructure, - BoundGenericProtocol, - BoundGenericOtherNominalType, - BoundGenericTypeAlias, - BoundGenericFunction, - BuiltinTypeName, - CFunctionPointer, - [Context] - Class, - ClassMetadataBaseOffset, - ConcreteProtocolConformance, - [Context] - Constructor, - CoroutineContinuationPrototype, - [Context] - Deallocator, - DeclContext, - [Context] - DefaultArgumentInitializer, - DependentAssociatedConformance, - DependentAssociatedTypeRef, - DependentGenericConformanceRequirement, - DependentGenericParamCount, - DependentGenericParamType, - DependentGenericSameTypeRequirement, - DependentGenericLayoutRequirement, - DependentGenericSignature, - DependentGenericType, - DependentMemberType, - DependentPseudogenericSignature, - DependentProtocolConformanceRoot, - DependentProtocolConformanceInherited, - DependentProtocolConformanceAssociated, - [Context] - Destructor, - [Context] - DidSet, - Directness, - DynamicAttribute, - DirectMethodReferenceAttribute, - DynamicSelf, - DynamicallyReplaceableFunctionImpl, - DynamicallyReplaceableFunctionKey, - DynamicallyReplaceableFunctionVar, - [Context] - Enum, - EnumCase, - ErrorType, - EscapingAutoClosureType, - NoEscapeFunctionType, - ExistentialMetatype, - [Context] - ExplicitClosure, - [Context] - Extension, - FieldOffset, - FullTypeMetadata, - [Context] - Function, - FunctionSignatureSpecialization, - FunctionSignatureSpecializationParam, - FunctionSignatureSpecializationParamKind, - FunctionSignatureSpecializationParamPayload, - FunctionType, - GenericPartialSpecialization, - GenericPartialSpecializationNotReAbstracted, - GenericProtocolWitnessTable, - GenericProtocolWitnessTableInstantiationFunction, - ResilientProtocolWitnessTable, - GenericSpecialization, - GenericSpecializationNotReAbstracted, - GenericSpecializationParam, - InlinedGenericFunction, - GenericTypeMetadataPattern, - [Context] - Getter, - Global, - [Context] - GlobalGetter, - Identifier, - Index, - [Context] - IVarInitializer, - [Context] - IVarDestroyer, - ImplEscaping, - ImplConvention, - ImplFunctionAttribute, - ImplFunctionType, - [Context] - ImplicitClosure, - ImplParameter, - ImplResult, - ImplErrorResult, - InOut, - InfixOperator, - [Context] - Initializer, - KeyPathGetterThunkHelper, - KeyPathSetterThunkHelper, - KeyPathEqualsThunkHelper, - KeyPathHashThunkHelper, - LazyProtocolWitnessTableAccessor, - LazyProtocolWitnessTableCacheVariable, - LocalDeclName, - [Context] - MaterializeForSet, - MergedFunction, - Metatype, - MetatypeRepresentation, - Metaclass, - MethodLookupFunction, - ObjCMetadataUpdateFunction, - [Context] - ModifyAccessor, - [Context] - Module, - [Context] - NativeOwningAddressor, - [Context] - NativeOwningMutableAddressor, - [Context] - NativePinningAddressor, - [Context] - NativePinningMutableAddressor, - NominalTypeDescriptor, - NonObjCAttribute, - Number, - ObjCAttribute, - ObjCBlock, - [Context] - OtherNominalType, - [Context] - OwningAddressor, - [Context] - OwningMutableAddressor, - PartialApplyForwarder, - PartialApplyObjCForwarder, - PostfixOperator, - PrefixOperator, - PrivateDeclName, - PropertyDescriptor, - [Context] - Protocol, - [Context] - ProtocolSymbolicReference, - ProtocolConformance, - ProtocolConformanceRefInTypeModule, - ProtocolConformanceRefInProtocolModule, - ProtocolConformanceRefInOtherModule, - ProtocolDescriptor, - ProtocolConformanceDescriptor, - ProtocolList, - ProtocolListWithClass, - ProtocolListWithAnyObject, - ProtocolSelfConformanceDescriptor, - ProtocolSelfConformanceWitness, - ProtocolSelfConformanceWitnessTable, - ProtocolWitness, - ProtocolWitnessTable, - ProtocolWitnessTableAccessor, - ProtocolWitnessTablePattern, - ReabstractionThunk, - ReabstractionThunkHelper, - [Context] - ReadAccessor, - RelatedEntityDeclName, - RetroactiveConformance, - ReturnType, - Shared, - Owned, - SILBoxType, - SILBoxTypeWithLayout, - SILBoxLayout, - SILBoxMutableField, - SILBoxImmutableField, - [Context] - Setter, - SpecializationPassID, - SpecializationIsFragile, - [Context] - Static, - [Context] - Structure, - [Context] - Subscript, - Suffix, - ThinFunctionType, - Tuple, - TupleElement, - TupleElementName, - Type, - [Context] - TypeSymbolicReference, - [Context] - TypeAlias, - TypeList, - TypeMangling, - TypeMetadata, - TypeMetadataAccessFunction, - TypeMetadataCompletionFunction, - TypeMetadataInstantiationCache, - TypeMetadataInstantiationFunction, - TypeMetadataSingletonInitializationCache, - TypeMetadataLazyCache, - Unowned, - UncurriedFunctionType, - Weak, - - Unmanaged, - [Context] - UnsafeAddressor, - [Context] - UnsafeMutableAddressor, - ValueWitness, - ValueWitnessTable, - [Context] - Variable, - VTableThunk, - VTableAttribute, // note: old mangling only - [Context] - WillSet, - ReflectionMetadataBuiltinDescriptor, - ReflectionMetadataFieldDescriptor, - ReflectionMetadataAssocTypeDescriptor, - ReflectionMetadataSuperclassDescriptor, - GenericTypeParamDecl, - CurryThunk, - DispatchThunk, - MethodDescriptor, - ProtocolRequirementsBaseDescriptor, - AssociatedConformanceDescriptor, - DefaultAssociatedConformanceAccessor, - BaseConformanceDescriptor, - AssociatedTypeDescriptor, - ThrowsAnnotation, - EmptyList, - FirstElementMarker, - VariadicMarker, - OutlinedBridgedMethod, - OutlinedCopy, - OutlinedConsume, - OutlinedRetain, - OutlinedRelease, - OutlinedInitializeWithTake, - OutlinedInitializeWithCopy, - OutlinedAssignWithTake, - OutlinedAssignWithCopy, - OutlinedDestroy, - OutlinedVariable, - AssocTypePath, - LabelList, - ModuleDescriptor, - ExtensionDescriptor, - AnonymousDescriptor, - AssociatedTypeGenericParamRef, - } - - public enum PayloadKind - { - None, - Text, - Index, - } - - public enum GenericTypeKind - { - Generic, - Assoc, - CompoundAssoc, - Substitution, - } - - public enum GenericConstraintKind - { - Protocol, - BaseClass, - SameType, - Layout, - } - - public enum FunctionSigSpecializationParamKind : uint - { - ConstantPropFunction = 0, - ConstantPropGlobal = 1, - ConstantPropInteger = 2, - ConstantPropFloat = 3, - ConstantPropString = 4, - ClosureProp = 5, - BoxToValue = 6, - BoxToStack = 7, - - // Option Set Flags use bits 6-31. This gives us 26 bits to use for option - // flags. - Dead = 1 << 6, - OwnedToGuaranteed = 1 << 7, - SROA = 1 << 8, - GuaranteedToOwned = 1 << 9, - ExistentialToGeneric = 1 << 10, - } - - public enum Directness - { - Direct, - Indirect, - } - - public enum FunctionEntityArgs - { - None, - Type, - TypeAndName, - TypeAndMaybePrivateName, - TypeAndIndex, - Index, - } - - public enum ValueWitnessKind - { - AllocateBuffer, - AssignWithCopy, - AssignWithTake, - DeallocateBuffer, - Destroy, - DestroyBuffer, - DestroyArray, - InitializeBufferWithCopyOfBuffer, - InitializeBufferWithCopy, - InitializeWithCopy, - InitializeBufferWithTake, - InitializeWithTake, - ProjectBuffer, - InitializeBufferWithTakeOfBuffer, - InitializeArrayWithCopy, - InitializeArrayWithTakeFrontToBack, - InitializeArrayWithTakeBackToFront, - StoreExtraInhabitant, - GetExtraInhabitantIndex, - GetEnumTag, - DestructiveProjectEnumData, - DestructiveInjectEnumTag, - GetEnumTagSinglePayload, - StoreEnumTagSinglePayload - } - - public enum MatchNodeContentType - { - None, - Index, - Text, - AlwaysMatch, - } - - public enum SymbolicReferenceKind - { - Context, - } -} diff --git a/src/SwiftReflector/Demangling/MatchRule.cs b/src/SwiftReflector/Demangling/MatchRule.cs deleted file mode 100644 index 97c862791795..000000000000 --- a/src/SwiftReflector/Demangling/MatchRule.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Demangling -{ - public class MatchRule - { - public MatchRule() - { - Name = ""; - NodeKind = NodeKind.Type; // arbitrary - MatchContent = MatchNodeContentType.AlwaysMatch; - ChildRules = new List(); - MatchChildCount = false; - Reducer = (n, b, name) => null; - } - - public string Name { get; set; } - public NodeKind NodeKind - { - get - { - if (NodeKindList.Count != 1) - throw new InvalidOperationException($"NodeKind is invalid when NodeKindList has {NodeKindList.Count} entries."); - return NodeKindList[0]; - } - set - { - NodeKindList = new List { value }; - } - } - public List NodeKindList { get; set; } - public MatchNodeContentType MatchContent { get; set; } - public List ChildRules { get; set; } - public bool MatchChildCount { get; set; } - public Func Reducer { get; set; } - - - public bool Matches(Node n) - { - Exceptions.ThrowOnNull(n, nameof(n)); - // 3 match criteria: NodeKind, Content type, children - return NodeKindMatches(n) && ContentMatches(n) && - ChildrenMatches(n); - } - - bool NodeKindMatches(Node n) - { - return NodeKindList.Contains(n.Kind); - } - - bool ContentMatches(Node n) - { - // Only care about the content type not its value - switch (MatchContent) - { - case MatchNodeContentType.AlwaysMatch: - return true; - case MatchNodeContentType.Index: - return n.HasIndex; - case MatchNodeContentType.Text: - return n.HasText; - case MatchNodeContentType.None: - return !n.HasIndex && !n.HasText; - default: - throw new InvalidOperationException($"Unknown match instruction {MatchContent} in match rule."); - } - } - - bool ChildrenMatches(Node n) - { - // if the rule says the child count matters, apply - if (MatchChildCount && n.Children.Count != ChildRules.Count) - return false; - - // match up to the minimum of each list - // if MatchChileCount is true, min is the size of both lists - int minimumChildCount = Math.Min(n.Children.Count, ChildRules.Count); - for (var i = 0; i < minimumChildCount; i++) - { - var childRule = ChildRules[i]; - // recurse - if (!childRule.Matches(n.Children[i])) - return false; - } - return true; - } - - public override string ToString() - { - return Name; - } - } -} diff --git a/src/SwiftReflector/Demangling/Node.cs b/src/SwiftReflector/Demangling/Node.cs deleted file mode 100644 index 30a330587d64..000000000000 --- a/src/SwiftReflector/Demangling/Node.cs +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SwiftReflector.Demangling -{ - public class Node - { - Node(NodeKind kind, PayloadKind payload) - { - Kind = kind; - PayloadKind = payload; - Children = new List(); - } - - public Node(NodeKind kind) - : this(kind, PayloadKind.None) - { - } - - public Node(NodeKind kind, string text) - : this(kind, PayloadKind.Text) - { - stringPayload = text; - } - - public Node(NodeKind kind, long index) - : this(kind, PayloadKind.Index) - { - indexPayload = index; - } - - string stringPayload = null; - long indexPayload = 0; - - public List Children { get; private set; } - - public NodeKind Kind { get; private set; } - public PayloadKind PayloadKind { get; private set; } - - public bool HasText { get { return PayloadKind == PayloadKind.Text; } } - public string Text - { - get - { - if (!HasText) - throw new InvalidOperationException($"Expected a text payload, but this has a {PayloadKind} payload"); - return stringPayload; - } - } - - public bool HasIndex { get { return PayloadKind == PayloadKind.Index; } } - public long Index - { - get - { - if (!HasIndex) - throw new InvalidOperationException($"Expected an index payload, but this has a {PayloadKind} payload"); - return indexPayload; - } - } - - public void AddChild(Node child) - { - Children.Add(child); - } - - public void RemoveChildAt(int pos) - { - Children.RemoveAt(pos); - } - - public void ReverseChildren(int startingAt = 0) - { - var last = Children.Count - 1; - if (startingAt < 0 || startingAt > Children.Count) - throw new ArgumentOutOfRangeException(nameof(startingAt)); - while (startingAt < last) - { - Node temp = Children[startingAt]; - Children[startingAt] = Children[last]; - Children[last] = temp; - startingAt++; - last--; - } - } - - - public static bool IsDeclName(NodeKind kind) - { - switch (kind) - { - case NodeKind.Identifier: - case NodeKind.LocalDeclName: - case NodeKind.PrivateDeclName: - case NodeKind.RelatedEntityDeclName: - case NodeKind.PrefixOperator: - case NodeKind.PostfixOperator: - case NodeKind.InfixOperator: - case NodeKind.TypeSymbolicReference: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - public static bool IsContext(NodeKind kind) - { - var type = typeof(NodeKind); - var memberInfo = type.GetMember(kind.ToString()); - var attrs = memberInfo[0].GetCustomAttributes(typeof(ContextAttribute), false); - return attrs != null && attrs.Length == 1; - } - - public static bool IsAnyGeneric(NodeKind kind) - { - switch (kind) - { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - case NodeKind.OtherNominalType: - case NodeKind.TypeAlias: - case NodeKind.TypeSymbolicReference: - return true; - default: - return false; - } - } - - public static bool IsNominal(NodeKind kind) - { - switch (kind) - { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - return true; - default: - return false; - } - } - - public static bool IsEntity(NodeKind kind) - { - if (kind == NodeKind.Type) - return true; - return IsContext(kind); - } - - public static bool IsRequirement(NodeKind kind) - { - switch (kind) - { - case NodeKind.DependentGenericSameTypeRequirement: - case NodeKind.DependentGenericLayoutRequirement: - case NodeKind.DependentGenericConformanceRequirement: - return true; - default: - return false; - } - } - - public static bool IsFunctionAttribute(NodeKind kind) - { - switch (kind) - { - case NodeKind.FunctionSignatureSpecialization: - case NodeKind.GenericSpecialization: - case NodeKind.InlinedGenericFunction: - case NodeKind.GenericSpecializationNotReAbstracted: - case NodeKind.GenericPartialSpecialization: - case NodeKind.GenericPartialSpecializationNotReAbstracted: - case NodeKind.ObjCAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.DirectMethodReferenceAttribute: - case NodeKind.VTableAttribute: - case NodeKind.PartialApplyForwarder: - case NodeKind.PartialApplyObjCForwarder: - case NodeKind.OutlinedVariable: - case NodeKind.OutlinedBridgedMethod: - case NodeKind.MergedFunction: - case NodeKind.DynamicallyReplaceableFunctionImpl: - case NodeKind.DynamicallyReplaceableFunctionKey: - case NodeKind.DynamicallyReplaceableFunctionVar: - return true; - default: - return false; - } - } - - public override string ToString() - { - var sb = new StringBuilder(); - ToString(0, sb); - return sb.ToString(); - } - - void ToString(int indent, StringBuilder sb) - { - for (int i = 0; i < indent; i++) - { - sb.Append(' '); - } - sb.Append("->").Append(Kind.ToString()); - switch (PayloadKind) - { - case PayloadKind.None: - sb.Append(Environment.NewLine); - break; - case PayloadKind.Index: - sb.Append($" ({Index})\n"); - break; - case PayloadKind.Text: - sb.Append($" (\"{Text}\")\n"); - break; - } - foreach (var node in Children) - { - node.ToString(indent + 2, sb); - } - } - - public bool IsAttribute() - { - switch (Kind) - { - case NodeKind.ObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.ImplFunctionAttribute: - case NodeKind.DirectMethodReferenceAttribute: - return true; - default: - return false; - } - } - - public SwiftTypeAttribute ExtractAttribute() - { - switch (Kind) - { - case NodeKind.ObjCAttribute: return SwiftTypeAttribute.ObjC; - case NodeKind.DynamicAttribute: return SwiftTypeAttribute.Dynamic; - case NodeKind.NonObjCAttribute: return SwiftTypeAttribute.NonObjC; - case NodeKind.ImplFunctionAttribute: return SwiftTypeAttribute.ImplFunction; - case NodeKind.DirectMethodReferenceAttribute: return SwiftTypeAttribute.DirectMethodReference; - default: - throw new NotSupportedException($"{Kind} is not an attribute"); - } - } - } -} diff --git a/src/SwiftReflector/Demangling/RuleRunner.cs b/src/SwiftReflector/Demangling/RuleRunner.cs deleted file mode 100644 index 717102fe3e37..000000000000 --- a/src/SwiftReflector/Demangling/RuleRunner.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SwiftReflector.Demangling -{ - public class RuleRunner - { - List rules = new List(); - public RuleRunner(IEnumerable rules) - { - this.rules.AddRange(rules); - } - - public SwiftType RunRules(Node node, bool isReference, SwiftName name) - { - var rule = rules.FirstOrDefault(r => r.Matches(node)); - - return rule != null ? rule.Reducer(node, isReference, name) : null; - } - } -} diff --git a/src/SwiftReflector/Demangling/Swift5Demangler.cs b/src/SwiftReflector/Demangling/Swift5Demangler.cs deleted file mode 100644 index a9e4a47ef17a..000000000000 --- a/src/SwiftReflector/Demangling/Swift5Demangler.cs +++ /dev/null @@ -1,3231 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Text; - - - -// This is a port of the Apple Swift 5 demangler -namespace SwiftReflector.Demangling -{ - public class Swift5Demangler - { - ulong offset; - string originalIdentifier; - Stack nodeStack = new Stack(); - List substitutions = new List(); - string text; - List words = new List(); - StringSlice slice; - bool isOldFunctionTypeMangling = false; - - public Func SymbolicReferenceResolver { get; set; } - - static string[] prefixes = { - /*Swift 4*/ "_T0", - /*Swift 4.x*/ "$S", "_$S", - /*Swift 5+*/ "$s", "_$s" - }; - - Swift5Demangler() - { - } - - - public Swift5Demangler(string mangledName, ulong offset = 0) - { - originalIdentifier = mangledName; - this.offset = offset; - slice = new StringSlice(originalIdentifier); - slice.Advance(GetManglingPrefixLength(originalIdentifier)); - } - - public TLDefinition Run() - { - Node topLevelNode = DemangleType(null); - if (topLevelNode != null && topLevelNode.IsAttribute() && nodeStack.Count >= 1) - { - var attribute = topLevelNode.ExtractAttribute(); - var tld = Run(); - if (tld != null && tld is TLFunction tlf) - { - tlf.Signature.Attributes.Add(attribute); - } - return tld; - } - else - { - Swift5NodeToTLDefinition converter = new Swift5NodeToTLDefinition(originalIdentifier, offset); - return converter.Convert(topLevelNode); - } - } - - bool NextIf(string str) - { - if (slice.StartsWith(str)) - { - slice.Advance(str.Length); - return true; - } - return false; - - } - - char PeekChar() - { - if (slice.IsAtEnd) - return (char)0; - return slice.Current; - } - - char NextChar() - { - return slice.Advance(); - } - - bool NextIf(char c) - { - return slice.AdvanceIfEquals(c); - } - - void PushBack() - { - slice.Rewind(); - } - - string ConsumeAll() - { - return slice.ConsumeRemaining(); - } - - void PushNode(Node node) - { - nodeStack.Push(node); - } - - Node PopNode() - { - if (nodeStack.Count == 0) - return null; - return nodeStack.Pop(); - } - - Node PopNode(NodeKind kind) - { - if (nodeStack.Count == 0) - return null; - if (kind != nodeStack.Peek().Kind) - return null; - return PopNode(); - } - - Node PopNode(Predicate pred) - { - if (nodeStack.Count == 0) - return null; - if (!pred(nodeStack.Peek().Kind)) - return null; - return PopNode(); - } - - void AddSubstitution(Node nd) - { - if (nd != null) - substitutions.Add(nd); - } - - Node CreateWithPoppedType(NodeKind kind) - { - return CreateWithChild(kind, PopNode(NodeKind.Type)); - } - - - // beginning of swift 5 demangler port - - static bool IsDeclName(NodeKind kind) - { - switch (kind) - { - case NodeKind.Identifier: - case NodeKind.LocalDeclName: - case NodeKind.PrivateDeclName: - case NodeKind.RelatedEntityDeclName: - case NodeKind.PrefixOperator: - case NodeKind.PostfixOperator: - case NodeKind.InfixOperator: - case NodeKind.TypeSymbolicReference: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsContext(NodeKind node) - { - var type = typeof(NodeKind); - var memInfo = type.GetMember(node.ToString()); - return memInfo[0].GetCustomAttributes(typeof(ContextAttribute), false).Length > 0; - } - - static bool IsAnyGeneric(NodeKind kind) - { - switch (kind) - { - case NodeKind.Structure: - case NodeKind.Class: - case NodeKind.Enum: - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - case NodeKind.OtherNominalType: - case NodeKind.TypeAlias: - case NodeKind.TypeSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsEntity(NodeKind kind) - { - if (kind == NodeKind.Type) - return true; - return IsContext(kind); - } - - static bool IsRequirement(NodeKind kind) - { - switch (kind) - { - case NodeKind.DependentGenericSameTypeRequirement: - case NodeKind.DependentGenericLayoutRequirement: - case NodeKind.DependentGenericConformanceRequirement: - return true; - default: - return false; - } - } - - static bool IsFunctionAttr(NodeKind kind) - { - switch (kind) - { - case NodeKind.FunctionSignatureSpecialization: - case NodeKind.GenericSpecialization: - case NodeKind.InlinedGenericFunction: - case NodeKind.GenericSpecializationNotReAbstracted: - case NodeKind.GenericPartialSpecialization: - case NodeKind.GenericPartialSpecializationNotReAbstracted: - case NodeKind.ObjCAttribute: - case NodeKind.NonObjCAttribute: - case NodeKind.DynamicAttribute: - case NodeKind.DirectMethodReferenceAttribute: - case NodeKind.VTableAttribute: - case NodeKind.PartialApplyForwarder: - case NodeKind.PartialApplyObjCForwarder: - case NodeKind.OutlinedVariable: - case NodeKind.OutlinedBridgedMethod: - case NodeKind.MergedFunction: - case NodeKind.DynamicallyReplaceableFunctionImpl: - case NodeKind.DynamicallyReplaceableFunctionKey: - case NodeKind.DynamicallyReplaceableFunctionVar: - return true; - default: - return false; - } - } - - int GetManglingPrefixLength(string mangledName) - { - if (string.IsNullOrEmpty(mangledName)) - return 0; - foreach (var prefix in prefixes) - { - mangledName.StartsWith(prefix, StringComparison.Ordinal); - return prefix.Length; - } - return 0; - } - - bool IsSwiftSymbol(string mangledName) - { - if (IsOldFunctionTypeMangling(mangledName)) - return true; - return GetManglingPrefixLength(mangledName) != 0; - } - - bool IsObjCSymbol(string mangledName) - { - var nameWithoutPrefix = DropSwiftManglingPrefix(mangledName); - return nameWithoutPrefix.StartsWith("So", StringComparison.Ordinal) || nameWithoutPrefix.StartsWith("Sc", StringComparison.Ordinal); - } - - bool IsOldFunctionTypeMangling(string mangledName) - { - return mangledName.StartsWith("_T", StringComparison.Ordinal); - } - - string DropSwiftManglingPrefix(string mangledName) - { - return mangledName.Substring(GetManglingPrefixLength(mangledName)); - } - - static bool IsAliasNode(Node node) - { - switch (node.Kind) - { - case NodeKind.Type: - return IsAliasNode(node.Children[0]); - case NodeKind.TypeAlias: - return true; - default: - return false; - } - } - - static bool IsAlias(string mangledName) - { - return IsAliasNode(new Swift5Demangler().DemangleType(mangledName)); - } - - static bool IsClassNode(Node node) - { - switch (node.Kind) - { - case NodeKind.Type: - return IsClassNode(node.Children[0]); - case NodeKind.Class: - case NodeKind.BoundGenericClass: - return true; - default: - return false; - } - } - - static bool IsClass(string mangledName) - { - return IsClassNode(new Swift5Demangler().DemangleType(mangledName)); - } - - static bool IsEnumNode(Node node) - { - switch (node.Kind) - { - case NodeKind.Type: - return IsEnumNode(node.Children[0]); - case NodeKind.Enum: - case NodeKind.BoundGenericEnum: - return true; - default: - return false; - } - } - - static bool IsEnum(string mangledName) - { - return IsEnumNode(new Swift5Demangler().DemangleType(mangledName)); - } - - static bool IsProtocolNode(Node node) - { - switch (node.Kind) - { - case NodeKind.Type: - return IsProtocolNode(node.Children[0]); - case NodeKind.Protocol: - case NodeKind.ProtocolSymbolicReference: - return true; - default: - return false; - } - } - - static bool IsProtocol(string mangledName) - { - return IsProtocolNode(new Swift5Demangler().DemangleType(mangledName)); - } - - static bool IsStructNode(Node node) - { - switch (node.Kind) - { - case NodeKind.Type: - return IsStructNode(node.Children[0]); - case NodeKind.Structure: - case NodeKind.BoundGenericStructure: - return true; - default: - return false; - } - } - - static bool IsStruct(string mangledName) - { - return IsStructNode(new Swift5Demangler().DemangleType(mangledName)); - } - - - - - void Clear() - { - nodeStack.Clear(); - substitutions.Clear(); - } - - void Init(string mangledName) - { - nodeStack = new Stack(); - substitutions = new List(); - words = new List(); - if (mangledName != null) - { - text = mangledName; - slice = new StringSlice(mangledName); - } - } - - public Node DemangleSymbol(string mangledName) - { - Init(mangledName); - - if (NextIf("_Tt")) - return DemangleObjCTypeName(); - - var prefixLength = GetManglingPrefixLength(mangledName); - if (prefixLength == 0) - return null; - isOldFunctionTypeMangling = IsOldFunctionTypeMangling(mangledName); - slice.Advance(prefixLength); - - if (!ParseAndPushNodes()) - return null; - - var topLevel = new Node(NodeKind.Global); - var parent = topLevel; - Node funcAttr = null; - while ((funcAttr = PopNode(IsFunctionAttr)) != null) - { - parent.AddChild(funcAttr); - if (funcAttr.Kind == NodeKind.PartialApplyForwarder || funcAttr.Kind == NodeKind.PartialApplyObjCForwarder) - parent = funcAttr; - foreach (var nd in nodeStack) - { - switch (nd.Kind) - { - case NodeKind.Type: - parent.AddChild(nd.Children[0]); - break; - default: - parent.AddChild(nd); - break; - } - } - } - if (topLevel.Children.Count == 0) - return null; - - return topLevel; - } - - Node DemangleType(string mangledName) - { - Init(mangledName); - - ParseAndPushNodes(); - - var result = PopNode(); - if (result != null) - return result; - - return new Node(NodeKind.Suffix, text); - } - - bool ParseAndPushNodes() - { - var idx = 0; - while (!slice.IsAtEnd) - { - var node = DemangleOperator(); - if (node == null) - return false; - PushNode(node); - idx++; - } - return true; - } - - Node AddChild(Node parent, Node child) - { - if (parent == null || child == null) - return null; - parent.Children.Add(child); - return parent; - } - - Node CreateWithChild(NodeKind kind, Node child) - { - if (child == null) - return null; - var node = new Node(kind); - node.Children.Add(child); - return node; - } - - Node CreateType(Node child) - { - return CreateWithChild(NodeKind.Type, child); - } - - Node CreateWithChildren(NodeKind kind, params Node[] children) - { - foreach (var nd in children) - if (nd == null) - throw new ArgumentOutOfRangeException(nameof(children)); - var node = new Node(kind); - node.Children.AddRange(children); - return node; - } - - Node ChangeKind(Node node, NodeKind newKind) - { - Node newNode = null; - if (node.HasText) - { - newNode = new Node(newKind, node.Text); - } - else if (node.HasIndex) - { - newNode = new Node(newKind, node.Index); - } - else - { - newNode = new Node(newKind); - } - newNode.Children.AddRange(node.Children); - return newNode; - } - - Node DemangleTypeMangling() - { - var type = PopNode(NodeKind.Type); - var labelList = PopFunctionParamLabels(type); - var typeMangling = new Node(NodeKind.TypeMangling); - - AddChild(typeMangling, labelList); - typeMangling = AddChild(typeMangling, type); - return typeMangling; - } - - Node DemangleSymbolicReference(int rawKind) - { - var data = new byte[4]; - for (int i = 0; i < 4; i++) - { - data[i] = (byte)NextChar(); - } - var value = BitConverter.ToInt32(data, 0); - - SymbolicReferenceKind kind; - Directness direct; - switch (rawKind) - { - case 1: - kind = SymbolicReferenceKind.Context; - direct = Directness.Direct; - break; - case 2: - kind = SymbolicReferenceKind.Context; - direct = Directness.Indirect; - break; - default: - return null; - } - - Node resolved = null; - if (SymbolicReferenceResolver != null) - { - resolved = SymbolicReferenceResolver(kind, direct, value, data); - } - if (resolved == null) - return null; - - if (kind == SymbolicReferenceKind.Context) - AddSubstitution(resolved); - return resolved; - } - - Node DemangleOperator() - { - var c = NextChar(); - switch (c) - { - case '\x01': - case '\x02': - case '\x03': - case '\x04': - return DemangleSymbolicReference(c); - case 'A': return DemangleMultiSubstitutions(); - case 'B': return DemangleBuiltinType(); - case 'C': return DemangleAnyGenericType(NodeKind.Class); - case 'D': return DemangleTypeMangling(); - case 'E': return DemangleExtensionContext(); - case 'F': return DemanglePlainFunction(); - case 'G': return DemangleBoundGenericType(); - case 'H': - var c2 = NextChar(); - switch (c2) - { - case 'A': return DemangleDependentProtocolConformanceAssociated(); - case 'C': return DemangleConcreteProtocolConformance(); - case 'D': return DemangleDependentProtocolConformanceRoot(); - case 'I': return DemangleDependentProtocolConformanceInherited(); - case 'P': - return CreateWithChild(NodeKind.ProtocolConformanceRefInTypeModule, PopProtocol()); - case 'p': - return CreateWithChild(NodeKind.ProtocolConformanceRefInProtocolModule, PopProtocol()); - default: - PushBack(); - PushBack(); - return DemangleIdentifier(); - } - case 'I': return DemangleImplFunctionType(); - case 'K': return new Node(NodeKind.ThrowsAnnotation); - case 'L': return DemangleLocalIdentifier(); - case 'M': return DemangleMetatype(); - case 'N': return CreateWithChild(NodeKind.TypeMetadata, PopNode(NodeKind.Type)); - case 'O': return DemangleAnyGenericType(NodeKind.Enum); - case 'P': return DemangleAnyGenericType(NodeKind.Protocol); - case 'Q': return DemangleArchetype(); - case 'R': return DemangleGenericRequirement(); - case 'S': return DemangleStandardSubstitution(); - case 'T': return DemangleThunkOrSpecialization(); - case 'V': return DemangleAnyGenericType(NodeKind.Structure); - case 'W': return DemangleWitness(); - case 'X': return DemangleSpecialType(); - case 'Z': return CreateWithChild(NodeKind.Static, PopNode(IsEntity)); - case 'a': return DemangleAnyGenericType(NodeKind.TypeAlias); - case 'c': return PopFunctionType(NodeKind.FunctionType); - case 'd': return new Node(NodeKind.VariadicMarker); - case 'f': return DemangleFunctionEntity(); - case 'g': return DemangleRetroactiveConformance(); - case 'h': return CreateType(CreateWithChild(NodeKind.Shared, PopTypeAndGetChild())); - case 'i': return DemangleSubscript(); - case 'l': return DemangleGenericSignature(false); - case 'm': return CreateType(CreateWithChild(NodeKind.Metatype, PopNode(NodeKind.Type))); - case 'n': return CreateType(CreateWithChild(NodeKind.Owned, PopTypeAndGetChild())); - case 'o': return DemangleOperatorIdentifier(); - case 'p': return DemangleProtocolListType(); - case 'q': return CreateType(DemangleGenericParamIndex()); - case 'r': return DemangleGenericSignature(true); - case 's': return new Node(NodeKind.Module, "Swift"); - case 't': return PopTuple(); - case 'u': return DemangleGenericType(); - case 'v': return DemangleVariable(); - case 'w': return DemangleValueWitness(); - case 'x': return CreateType(GetDependentGenericParamType(0, 0)); - case 'y': return new Node(NodeKind.EmptyList); - case 'z': return CreateType(CreateWithChild(NodeKind.InOut, PopTypeAndGetChild())); - case '_': return new Node(NodeKind.FirstElementMarker); - case '.': - PushBack(); - return new Node(NodeKind.Suffix, slice.ConsumeRemaining()); - default: - PushBack(); - return DemangleIdentifier(); - } - } - - int DemangleNatural() - { - if (!Char.IsDigit(slice.Current)) - return -1000; - var num = 0; - while (true) - { - var c = slice.Current; - if (!Char.IsDigit(c)) - return num; - var newNum = (10 * num) + (c - '0'); - if (newNum < num) - return -1000; - num = newNum; - NextChar(); - } - } - - int DemangleIndex() - { - if (NextIf('_')) - return 0; - var num = DemangleNatural(); - if (num >= 0 && NextIf('_')) - return num + 1; - return -1000; - } - - - Node DemangleIndexAsNode() - { - var idx = DemangleIndex(); - if (idx >= 0) - return new Node(NodeKind.Number, idx); - return null; - } - - Node DemangleMultiSubstitutions() - { - var repeatCount = 1; - while (true) - { - if (slice.IsAtEnd) - return null; - var c = NextChar(); - if (Char.IsLower(c)) - { - var nd = PushMultiSubstitutions(repeatCount, c - 'a'); - if (nd == null) - return null; - PushNode(nd); - repeatCount = -1; - continue; - } - if (Char.IsUpper(c)) - { - return PushMultiSubstitutions(repeatCount, c - 'A'); - } - if (c == '_') - { - var idx = repeatCount + 27; - if (idx >= substitutions.Count) - return null; - return substitutions[idx]; - } - PushBack(); - repeatCount = DemangleNatural(); - if (repeatCount < 0) - return null; - } - } - - Node PushMultiSubstitutions(int repeatCount, int substIdx) - { - if (substIdx >= substitutions.Count) - return null; - var nd = substitutions[substIdx]; - while (repeatCount-- > 1) - { - PushNode(nd); - } - return nd; - } - - Node CreateSwiftType(NodeKind typeKind, string name) - { - return CreateType(CreateWithChildren(typeKind, new Node(NodeKind.Module, "Swift"), new Node(NodeKind.Identifier, name))); - } - - Node DemangleStandardSubstitution() - { - var c = NextChar(); - switch (c) - { - case 'o': - return new Node(NodeKind.Module, "__C"); - case 'C': - return new Node(NodeKind.Module, "__C_Synthesized"); - case 'g': - { - var optionalTy = CreateType(CreateWithChildren(NodeKind.BoundGenericEnum, - CreateSwiftType(NodeKind.Enum, "Optional"), - CreateWithChild(NodeKind.TypeList, PopNode(NodeKind.Type)))); - AddSubstitution(optionalTy); - return optionalTy; - } - default: - PushBack(); - Node nd; - var repeatCount = DemangleNatural(); - if ((nd = CreateStandardSubstitution(NextChar())) != null) - { - while (repeatCount-- > 1) - { - PushNode(nd); - } - return nd; - } - return null; - } - } - - Node CreateStandardSubstitution(char subst) - { - var kind = NodeKind.Structure; - string name = null; - switch (subst) - { - case 'A': name = "AutoreleasingUnsafeMutablePointer"; break; - case 'a': name = "Array"; break; - case 'b': name = "Bool"; break; - case 'c': name = "UnicodeScalar"; break; - case 'D': name = "Dictionary"; break; - case 'd': name = "Double"; break; - case 'f': name = "Float"; break; - case 'h': name = "Set"; break; - case 'I': name = "DefaultIndicies"; break; - case 'i': name = "Int"; break; - case 'J': name = "Character"; break; - case 'N': name = "ClosedRange"; break; - case 'n': name = "Range"; break; - case 'O': name = "ObjectIdentifier"; break; - case 'P': name = "UnsafePointer"; break; - case 'p': name = "UnsafeMutablePointer"; break; - case 'R': name = "UnsafeBufferPointer"; break; - case 'r': name = "UnsafeMutableBufferPointer"; break; - case 'S': name = "String"; break; - case 's': name = "Substring"; break; - case 'u': name = "UInt"; break; - case 'V': name = "UnsafeRawPointer"; break; - case 'v': name = "UnsafeMutableRawPointer"; break; - case 'W': name = "UnsafeRawBufferPointer"; break; - case 'w': name = "UnsafeMutableRawBufferPointer"; break; - - case 'q': name = "Optional"; kind = NodeKind.Enum; break; - - case 'B': name = "BinaryFloatingPoint"; kind = NodeKind.Protocol; break; - case 'E': name = "Encodable"; kind = NodeKind.Protocol; break; - case 'e': name = "Decodable"; kind = NodeKind.Protocol; break; - case 'F': name = "FloatingPoint"; kind = NodeKind.Protocol; break; - case 'G': name = "RandomNumberGenerator"; kind = NodeKind.Protocol; break; - case 'H': name = "Hashable"; kind = NodeKind.Protocol; break; - case 'j': name = "Numeric"; kind = NodeKind.Protocol; break; - case 'K': name = "BidirectionalCollection"; kind = NodeKind.Protocol; break; - case 'k': name = "RandomAccessCollection"; kind = NodeKind.Protocol; break; - case 'L': name = "Comparable"; kind = NodeKind.Protocol; break; - case 'l': name = "Collection"; kind = NodeKind.Protocol; break; - case 'M': name = "MutableCollection"; kind = NodeKind.Protocol; break; - case 'm': name = "RangeReplaceableCollection"; kind = NodeKind.Protocol; break; - case 'Q': name = "Equatable"; kind = NodeKind.Protocol; break; - case 'T': name = "Sequence"; kind = NodeKind.Protocol; break; - case 't': name = "IteratorProtocol"; kind = NodeKind.Protocol; break; - case 'U': name = "UnsignedInteger"; kind = NodeKind.Protocol; break; - case 'X': name = "RangeExpression"; kind = NodeKind.Protocol; break; - case 'x': name = "Strideable"; kind = NodeKind.Protocol; break; - case 'Y': name = "RawRepresentable"; kind = NodeKind.Protocol; break; - case 'y': name = "StringProtocol"; kind = NodeKind.Protocol; break; - case 'Z': name = "SignedInteger"; kind = NodeKind.Protocol; break; - case 'z': name = "BinaryInteger"; kind = NodeKind.Protocol; break; - default: - return null; - } - - return CreateSwiftType(kind, name); - } - - Node DemangleIdentifier() - { - var hasWordSubsts = false; - var isPunycoded = false; - var c = PeekChar(); - if (!Char.IsDigit(c)) - return null; - if (c == '0') - { - NextChar(); - if (PeekChar() == '0') - { - NextChar(); - isPunycoded = true; - } - else - { - hasWordSubsts = true; - } - } - var identifier = new StringBuilder(); - do - { - while (hasWordSubsts && Char.IsLetter(PeekChar())) - { - var cc = NextChar(); - var wordIdx = 0; - if (Char.IsLower(cc)) - { - wordIdx = cc - 'a'; - } - else - { - wordIdx = cc - 'A'; - hasWordSubsts = false; - } - if (wordIdx >= words.Count) - return null; - string piece0 = words[wordIdx]; - identifier.Append(piece0); - } - if (NextIf('0')) - break; - var numChars = DemangleNatural(); - if (numChars <= 0) - return null; - if (isPunycoded) - NextIf('_'); - if (numChars > slice.Length) - return null; - string piece = slice.Substring(slice.Position, numChars); - if (isPunycoded) - { - PunyCode puny = new PunyCode(); - string punyCodedString = puny.Decode(piece); - identifier.Append(punyCodedString); - } - else - { - identifier.Append(piece); - var wordStartPos = -1; - for (int idx = 0; idx <= piece.Length; idx++) - { - char ccc = idx < piece.Length ? piece[idx] : (char)0; - if (wordStartPos >= 0 && IsWordEnd(ccc, piece[idx - 1])) - { - if (idx - wordStartPos >= 2 && words.Count < 26) - { - var word = piece.Substring(wordStartPos, idx - wordStartPos); - words.Add(word); - } - wordStartPos = -1; - } - if (wordStartPos < 0 && IsWordStart(ccc)) - { - wordStartPos = idx; - } - } - } - slice.Advance(numChars); - } while (hasWordSubsts); - if (identifier.Length == 0) - return null; - var ident = new Node(NodeKind.Identifier, identifier.ToString()); - AddSubstitution(ident); - return ident; - } - - bool IsWordStart(char ch) - { - return !Char.IsDigit(ch) && ch != '_' && ch != (char)0; - } - - bool IsWordEnd(char ch, char prevCh) - { - if (ch == '_' || ch == (char)0) - return true; - if (!Char.IsUpper(prevCh) && Char.IsUpper(ch)) - return true; - return false; - } - - - Node DemangleOperatorIdentifier() - { - var ident = PopNode(NodeKind.Identifier); - if (ident == null) - return null; - var op_char_table = "& @/= > <*!|+?%-~ ^ ."; - StringBuilder opStr = new StringBuilder(); - foreach (var c in ident.Text) - { - if (c > 0x7f) - { - opStr.Append(c); - continue; - } - if (!Char.IsLower(c)) - return null; - char o = op_char_table[c - 'a']; - if (o == ' ') - return null; - opStr.Append(o); - } - switch (NextChar()) - { - case 'i': return new Node(NodeKind.InfixOperator, opStr.ToString()); - case 'p': return new Node(NodeKind.PrefixOperator, opStr.ToString()); - case 'P': return new Node(NodeKind.PostfixOperator, opStr.ToString()); - default: return null; - } - } - - - Node DemangleLocalIdentifier() - { - if (NextIf('L')) - { - var discriminator = PopNode(NodeKind.Identifier); - var name = PopNode(IsDeclName); - return CreateWithChildren(NodeKind.PrivateDeclName, discriminator, name); - } - if (NextIf('l')) - { - var discriminator = PopNode(NodeKind.Identifier); - return CreateWithChild(NodeKind.PrivateDeclName, discriminator); - } - if ((PeekChar() >= 'a' && PeekChar() <= 'j') || - (PeekChar() >= 'A' && PeekChar() <= 'J')) - { - var relatedEntityKind = NextChar(); - var name = PopNode(); - var result = new Node(NodeKind.RelatedEntityDeclName, relatedEntityKind.ToString()); - return AddChild(result, name); - } - var discriminatorx = DemangleIndexAsNode(); - var namex = PopNode(IsDeclName); - return CreateWithChildren(NodeKind.LocalDeclName, discriminatorx, namex); - } - - Node PopModule() - { - var ident = PopNode(NodeKind.Identifier); - if (ident != null) - return ChangeKind(ident, NodeKind.Module); - return PopNode(NodeKind.Module); - } - - Node PopContext() - { - var mod = PopModule(); - if (mod != null) - return mod; - - var ty = PopNode(NodeKind.Type); - if (ty != null) - { - if (ty.Children.Count != 1) - return null; - var child = ty.Children[0]; - if (!IsContext(child.Kind)) - return null; - return child; - } - return PopNode(IsContext); - } - - Node PopTypeAndGetChild() - { - var ty = PopNode(NodeKind.Type); - if (ty == null || ty.Children.Count != 1) - return null; - return ty.Children[0]; - } - - - Node PopTypeAndGetAnyGeneric() - { - var child = PopTypeAndGetChild(); - if (child != null && IsAnyGeneric(child.Kind)) - return child; - return null; - } - - Node DemangleBuiltinType() - { - Node ty = null; - const int maxTypeSize = 4096; - switch (NextChar()) - { - case 'b': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.BridgeObject"); - break; - case 'B': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.UnsafeValueBuffer"); - break; - case 'f': - { - var size = DemangleIndex() - 1; - if (size <= 0 || size > maxTypeSize) - return null; - var floatName = $"Builtin.FPIEEE{size}"; - ty = new Node(NodeKind.BuiltinTypeName, floatName); - break; - } - case 'i': - { - var size = DemangleIndex() - 1; - if (size < 0 || size > maxTypeSize) - return null; - var intName = $"Builtin.Int{size}"; - ty = new Node(NodeKind.BuiltinTypeName, intName); - break; - } - case 'I': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.IntLiteral"); - break; - case 'v': - var elts = DemangleIndex() - 1; - if (elts <= 0 || elts > maxTypeSize) - return null; - var eltType = PopTypeAndGetChild(); - if (eltType == null || eltType.Kind != NodeKind.BuiltinTypeName || - !eltType.Text.StartsWith("Builtin.", StringComparison.Ordinal)) - return null; - var name = $"Builtin.Vec{elts}x{eltType.Text.Substring("Builtin.".Length)}"; - ty = new Node(NodeKind.BuiltinTypeName, name); - break; - case 'O': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.UnknownObject"); - break; - case 'o': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.NativeObject"); - break; - case 'p': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.RawPointer"); - break; - case 't': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.SILToken"); - break; - case 'w': - ty = new Node(NodeKind.BuiltinTypeName, "Builtin.Word"); - break; - default: - return null; - } - return CreateType(ty); - } - - Node DemangleAnyGenericType(NodeKind kind) - { - var name = PopNode(IsDeclName); - var ctx = PopContext(); - var nty = CreateType(CreateWithChildren(kind, ctx, name)); - AddSubstitution(nty); - return nty; - } - - Node DemangleExtensionContext() - { - var genSig = PopNode(NodeKind.DependentGenericSignature); - var module = PopModule(); - var type = PopTypeAndGetAnyGeneric(); - var ext = CreateWithChildren(NodeKind.Extension, module, type); - if (genSig != null) - ext = AddChild(ext, genSig); - return ext; - } - - Node DemanglePlainFunction() - { - var genSig = PopNode(NodeKind.DependentGenericSignature); - var type = PopFunctionType(NodeKind.FunctionType); - var labelList = PopFunctionParamLabels(type); - - if (genSig != null) - { - type = CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, type)); - } - - var name = PopNode(IsDeclName); - var ctx = PopContext(); - - if (labelList != null) - return CreateWithChildren(NodeKind.Function, ctx, name, labelList, type); - return CreateWithChildren(NodeKind.Function, ctx, name, type); - } - - - Node PopFunctionType(NodeKind kind) - { - var funcType = new Node(kind); - AddChild(funcType, PopNode(NodeKind.ThrowsAnnotation)); - funcType = AddChild(funcType, PopFunctionParams(NodeKind.ArgumentTuple)); - funcType = AddChild(funcType, PopFunctionParams(NodeKind.ReturnType)); - return CreateType(funcType); - } - - Node PopFunctionParams(NodeKind kind) - { - Node paramsType = null; - if (PopNode(NodeKind.EmptyList) != null) - { - paramsType = CreateType(new Node(NodeKind.Tuple)); - } - else - { - paramsType = PopNode(NodeKind.Type); - } - Node node = null; - - if (paramsType != null && kind == NodeKind.ArgumentTuple) - { - var @params = paramsType.Children[0]; - var numParams = @params.Kind == NodeKind.Tuple ? @params.Children.Count : 1; - node = new Node(kind, numParams); - } - else - { - node = new Node(kind); - } - - return AddChild(node, paramsType); - } - - Node PopFunctionParamLabels(Node type) - { - if (!isOldFunctionTypeMangling && PopNode(NodeKind.EmptyList) != null) - return new Node(NodeKind.LabelList); - - if (type == null || type.Kind != NodeKind.Type) - return null; - - var funcType = type.Children[0]; - if (funcType.Kind == NodeKind.DependentGenericType) - funcType = funcType.Children[1].Children[0]; - - if (funcType.Kind != NodeKind.FunctionType && funcType.Kind != NodeKind.NoEscapeFunctionType) - return null; - - var parameterType = funcType.Children[0]; - if (parameterType.Kind == NodeKind.ThrowsAnnotation) - parameterType = funcType.Children[1]; - - - if (parameterType.Index == 0) - return null; - - Func> getChildIf = (node, filterBy) => - { - for (int i = 0, n = node.Children.Count; i != n; ++i) - { - var child = node.Children[i]; - if (child.Kind == filterBy) - return new KeyValuePair(child, i); - } - return new KeyValuePair(null, 0); - }; - - Func getLabel = (@params, idx) => - { - if (isOldFunctionTypeMangling) - { - var param = @params.Children[idx]; - var label = getChildIf(param, NodeKind.TupleElementName); - - if (label.Key != null) - { - param.RemoveChildAt(label.Value); - return new Node(NodeKind.Identifier, label.Key.Text); - } - return new Node(NodeKind.FirstElementMarker); - } - return PopNode(); - }; - - var labelList = new Node(NodeKind.LabelList); - var tuple = parameterType.Children[0].Children[0]; - - if (isOldFunctionTypeMangling && (tuple != null || tuple.Kind != NodeKind.Tuple)) - return labelList; - - var hasLabels = false; - for (int i = 0; i != parameterType.Index; ++i) - { - var label = getLabel(tuple, i); - if (label == null) - return null; - - if (label.Kind != NodeKind.Identifier && label.Kind != NodeKind.FirstElementMarker) - return null; - - labelList.AddChild(label); - hasLabels |= label.Kind != NodeKind.FirstElementMarker; - } - - if (!hasLabels) - return new Node(NodeKind.LabelList); - - if (!isOldFunctionTypeMangling) - labelList.ReverseChildren(); - - return labelList; - } - - Node PopTuple() - { - var root = new Node(NodeKind.Tuple); - - if (PopNode(NodeKind.EmptyList) == null) - { - var firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker)) != null; - var tupleElmt = new Node(NodeKind.TupleElement); - AddChild(tupleElmt, PopNode(NodeKind.VariadicMarker)); - Node ident; - if ((ident = PopNode(NodeKind.Identifier)) != null) - { - tupleElmt.AddChild(new Node(NodeKind.TupleElementName, ident.Text)); - } - var ty = PopNode(NodeKind.Type); - if (ty == null) - return null; - tupleElmt.AddChild(ty); - root.AddChild(tupleElmt); - } while (!firstElem); - - root.ReverseChildren(); - } - return CreateType(root); - } - - Node PopTypeList() - { - var root = new Node(NodeKind.TypeList); - - if (PopNode(NodeKind.EmptyList) == null) - { - var firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker) != null); - var ty = PopNode(NodeKind.Type); - if (ty == null) - return ty; - root.AddChild(ty); - } while (!firstElem); - root.ReverseChildren(); - } - return root; - } - - Node PopProtocol() - { - Node type; - if ((type = PopNode(NodeKind.Type)) != null) - { - if (type.Children.Count < 1) - return null; - - if (!IsProtocolNode(type)) - return null; - return type; - } - - Node symbolicRef; - if ((symbolicRef = PopNode(NodeKind.ProtocolSymbolicReference)) != null) - { - return symbolicRef; - } - - var name = PopNode(IsDeclName); - var ctx = PopContext(); - var proto = CreateWithChildren(NodeKind.Protocol, ctx, name); - return CreateType(proto); - } - - Node PopAnyProtocolConformanceList() - { - var conformanceList = new Node(NodeKind.AnyProtocolConformanceList); - if (PopNode(NodeKind.EmptyList) == null) - { - var firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker) != null); - var anyConformance = PopAnyProtocolConformance(); - if (anyConformance == null) - return null; - conformanceList.AddChild(anyConformance); - } while (!firstElem); - conformanceList.ReverseChildren(); - } - return conformanceList; - } - - Node PopAnyProtocolConformance() - { - return PopNode((kind) => - { - switch (kind) - { - case NodeKind.ConcreteProtocolConformance: - case NodeKind.DependentProtocolConformanceRoot: - case NodeKind.DependentProtocolConformanceInherited: - case NodeKind.DependentProtocolConformanceAssociated: - return true; - default: - return false; - } - }); - } - - Node DemangleRetroactiveProtocolConformanceRef() - { - var module = PopModule(); - var proto = PopProtocol(); - var protocolConformanceRef = CreateWithChildren(NodeKind.ProtocolConformanceRefInOtherModule, proto, module); - return protocolConformanceRef; - } - - Node DemangleConcreteProtocolConformance() - { - var conditionalConformanceList = PopAnyProtocolConformanceList(); - - var conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInTypeModule); - if (conformanceRef == null) - { - conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInProtocolModule); - } - if (conformanceRef == null) - conformanceRef = DemangleRetroactiveProtocolConformanceRef(); - - var type = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.ConcreteProtocolConformance, - type, conformanceRef, conditionalConformanceList); - } - - - Node DemangleProtocolConformance() - { - var conditionalConformanceList = PopAnyProtocolConformanceList(); - - var conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInTypeModule); - if (conformanceRef == null) - { - conformanceRef = PopNode(NodeKind.ProtocolConformanceRefInProtocolModule); - } - - if (conformanceRef == null) - conformanceRef = DemangleRetroactiveProtocolConformanceRef(); - - var type = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.ConcreteProtocolConformance, type, conformanceRef, conditionalConformanceList); - } - - Node PopDependentProtocolConformance() - { - return PopNode((kind) => - { - switch (kind) - { - case NodeKind.DependentProtocolConformanceRoot: - case NodeKind.DependentProtocolConformanceInherited: - case NodeKind.DependentProtocolConformanceAssociated: - return true; - default: - return false; - } - }); - } - - Node DemangleDependentProtocolConformanceRoot() - { - var index = DemangleIndex(); - var conformance = - index > 0 ? new Node(NodeKind.DependentProtocolConformanceRoot, index - 1) - : new Node(NodeKind.DependentProtocolConformanceRoot); - Node protocol = null; - if ((protocol = PopProtocol()) != null) - conformance.AddChild(protocol); - else - return null; - - Node dependentType; - if ((dependentType = PopNode(NodeKind.Type)) != null) - conformance.AddChild(dependentType); - else - return null; - - return conformance; - } - - Node DemangleDependentProtocolConformanceInherited() - { - var index = DemangleIndex(); - var conformance = - index > 0 ? new Node(NodeKind.DependentProtocolConformanceInherited, index - 1) - : new Node(NodeKind.DependentProtocolConformanceInherited); - Node protocol; - if ((protocol = PopProtocol()) != null) - conformance.AddChild(protocol); - else - return null; - - Node nested; - - if ((nested = PopDependentProtocolConformance()) != null) - conformance.AddChild(nested); - else - return null; - - conformance.ReverseChildren(); - return conformance; - } - - Node PopDependentAssociatedConformance() - { - var protocol = PopProtocol(); - var dependentType = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.DependentAssociatedConformance, dependentType, protocol); - } - - Node DemangleDependentProtocolConformanceAssociated() - { - var index = DemangleIndex(); - var conformance = index > 0 ? new Node(NodeKind.DependentProtocolConformanceRoot, index - 1) - : new Node(NodeKind.DependentProtocolConformanceRoot); - - Node associatedConformance; - if ((associatedConformance = PopDependentAssociatedConformance()) != null) - conformance.AddChild(associatedConformance); - else - return null; - - Node nested; - if ((nested = PopDependentProtocolConformance()) != null) - conformance.AddChild(nested); - else - return null; - - conformance.ReverseChildren(); - - return conformance; - } - - Node DemangleRetroactiveConformance() - { - var index = DemangleIndex(); - if (index < 0) - return null; - - var conformance = PopAnyProtocolConformance(); - if (conformance == null) - return null; - - var retroactiveConformance = new Node(NodeKind.RetroactiveConformance, index); - retroactiveConformance.AddChild(conformance); - return retroactiveConformance; - } - - Node DemangleBoundGenericType() - { - Node retroactiveConformances = null; - Node retroactiveConformance; - while ((retroactiveConformance = PopNode(NodeKind.RetroactiveConformance)) != null) - { - if (retroactiveConformances == null) - retroactiveConformances = new Node(NodeKind.TypeList); - retroactiveConformances.AddChild(retroactiveConformance); - } - if (retroactiveConformances != null) - retroactiveConformances.ReverseChildren(); - - var typeListList = new List(); - for (; ; ) - { - var tlist = new Node(NodeKind.TypeList); - typeListList.Add(tlist); - Node ty; - while ((ty = PopNode(NodeKind.Type)) != null) - { - tlist.AddChild(ty); - } - tlist.ReverseChildren(); - if (PopNode(NodeKind.EmptyList) != null) - break; - if (PopNode(NodeKind.FirstElementMarker) == null) - return null; - } - var nominal = PopTypeAndGetAnyGeneric(); - var boundNode = DemangleBoundGenericArgs(nominal, typeListList, 0); - AddChild(boundNode, retroactiveConformances); - var nty = CreateType(boundNode); - AddSubstitution(nty); - return nty; - } - - Node DemangleBoundGenericArgs(Node nominal, List typeLists, int typeListIdx) - { - if (nominal == null) - return null; - - if (typeListIdx >= typeLists.Count) - return null; - - if (nominal.Kind == NodeKind.TypeSymbolicReference || nominal.Kind == NodeKind.ProtocolSymbolicReference) - { - var remainingTypeList = new Node(NodeKind.TypeList); - for (int i = typeLists.Count - 1; i >= typeListIdx && i < typeLists.Count; --i) - { - var list = typeLists[i]; - foreach (var child in list.Children) - { - remainingTypeList.AddChild(child); - } - } - return CreateWithChildren(NodeKind.BoundGenericOtherNominalType, CreateType(nominal), remainingTypeList); - } - - if (nominal.Children.Count == 0) - return null; - var context = nominal.Children[0]; - - var consumesGenericArgs = true; - switch (nominal.Kind) - { - case NodeKind.Variable: - case NodeKind.ExplicitClosure: - case NodeKind.Subscript: - consumesGenericArgs = false; - break; - default: - break; - } - - var args = typeLists[typeListIdx]; - if (consumesGenericArgs) - ++typeListIdx; - - if (typeListIdx < typeLists.Count) - { - Node boundParent = null; - if (context.Kind == NodeKind.Extension) - { - boundParent = DemangleBoundGenericArgs(context.Children[1], typeLists, typeListIdx); - boundParent = CreateWithChildren(NodeKind.Extension, context.Children[0], boundParent); - if (context.Children.Count == 3) - { - AddChild(boundParent, context.Children[2]); - } - } - else - { - boundParent = DemangleBoundGenericArgs(context, typeLists, typeListIdx); - } - - var newNominal = CreateWithChild(nominal.Kind, boundParent); - if (newNominal == null) - return null; - - for (int idx = 1; idx < nominal.Children.Count; ++idx) - { - AddChild(newNominal, nominal.Children[idx]); - } - nominal = newNominal; - } - if (!consumesGenericArgs) - return nominal; - - if (args.Children.Count == 0) - return nominal; - - NodeKind kind; - switch (nominal.Kind) - { - case NodeKind.Class: - kind = NodeKind.BoundGenericClass; - break; - case NodeKind.Structure: - kind = NodeKind.BoundGenericStructure; - break; - case NodeKind.Enum: - kind = NodeKind.BoundGenericEnum; - break; - case NodeKind.Protocol: - kind = NodeKind.BoundGenericProtocol; - break; - case NodeKind.OtherNominalType: - kind = NodeKind.BoundGenericOtherNominalType; - break; - case NodeKind.TypeAlias: - kind = NodeKind.BoundGenericTypeAlias; - break; - case NodeKind.Function: - case NodeKind.Constructor: - return CreateWithChildren(NodeKind.BoundGenericFunction, nominal, args); - default: - return null; - } - return CreateWithChildren(kind, CreateType(nominal), args); - } - - Node DemangleImpleParamConvention() - { - string attr = null; - switch (NextChar()) - { - case 'i': attr = "@in"; break; - case 'c': attr = "@in_constant"; break; - case 'l': attr = "@inout"; break; - case 'b': attr = "@inout_aliasable"; break; - case 'n': attr = "@in_guaranteed"; break; - case 'x': attr = "@owned"; break; - case 'g': attr = "@guaranteed"; break; - case 'e': attr = "@deallocating"; break; - case 'y': attr = "@unowned"; break; - default: - PushBack(); - return null; - } - return CreateWithChild(NodeKind.ImplParameter, new Node(NodeKind.ImplConvention, attr)); - } - - Node DemangleImplResultConvention(NodeKind convKind) - { - string attr = null; - switch (NextChar()) - { - case 'r': attr = "@out"; break; - case 'o': attr = "@owned"; break; - case 'd': attr = "@unowned"; break; - case 'u': attr = "@unowned_inner_pointer"; break; - case 'a': attr = "@autoreleased"; break; - default: - PushBack(); - return null; - } - return CreateWithChild(convKind, new Node(NodeKind.ImplConvention, attr)); - } - - Node DemangleImplFunctionType() - { - var type = new Node(NodeKind.ImplFunctionType); - - var genSig = PopNode(NodeKind.DependentGenericSignature); - if (genSig != null && NextIf('P')) - genSig = ChangeKind(genSig, NodeKind.DependentPseudogenericSignature); - - if (NextIf('e')) - type.AddChild(new Node(NodeKind.ImplEscaping)); - - string cattr = null; - switch (NextChar()) - { - case 'y': cattr = "@callee_unowned"; break; - case 'g': cattr = "@callee_guaranteed"; break; - case 'x': cattr = "@callee_owned"; break; - case 't': cattr = "@convention(thin)"; break; - default: - return null; - } - type.AddChild(new Node(NodeKind.ImplConvention, cattr)); - - string fattr = null; - switch (NextChar()) - { - case 'B': fattr = "@convention(block)"; break; - case 'C': fattr = "@convention(c)"; break; - case 'M': fattr = "@convention(method)"; break; - case 'O': fattr = "@convention(objc_method)"; break; - case 'K': fattr = "@convention(closure)"; break; - case 'W': fattr = "@convention(witness_method)"; break; - default: - PushBack(); - break; - } - if (fattr != null) - type.AddChild(new Node(NodeKind.ImplFunctionAttribute, fattr)); - - AddChild(type, genSig); - - var numTypesToAdd = 0; - Node param; - while ((param = DemangleImpleParamConvention()) != null) - { - type = AddChild(type, param); - numTypesToAdd++; - } - Node result; - while ((result = DemangleImplResultConvention(NodeKind.ImplResult)) != null) - { - type = AddChild(type, result); - numTypesToAdd++; - } - if (NextIf('z')) - { - var errorResult = DemangleImplResultConvention(NodeKind.ImplErrorResult); - if (errorResult == null) - return null; - type = AddChild(type, errorResult); - numTypesToAdd++; - } - if (!NextIf('_')) - return null; - - for (int idx = 0; idx < numTypesToAdd; ++idx) - { - var convTy = PopNode(NodeKind.Type); - if (convTy == null) - return null; - type.Children[type.Children.Count - idx - 1].AddChild(convTy); - } - - return CreateType(type); - } - - Node DemangleMetatype() - { - switch (NextChar()) - { - case 'c': - return CreateWithChild(NodeKind.ProtocolConformanceDescriptor, PopProtocolConformance()); - case 'f': - return CreateWithPoppedType(NodeKind.FullTypeMetadata); - case 'P': - return CreateWithPoppedType(NodeKind.GenericTypeMetadataPattern); - case 'a': - return CreateWithPoppedType(NodeKind.TypeMetadataAccessFunction); - case 'I': - return CreateWithPoppedType(NodeKind.TypeMetadataInstantiationCache); - case 'i': - return CreateWithPoppedType(NodeKind.TypeMetadataInstantiationFunction); - case 'r': - return CreateWithPoppedType(NodeKind.TypeMetadataCompletionFunction); - case 'l': - return CreateWithPoppedType( - NodeKind.TypeMetadataSingletonInitializationCache); - case 'L': - return CreateWithPoppedType(NodeKind.TypeMetadataLazyCache); - case 'm': - return CreateWithPoppedType(NodeKind.Metaclass); - case 'n': - return CreateWithPoppedType(NodeKind.NominalTypeDescriptor); - case 'o': - return CreateWithPoppedType(NodeKind.ClassMetadataBaseOffset); - case 'p': - return CreateWithChild(NodeKind.ProtocolDescriptor, PopProtocol()); - case 'S': - return CreateWithChild(NodeKind.ProtocolSelfConformanceDescriptor, - PopProtocol()); - case 'u': - return CreateWithPoppedType(NodeKind.MethodLookupFunction); - case 'U': - return CreateWithPoppedType(NodeKind.ObjCMetadataUpdateFunction); - case 'B': - return CreateWithChild(NodeKind.ReflectionMetadataBuiltinDescriptor, - PopNode(NodeKind.Type)); - case 'F': - return CreateWithChild(NodeKind.ReflectionMetadataFieldDescriptor, - PopNode(NodeKind.Type)); - case 'A': - return CreateWithChild(NodeKind.ReflectionMetadataAssocTypeDescriptor, - PopProtocolConformance()); - case 'C': - { - Node Ty = PopNode(NodeKind.Type); - if (Ty == null || !IsAnyGeneric(Ty.Children[0].Kind)) - return null; - return CreateWithChild(NodeKind.ReflectionMetadataSuperclassDescriptor, - Ty.Children[0]); - } - case 'V': - return CreateWithChild(NodeKind.PropertyDescriptor, - PopNode(IsEntity)); - case 'X': - return DemanglePrivateContextDescriptor(); - default: - return null; - } - } - - Node DemanglePrivateContextDescriptor() - { - switch (NextChar()) - { - case 'E': - { - var extension = PopContext(); - if (extension == null) - return null; - return CreateWithChild(NodeKind.ExtensionDescriptor, extension); - } - case 'M': - { - var module = PopModule(); - if (module == null) - return null; - return CreateWithChild(NodeKind.ModuleDescriptor, module); - } - case 'Y': - { - var discriminator = PopNode(); - if (discriminator == null) - return null; - var context = PopContext(); - if (context == null) - return null; - - var node = new Node(NodeKind.AnonymousDescriptor); - node.AddChild(context); - node.AddChild(discriminator); - return node; - } - case 'X': - { - var context = PopContext(); - if (context == null) - return null; - return CreateWithChild(NodeKind.AnonymousDescriptor, context); - } - case 'A': - { - var path = PopAssocTypePath(); - if (path == null) - return null; - var @base = PopNode(NodeKind.Type); - if (@base == null) - return null; - return CreateWithChildren(NodeKind.AssociatedTypeGenericParamRef, - @base, path); - } - default: - return null; - } - } - - Node DemangleArchetype() - { - switch (NextChar()) - { - case 'a': - { - var ident = PopNode(NodeKind.Identifier); - var archeTy = PopTypeAndGetChild(); - var assocTy = CreateType(CreateWithChildren(NodeKind.AssociatedTypeRef, archeTy, ident)); - AddSubstitution(assocTy); - return assocTy; - } - case 'y': - { - var t = DemangleAssociatedTypeSimple(DemangleGenericParamIndex()); - AddSubstitution(t); - return t; - } - case 'z': - { - var t = DemangleAssociatedTypeSimple(GetDependentGenericParamType(0, 0)); - AddSubstitution(t); - return t; - } - case 'Y': - { - var t = DemangleAssociatedTypeCompound(DemangleGenericParamIndex()); - AddSubstitution(t); - return t; - } - case 'Z': - { - var t = DemangleAssociatedTypeCompound(GetDependentGenericParamType(0, 0)); - AddSubstitution(t); - return t; - } - default: - return null; - } - } - - Node DemangleAssociatedTypeSimple(Node genericParamIdx) - { - var GPI = CreateType(genericParamIdx); - var ATName = PopAssocTypeName(); - return CreateType(CreateWithChildren(NodeKind.DependentMemberType, GPI, ATName)); - } - - Node DemangleAssociatedTypeCompound(Node genericParamIdx) - { - var assocTyNames = new List(); - bool firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker) != null); - var assocTyName = PopAssocTypeName(); - if (assocTyName == null) - return null; - assocTyNames.Add(assocTyName); - } while (!firstElem); - - var @base = genericParamIdx; - - - for (int i = assocTyNames.Count - 1; i >= 0; --i) - { - var assocTy = assocTyNames[i]; - var depTy = new Node(NodeKind.DependentMemberType); - depTy = AddChild(depTy, CreateType(@base)); - @base = AddChild(depTy, assocTy); - } - return CreateType(@base); - } - - Node PopAssocTypeName() - { - var proto = PopNode(NodeKind.Type); - if (proto != null && !IsProtocolNode(proto)) - return null; - - // If we haven't seen a protocol, check for a symbolic reference. - if (proto == null) - proto = PopNode(NodeKind.ProtocolSymbolicReference); - - var id = PopNode(NodeKind.Identifier); - var assocTy = ChangeKind(id, NodeKind.DependentAssociatedTypeRef); - AddChild(assocTy, proto); - return assocTy; - } - - Node PopAssocTypePath() - { - var assocTypePath = new Node(NodeKind.AssocTypePath); - bool firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker) != null); - var assocTy = PopAssocTypeName(); - if (assocTy == null) - return null; - assocTypePath.AddChild(assocTy); - } while (!firstElem); - assocTypePath.ReverseChildren(); - return assocTypePath; - } - - Node GetDependentGenericParamType(int depth, int index) - { - if (depth < 0 || index < 0) - return null; - - StringBuilder name = new StringBuilder(); - int idxChar = index; - do - { - name.Append((char)('A' + (idxChar % 26))); - idxChar /= 26; - } while (idxChar > 0); - if (depth != 0) - name.Append(depth); - - var paramTy = new Node(NodeKind.DependentGenericParamType, name.ToString()); - paramTy.AddChild(new Node(NodeKind.Index, depth)); - paramTy.AddChild(new Node(NodeKind.Index, index)); - return paramTy; - } - - Node DemangleGenericParamIndex() - { - if (NextIf('d')) - { - int depth = DemangleIndex() + 1; - int index = DemangleIndex(); - return GetDependentGenericParamType(depth, index); - } - if (NextIf('z')) - { - return GetDependentGenericParamType(0, 0); - } - return GetDependentGenericParamType(0, DemangleIndex() + 1); - } - - Node PopProtocolConformance() - { - var genSig = PopNode(NodeKind.DependentGenericSignature); - var module = PopModule(); - var proto = PopProtocol(); - var type = PopNode(NodeKind.Type); - Node Ident = null; - if (type == null) - { - // Property behavior conformance - Ident = PopNode(NodeKind.Identifier); - type = PopNode(NodeKind.Type); - } - if (genSig != null) - { - type = CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, type)); - } - var Conf = CreateWithChildren(NodeKind.ProtocolConformance, type, proto, module); - AddChild(Conf, Ident); - return Conf; - } - - Node DemangleThunkOrSpecialization() - { - var c = NextChar(); - switch (c) - { - case 'c': return CreateWithChild(NodeKind.CurryThunk, PopNode(IsEntity)); - case 'j': return CreateWithChild(NodeKind.DispatchThunk, PopNode(IsEntity)); - case 'q': return CreateWithChild(NodeKind.MethodDescriptor, PopNode(IsEntity)); - case 'o': return new Node(NodeKind.ObjCAttribute); - case 'O': return new Node(NodeKind.NonObjCAttribute); - case 'D': return new Node(NodeKind.DynamicAttribute); - case 'd': return new Node(NodeKind.DirectMethodReferenceAttribute); - case 'a': return new Node(NodeKind.PartialApplyObjCForwarder); - case 'A': return new Node(NodeKind.PartialApplyForwarder); - case 'm': return new Node(NodeKind.MergedFunction); - case 'X': return new Node(NodeKind.DynamicallyReplaceableFunctionVar); - case 'x': return new Node(NodeKind.DynamicallyReplaceableFunctionKey); - case 'I': return new Node(NodeKind.DynamicallyReplaceableFunctionImpl); - case 'C': - { - var type = PopNode(NodeKind.Type); - return CreateWithChild(NodeKind.CoroutineContinuationPrototype, type); - } - case 'V': - { - var @base = PopNode(IsEntity); - var derived = PopNode(IsEntity); - return CreateWithChildren(NodeKind.VTableThunk, derived, @base); - } - case 'W': - { - var entity = PopNode(IsEntity); - var conf = PopProtocolConformance(); - return CreateWithChildren(NodeKind.ProtocolWitness, conf, entity); - } - case 'S': - return CreateWithChild(NodeKind.ProtocolSelfConformanceWitness, - PopNode(IsEntity)); - case 'R': - case 'r': - { - var thunk = new Node(c == 'R' ? - NodeKind.ReabstractionThunkHelper : - NodeKind.ReabstractionThunk); - Node genSig; - if ((genSig = PopNode(NodeKind.DependentGenericSignature)) != null) - AddChild(thunk, genSig); - var Ty2 = PopNode(NodeKind.Type); - thunk = AddChild(thunk, PopNode(NodeKind.Type)); - return AddChild(thunk, Ty2); - } - case 'g': - return DemangleGenericSpecialization(NodeKind.GenericSpecialization); - case 'G': - return DemangleGenericSpecialization(NodeKind.GenericSpecializationNotReAbstracted); - case 'i': - return DemangleGenericSpecialization(NodeKind.InlinedGenericFunction); - case 'p': - { - var spec = DemangleSpecAttributes(NodeKind.GenericPartialSpecialization); - var param = CreateWithChild(NodeKind.GenericSpecializationParam, PopNode(NodeKind.Type)); - return AddChild(spec, param); - } - case 'P': - { - var spec = DemangleSpecAttributes(NodeKind.GenericPartialSpecializationNotReAbstracted); - var param = CreateWithChild(NodeKind.GenericSpecializationParam, PopNode(NodeKind.Type)); - return AddChild(spec, param); - } - case 'f': - return DemangleFunctionSpecialization(); - case 'K': - case 'k': - { - var nodeKind = c == 'K' ? NodeKind.KeyPathGetterThunkHelper - : NodeKind.KeyPathSetterThunkHelper; - var types = new List(); - var node = PopNode(); - if (node == null || node.Kind != NodeKind.Type) - return null; - do - { - types.Add(node); - node = PopNode(); - } while (node != null && node.Kind == NodeKind.Type); - - Node result; - if (node != null) - { - if (node.Kind == NodeKind.DependentGenericSignature) - { - var decl = PopNode(); - if (decl == null) - return null; - result = CreateWithChildren(nodeKind, decl, /*sig*/ node); - } - else - { - result = CreateWithChild(nodeKind, /*decl*/ node); - } - } - else - { - return null; - } - foreach (var i in types) - { - result.AddChild(i); - } - return result; - } - case 'l': - { - var assocTypeName = PopAssocTypeName(); - if (assocTypeName == null) - return null; - - return CreateWithChild(NodeKind.AssociatedTypeDescriptor, - assocTypeName); - } - case 'L': - return CreateWithChild(NodeKind.ProtocolRequirementsBaseDescriptor, - PopProtocol()); - case 'M': - return CreateWithChild(NodeKind.DefaultAssociatedTypeMetadataAccessor, - PopAssocTypeName()); - - case 'n': - { - var requirementTy = PopProtocol(); - var conformingType = PopAssocTypePath(); - var protoTy = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.AssociatedConformanceDescriptor, - protoTy, conformingType, requirementTy); - } - - case 'N': - { - var requirementTy = PopProtocol(); - var assocTypePath = PopAssocTypePath(); - var protoTy = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.DefaultAssociatedConformanceAccessor, - protoTy, assocTypePath, requirementTy); - } - - case 'b': - { - var requirementTy = PopProtocol(); - var protoTy = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.BaseConformanceDescriptor, - protoTy, requirementTy); - } - - case 'H': - case 'h': - { - var nodeKind = c == 'H' ? NodeKind.KeyPathEqualsThunkHelper - : NodeKind.KeyPathHashThunkHelper; - Node genericSig = null; - var types = new List(); - - var node = PopNode(); - if (node != null) - { - if (node.Kind == NodeKind.DependentGenericSignature) - { - genericSig = node; - } - else if (node.Kind == NodeKind.Type) - { - types.Add(node); - } - else - { - return null; - } - } - else - { - return null; - } - - Node node1; - while ((node1 = PopNode()) != null) - { - if (node1.Kind != NodeKind.Type) - { - return null; - } - types.Add(node); - } - - var result = new Node(nodeKind); - foreach (var i in types) - { - result.AddChild(i); - } - if (genericSig != null) - result.AddChild(genericSig); - return result; - } - case 'v': - { - int idx = DemangleIndex(); - if (idx < 0) - return null; - return new Node(NodeKind.OutlinedVariable, idx); - } - case 'e': - { - string @params = DemangleBridgedMethodParams(); - if (string.IsNullOrEmpty(@params)) - return null; - return new Node(NodeKind.OutlinedBridgedMethod, @params); - } - default: - return null; - } - } - - string DemangleBridgedMethodParams() - { - if (NextIf('_')) - return ""; - - StringBuilder Str = new StringBuilder(); - - var kind = NextChar(); - switch (kind) - { - default: - return ""; - case 'p': - case 'a': - case 'm': - Str.Append(kind); - break; - } - - while (!NextIf('_')) - { - var c = NextChar(); - if (c != 0 && c != 'n' && c != 'b') - return ""; - Str.Append(c); - } - return Str.ToString(); - } - - Node DemangleGenericSpecialization(NodeKind SpecKind) - { - var Spec = DemangleSpecAttributes(SpecKind); - if (Spec == null) - return null; - var TyList = PopTypeList(); - if (TyList == null) - return null; - foreach (var Ty in TyList.Children) - { - Spec.AddChild(CreateWithChild(NodeKind.GenericSpecializationParam, Ty)); - } - return Spec; - } - - - Node DemangleFunctionSpecialization() - { - var spec = DemangleSpecAttributes(NodeKind.FunctionSignatureSpecialization); - ulong paramIdx = 0; - while (spec != null && !NextIf('_')) - { - spec = AddChild(spec, DemangleFuncSpecParam(paramIdx)); - paramIdx++; - } - if (!NextIf('n')) - spec = AddChild(spec, DemangleFuncSpecParam((~(ulong)0))); - - if (spec == null) - return null; - - // Add the required parameters in reverse order. - for (int idx = 0, num = spec.Children.Count; idx < num; ++idx) - { - var param = spec.Children[num - idx - 1]; - if (param.Kind != NodeKind.FunctionSignatureSpecializationParam) - continue; - - if (param.Children.Count == 0) - continue; - var kindNd = param.Children[0]; - var paramKind = (FunctionSigSpecializationParamKind)kindNd.Index; - switch (paramKind) - { - case FunctionSigSpecializationParamKind.ConstantPropFunction: - case FunctionSigSpecializationParamKind.ConstantPropGlobal: - case FunctionSigSpecializationParamKind.ConstantPropString: - case FunctionSigSpecializationParamKind.ClosureProp: - { - var fixedChildren = param.Children.Count; - Node ty; - while ((ty = PopNode(NodeKind.Type)) != null) - { - if (paramKind != FunctionSigSpecializationParamKind.ClosureProp) - return null; - param = AddChild(param, ty); - } - var name = PopNode(NodeKind.Identifier); - if (name == null) - return null; - string nameText = name.Text; - if (paramKind == FunctionSigSpecializationParamKind.ConstantPropString && !String.IsNullOrEmpty(nameText) - && nameText[0] == '_') - { - // A '_' escapes a leading digit or '_' of a string constant. - nameText = nameText.Substring(1); - } - AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, nameText)); - param.ReverseChildren(fixedChildren); - break; - } - default: - break; - } - } - return spec; - } - - Node DemangleFuncSpecParam(ulong paramIdx) - { - var param = new Node(NodeKind.FunctionSignatureSpecializationParam, (long)paramIdx); - switch (NextChar()) - { - case 'n': - return param; - case 'c': - // Consumes an identifier and multiple type parameters. - // The parameters will be added later. - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ClosureProp)); - case 'p': - { - switch (NextChar()) - { - case 'f': - // Consumes an identifier parameter, which will be added later. - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (long)(FunctionSigSpecializationParamKind.ConstantPropFunction))); - case 'g': - // Consumes an identifier parameter, which will be added later. - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropGlobal)); - case 'i': - return AddFuncSpecParamNumber(param, FunctionSigSpecializationParamKind.ConstantPropInteger); - case 'd': - return AddFuncSpecParamNumber(param, FunctionSigSpecializationParamKind.ConstantPropFloat); - case 's': - { - // Consumes an identifier parameter (the string constant), - // which will be added later. - string encoding = null; - switch (NextChar()) - { - case 'b': encoding = "u8"; break; - case 'w': encoding = "u16"; break; - case 'c': encoding = "objc"; break; - default: return null; - } - AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (long)FunctionSigSpecializationParamKind.ConstantPropString)); - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, encoding)); - } - default: - return null; - } - } - case 'e': - { - uint value = (uint)FunctionSigSpecializationParamKind.ExistentialToGeneric; - if (NextIf('D')) - value |= (uint)FunctionSigSpecializationParamKind.Dead; - if (NextIf('G')) - value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf('O')) - value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'd': - { - uint value = (uint)FunctionSigSpecializationParamKind.Dead; - if (NextIf('G')) - value |= (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf('O')) - value |= (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'g': - { - uint value = (uint)FunctionSigSpecializationParamKind.OwnedToGuaranteed; - if (NextIf('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'o': - { - uint value = (uint)FunctionSigSpecializationParamKind.GuaranteedToOwned; - if (NextIf('X')) - value |= (uint)FunctionSigSpecializationParamKind.SROA; - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, value)); - } - case 'x': - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.SROA)); - case 'i': - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.BoxToValue)); - case 's': - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamKind, - (uint)FunctionSigSpecializationParamKind.BoxToStack)); - default: - return null; - } - } - - Node AddFuncSpecParamNumber(Node param, FunctionSigSpecializationParamKind kind) - { - param.AddChild(new Node(NodeKind.FunctionSignatureSpecializationParamKind, (uint)kind)); - var str = new StringBuilder(); - while (Char.IsDigit(PeekChar())) - { - str.Append(NextChar()); - } - if (str.Length == 0) - return null; - return AddChild(param, new Node(NodeKind.FunctionSignatureSpecializationParamPayload, str.ToString())); - } - - Node DemangleSpecAttributes(NodeKind SpecKind) - { - bool isFragile = NextIf('q'); - - int passID = (int)NextChar() - '0'; - if (passID < 0 || passID > 9) - return null; - - var specNd = new Node(SpecKind); - if (isFragile) - specNd.AddChild(new Node(NodeKind.SpecializationIsFragile)); - - specNd.AddChild(new Node(NodeKind.SpecializationPassID, passID)); - return specNd; - } - - Node DemangleWitness() - { - switch (NextChar()) - { - case 'C': - return CreateWithChild(NodeKind.EnumCase, PopNode(IsEntity)); - case 'V': - return CreateWithChild(NodeKind.ValueWitnessTable, PopNode(NodeKind.Type)); - case 'v': - { - uint directness; - switch (NextChar()) - { - case 'd': directness = (uint)Directness.Direct; break; - case 'i': directness = (uint)Directness.Indirect; break; - default: return null; - } - return CreateWithChildren(NodeKind.FieldOffset, new Node(NodeKind.Directness, directness), - PopNode(IsEntity)); - } - case 'S': - return CreateWithChild(NodeKind.ProtocolSelfConformanceWitnessTable, PopProtocol()); - case 'P': - return CreateWithChild(NodeKind.ProtocolWitnessTable, PopProtocolConformance()); - case 'p': - return CreateWithChild(NodeKind.ProtocolWitnessTablePattern, PopProtocolConformance()); - case 'G': - return CreateWithChild(NodeKind.GenericProtocolWitnessTable, PopProtocolConformance()); - case 'I': - return CreateWithChild(NodeKind.GenericProtocolWitnessTableInstantiationFunction, PopProtocolConformance()); - - case 'r': - return CreateWithChild(NodeKind.ResilientProtocolWitnessTable, PopProtocolConformance()); - - case 'l': - { - var conf = PopProtocolConformance(); - var type = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.LazyProtocolWitnessTableAccessor, type, conf); - } - case 'L': - { - var conf = PopProtocolConformance(); - var type = PopNode(NodeKind.Type); - return CreateWithChildren(NodeKind.LazyProtocolWitnessTableCacheVariable, type, conf); - } - case 'a': - return CreateWithChild(NodeKind.ProtocolWitnessTableAccessor, PopProtocolConformance()); - case 't': - { - var name = PopNode(IsDeclName); - var conf = PopProtocolConformance(); - return CreateWithChildren(NodeKind.AssociatedTypeMetadataAccessor, conf, name); - } - case 'T': - { - var protoTy = PopNode(NodeKind.Type); - var conformingType = PopAssocTypePath(); - var conf = PopProtocolConformance(); - return CreateWithChildren(NodeKind.AssociatedTypeWitnessTableAccessor, conf, conformingType, protoTy); - } - case 'b': - { - var protoTy = PopNode(NodeKind.Type); - var conf = PopProtocolConformance(); - return CreateWithChildren(NodeKind.BaseWitnessTableAccessor, conf, protoTy); - } - case 'O': - { - switch (NextChar()) - { - case 'y': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedCopy, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedCopy, PopNode(NodeKind.Type)); - } - case 'e': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedConsume, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedConsume, PopNode(NodeKind.Type)); - } - case 'r': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedRetain, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedRetain, PopNode(NodeKind.Type)); - } - case 's': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedRelease, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedRelease, PopNode(NodeKind.Type)); - } - case 'b': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedInitializeWithTake, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedInitializeWithTake, PopNode(NodeKind.Type)); - } - case 'c': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedInitializeWithCopy, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedInitializeWithCopy, PopNode(NodeKind.Type)); - } - case 'd': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedAssignWithTake, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedAssignWithTake, PopNode(NodeKind.Type)); - } - case 'f': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedAssignWithCopy, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedAssignWithCopy, PopNode(NodeKind.Type)); - } - case 'h': - { - Node sig; - if ((sig = PopNode(NodeKind.DependentGenericSignature)) != null) - return CreateWithChildren(NodeKind.OutlinedDestroy, PopNode(NodeKind.Type), sig); - return CreateWithChild(NodeKind.OutlinedDestroy, PopNode(NodeKind.Type)); - } - default: - return null; - } - } - default: - return null; - } - } - - Node DemangleSpecialType() - { - char specialChar; - switch (specialChar = NextChar()) - { - case 'E': - return PopFunctionType(NodeKind.NoEscapeFunctionType); - case 'A': - return PopFunctionType(NodeKind.EscapingAutoClosureType); - case 'f': - return PopFunctionType(NodeKind.ThinFunctionType); - case 'K': - return PopFunctionType(NodeKind.AutoClosureType); - case 'U': - return PopFunctionType(NodeKind.UncurriedFunctionType); - case 'B': - return PopFunctionType(NodeKind.ObjCBlock); - case 'C': - return PopFunctionType(NodeKind.CFunctionPointer); - case 'o': - return CreateType(CreateWithChild(NodeKind.Unowned, PopNode(NodeKind.Type))); - case 'u': - return CreateType(CreateWithChild(NodeKind.Unmanaged, PopNode(NodeKind.Type))); - case 'w': - return CreateType(CreateWithChild(NodeKind.Weak, PopNode(NodeKind.Type))); - case 'b': - return CreateType(CreateWithChild(NodeKind.SILBoxType, PopNode(NodeKind.Type))); - case 'D': - return CreateType(CreateWithChild(NodeKind.DynamicSelf, PopNode(NodeKind.Type))); - case 'M': - { - var MTR = DemangleMetatypeRepresentation(); - var type = PopNode(NodeKind.Type); - return CreateType(CreateWithChildren(NodeKind.Metatype, MTR, type)); - } - case 'm': - { - var MTR = DemangleMetatypeRepresentation(); - var type = PopNode(NodeKind.Type); - return CreateType(CreateWithChildren(NodeKind.ExistentialMetatype, MTR, type)); - } - case 'p': - return CreateType(CreateWithChild(NodeKind.ExistentialMetatype, PopNode(NodeKind.Type))); - case 'c': - { - var Superclass = PopNode(NodeKind.Type); - var Protocols = DemangleProtocolList(); - return CreateType(CreateWithChildren(NodeKind.ProtocolListWithClass, Protocols, Superclass)); - } - case 'l': - { - var Protocols = DemangleProtocolList(); - return CreateType(CreateWithChild(NodeKind.ProtocolListWithAnyObject, Protocols)); - } - case 'X': - case 'x': - { - // SIL box types. - Node signature = null, genericArgs = null; - if (specialChar == 'X') - { - signature = PopNode(NodeKind.DependentGenericSignature); - if (signature == null) - return null; - genericArgs = PopTypeList(); - if (genericArgs == null) - return null; - } - - var fieldTypes = PopTypeList(); - if (fieldTypes == null) - return null; - // Build layout. - var layout = new Node(NodeKind.SILBoxLayout); - for (int i = 0, e = fieldTypes.Children.Count; i < e; ++i) - { - var fieldType = fieldTypes.Children[i]; - bool isMutable = false; - // 'inout' typelist mangling is used to represent mutable fields. - if (fieldType.Children[0].Kind == NodeKind.InOut) - { - isMutable = true; - fieldType = CreateType(fieldType.Children[0].Children[0]); - } - var field = new Node(isMutable - ? NodeKind.SILBoxMutableField - : NodeKind.SILBoxImmutableField); - field.AddChild(fieldType); - layout.AddChild(field); - } - var boxTy = new Node(NodeKind.SILBoxTypeWithLayout); - boxTy.AddChild(layout); - if (signature != null) - { - boxTy.AddChild(signature); - boxTy.AddChild(genericArgs); - } - return CreateType(boxTy); - } - case 'Y': - return DemangleAnyGenericType(NodeKind.OtherNominalType); - case 'Z': - { - var types = PopTypeList(); - var name = PopNode(NodeKind.Identifier); - var parent = PopContext(); - var anon = new Node(NodeKind.AnonymousContext); - anon = AddChild(anon, name); - anon = AddChild(anon, parent); - anon = AddChild(anon, types); - return anon; - } - case 'e': - return CreateType(new Node(NodeKind.ErrorType)); - default: - return null; - } - } - - Node DemangleMetatypeRepresentation() - { - switch (NextChar()) - { - case 't': - return new Node(NodeKind.MetatypeRepresentation, "@thin"); - case 'T': - return new Node(NodeKind.MetatypeRepresentation, "@thick"); - case 'o': - return new Node(NodeKind.MetatypeRepresentation, "@objc_metatype"); - default: - return null; - } - } - - Node DemangleAccessor(Node childNode) - { - NodeKind kind; - switch (NextChar()) - { - case 'm': kind = NodeKind.MaterializeForSet; break; - case 's': kind = NodeKind.Setter; break; - case 'g': kind = NodeKind.Getter; break; - case 'G': kind = NodeKind.GlobalGetter; break; - case 'w': kind = NodeKind.WillSet; break; - case 'W': kind = NodeKind.DidSet; break; - case 'r': kind = NodeKind.ReadAccessor; break; - case 'M': kind = NodeKind.ModifyAccessor; break; - case 'a': - switch (NextChar()) - { - case 'O': kind = NodeKind.OwningMutableAddressor; break; - case 'o': kind = NodeKind.NativeOwningMutableAddressor; break; - case 'P': kind = NodeKind.NativePinningMutableAddressor; break; - case 'u': kind = NodeKind.UnsafeMutableAddressor; break; - default: return null; - } - break; - case 'l': - switch (NextChar()) - { - case 'O': kind = NodeKind.OwningAddressor; break; - case 'o': kind = NodeKind.NativeOwningAddressor; break; - case 'p': kind = NodeKind.NativePinningAddressor; break; - case 'u': kind = NodeKind.UnsafeAddressor; break; - default: return null; - } - break; - case 'p': // Pseudo-accessor referring to the variable/subscript itself - return childNode; - default: return null; - } - var entity = CreateWithChild(kind, childNode); - return entity; - } - - enum Args - { - None, - TypeAndMaybePrivateName, - TypeAndIndex, - Index - } - - Node DemangleFunctionEntity() - { - var args = Args.None; - NodeKind Kind = NodeKind.EmptyList; - switch (NextChar()) - { - case 'D': args = Args.None; Kind = NodeKind.Deallocator; break; - case 'd': args = Args.None; Kind = NodeKind.Destructor; break; - case 'E': args = Args.None; Kind = NodeKind.IVarDestroyer; break; - case 'e': args = Args.None; Kind = NodeKind.IVarInitializer; break; - case 'i': args = Args.None; Kind = NodeKind.Initializer; break; - case 'C': - args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Allocator; break; - case 'c': - args = Args.TypeAndMaybePrivateName; Kind = NodeKind.Constructor; break; - case 'U': args = Args.TypeAndIndex; Kind = NodeKind.ExplicitClosure; break; - case 'u': args = Args.TypeAndIndex; Kind = NodeKind.ImplicitClosure; break; - case 'A': args = Args.Index; Kind = NodeKind.DefaultArgumentInitializer; break; - case 'p': return DemangleEntity(NodeKind.GenericTypeParamDecl); - default: return null; - } - - Node nameOrIndex = null, paramType = null, labelList = null; - switch (args) - { - case Args.None: - break; - case Args.TypeAndMaybePrivateName: - nameOrIndex = PopNode(NodeKind.PrivateDeclName); - paramType = PopNode(NodeKind.Type); - labelList = PopFunctionParamLabels(paramType); - break; - case Args.TypeAndIndex: - nameOrIndex = DemangleIndexAsNode(); - paramType = PopNode(NodeKind.Type); - break; - case Args.Index: - nameOrIndex = DemangleIndexAsNode(); - break; - } - var entity = CreateWithChild(Kind, PopContext()); - switch (args) - { - case Args.None: - break; - case Args.Index: - entity = AddChild(entity, nameOrIndex); - break; - case Args.TypeAndMaybePrivateName: - AddChild(entity, labelList); - entity = AddChild(entity, paramType); - AddChild(entity, nameOrIndex); - break; - case Args.TypeAndIndex: - entity = AddChild(entity, nameOrIndex); - entity = AddChild(entity, paramType); - break; - } - return entity; - } - - Node DemangleEntity(NodeKind Kind) - { - var type = PopNode(NodeKind.Type); - var labelList = PopFunctionParamLabels(type); - var name = PopNode(IsDeclName); - var context = PopContext(); - return labelList != null ? CreateWithChildren(Kind, context, name, labelList, type) - : CreateWithChildren(Kind, context, name, type); - } - - Node DemangleVariable() - { - var variable = DemangleEntity(NodeKind.Variable); - return DemangleAccessor(variable); - } - - Node DemangleSubscript() - { - var privateName = PopNode(NodeKind.PrivateDeclName); - var type = PopNode(NodeKind.Type); - var labelList = PopFunctionParamLabels(type); - var context = PopContext(); - - var subscript = new Node(NodeKind.Subscript); - subscript = AddChild(subscript, context); - AddChild(subscript, labelList); - subscript = AddChild(subscript, type); - AddChild(subscript, privateName); - - return DemangleAccessor(subscript); - } - - Node DemangleProtocolList() - { - var typeList = new Node(NodeKind.TypeList); - var protoList = CreateWithChild(NodeKind.ProtocolList, typeList); - if (PopNode(NodeKind.EmptyList) == null) - { - bool firstElem = false; - do - { - firstElem = (PopNode(NodeKind.FirstElementMarker) != null); - var proto = PopProtocol(); - if (proto == null) - return null; - typeList.AddChild(proto); - } while (!firstElem); - - typeList.ReverseChildren(); - } - return protoList; - } - - Node DemangleProtocolListType() - { - var protoList = DemangleProtocolList(); - return CreateType(protoList); - } - - Node DemangleGenericSignature(bool hasParamCounts) - { - var Sig = new Node(NodeKind.DependentGenericSignature); - if (hasParamCounts) - { - while (!NextIf('l')) - { - int count = 0; - if (!NextIf('z')) - count = DemangleIndex() + 1; - if (count < 0) - return null; - Sig.AddChild(new Node(NodeKind.DependentGenericParamCount, count)); - } - } - else - { - Sig.AddChild(new Node(NodeKind.DependentGenericParamCount, 1)); - } - var NumCounts = Sig.Children.Count; - Node Req; - while ((Req = PopNode(IsRequirement)) != null) - { - Sig.AddChild(Req); - } - Sig.ReverseChildren(NumCounts); - return Sig; - } - - enum TypeKind - { - Generic, - Assoc, - CompoundAssoc, - Substitution - } - - enum ConstraintKind - { - Protocol, - BaseClass, - SameType, - Layout - } - - Node DemangleGenericRequirement() - { - TypeKind typeKind; - ConstraintKind constraintKind; - - switch (NextChar()) - { - case 'c': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Assoc; break; - case 'C': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.CompoundAssoc; break; - case 'b': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Generic; break; - case 'B': constraintKind = ConstraintKind.BaseClass; typeKind = TypeKind.Substitution; break; - case 't': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Assoc; break; - case 'T': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.CompoundAssoc; break; - case 's': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Generic; break; - case 'S': constraintKind = ConstraintKind.SameType; typeKind = TypeKind.Substitution; break; - case 'm': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Assoc; break; - case 'M': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.CompoundAssoc; break; - case 'l': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Generic; break; - case 'L': constraintKind = ConstraintKind.Layout; typeKind = TypeKind.Substitution; break; - case 'p': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Assoc; break; - case 'P': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.CompoundAssoc; break; - case 'Q': constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Substitution; break; - default: constraintKind = ConstraintKind.Protocol; typeKind = TypeKind.Generic; PushBack(); break; - } - - Node ConstrTy = null; - - switch (typeKind) - { - case TypeKind.Generic: - ConstrTy = CreateType(DemangleGenericParamIndex()); - break; - case TypeKind.Assoc: - ConstrTy = DemangleAssociatedTypeSimple(DemangleGenericParamIndex()); - AddSubstitution(ConstrTy); - break; - case TypeKind.CompoundAssoc: - ConstrTy = DemangleAssociatedTypeCompound(DemangleGenericParamIndex()); - AddSubstitution(ConstrTy); - break; - case TypeKind.Substitution: - ConstrTy = PopNode(NodeKind.Type); - break; - } - - switch (constraintKind) - { - case ConstraintKind.Protocol: - return CreateWithChildren(NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopProtocol()); - case ConstraintKind.BaseClass: - return CreateWithChildren(NodeKind.DependentGenericConformanceRequirement, ConstrTy, PopNode(NodeKind.Type)); - case ConstraintKind.SameType: - return CreateWithChildren(NodeKind.DependentGenericSameTypeRequirement, ConstrTy, PopNode(NodeKind.Type)); - case ConstraintKind.Layout: - { - var c = NextChar(); - Node size = null; - Node alignment = null; - string name = null; - if (c == 'U') - { - name = "U"; - } - else if (c == 'R') - { - name = "R"; - } - else if (c == 'N') - { - name = "N"; - } - else if (c == 'C') - { - name = "C"; - } - else if (c == 'D') - { - name = "D"; - } - else if (c == 'T') - { - name = "T"; - } - else if (c == 'E') - { - size = DemangleIndexAsNode(); - if (size == null) - return null; - alignment = DemangleIndexAsNode(); - name = "E"; - } - else if (c == 'e') - { - size = DemangleIndexAsNode(); - if (size == null) - return null; - name = "e"; - } - else if (c == 'M') - { - size = DemangleIndexAsNode(); - if (size == null) - return null; - alignment = DemangleIndexAsNode(); - name = "M"; - } - else if (c == 'm') - { - size = DemangleIndexAsNode(); - if (size == null) - return null; - name = "m"; - } - else - { - // Unknown layout constraint. - return null; - } - - var NameNode = new Node(NodeKind.Identifier, name); - var LayoutRequirement = CreateWithChildren(NodeKind.DependentGenericLayoutRequirement, ConstrTy, NameNode); - if (size != null) - AddChild(LayoutRequirement, size); - if (alignment != null) - AddChild(LayoutRequirement, alignment); - return LayoutRequirement; - } - } - return null; - } - - Node DemangleGenericType() - { - var genSig = PopNode(NodeKind.DependentGenericSignature); - var ty = PopNode(NodeKind.Type); - return CreateType(CreateWithChildren(NodeKind.DependentGenericType, genSig, ty)); - } - - int DecodeValueWitnessKind(string codeStr) - { - switch (codeStr) - { - case "al": return (int)ValueWitnessKind.AllocateBuffer; - case "ca": return (int)ValueWitnessKind.AssignWithCopy; - case "ta": return (int)ValueWitnessKind.AssignWithTake; - case "de": return (int)ValueWitnessKind.DeallocateBuffer; - case "xx": return (int)ValueWitnessKind.Destroy; - case "XX": return (int)ValueWitnessKind.DestroyBuffer; - case "Xx": return (int)ValueWitnessKind.DestroyArray; - case "CP": return (int)ValueWitnessKind.InitializeBufferWithCopyOfBuffer; - case "Cp": return (int)ValueWitnessKind.InitializeBufferWithCopy; - case "cp": return (int)ValueWitnessKind.InitializeWithCopy; - case "Tk": return (int)ValueWitnessKind.InitializeBufferWithTake; - case "tk": return (int)ValueWitnessKind.InitializeWithTake; - case "pr": return (int)ValueWitnessKind.ProjectBuffer; - case "TK": return (int)ValueWitnessKind.InitializeBufferWithTakeOfBuffer; - case "Cc": return (int)ValueWitnessKind.InitializeArrayWithCopy; - case "Tt": return (int)ValueWitnessKind.InitializeArrayWithTakeFrontToBack; - case "tT": return (int)ValueWitnessKind.InitializeArrayWithTakeBackToFront; - case "xs": return (int)ValueWitnessKind.StoreExtraInhabitant; - case "xg": return (int)ValueWitnessKind.GetExtraInhabitantIndex; - case "ug": return (int)ValueWitnessKind.GetEnumTag; - case "up": return (int)ValueWitnessKind.DestructiveProjectEnumData; - case "ui": return (int)ValueWitnessKind.DestructiveInjectEnumTag; - case "et": return (int)ValueWitnessKind.GetEnumTagSinglePayload; - case "st": return (int)ValueWitnessKind.StoreEnumTagSinglePayload; - default: - return -1; - } - } - - Node DemangleValueWitness() - { - char[] code = new char[2]; - code[0] = NextChar(); - code[1] = NextChar(); - int kind = DecodeValueWitnessKind(new string(code)); - if (kind < 0) - return null; - var vw = new Node(NodeKind.ValueWitness, (uint)kind); - return AddChild(vw, PopNode(NodeKind.Type)); - } - - Node DemangleObjCTypeName() - { - var ty = new Node(NodeKind.Type); - var global = AddChild(new Node(NodeKind.Global), AddChild(new Node(NodeKind.TypeMangling), ty)); - Node nominal = null; - bool isProto = false; - if (NextIf('C')) - { - nominal = new Node(NodeKind.Class); - AddChild(ty, nominal); - } - else if (NextIf('P')) - { - isProto = true; - nominal = new Node(NodeKind.Protocol); - AddChild(ty, AddChild(new Node(NodeKind.ProtocolList), - AddChild(new Node(NodeKind.TypeList), - AddChild(new Node(NodeKind.Type), nominal)))); - } - else - { - return null; - } - - if (NextIf('s')) - { - nominal.AddChild(new Node(NodeKind.Module, "Swift")); - } - else - { - var Module = DemangleIdentifier(); - if (Module == null) - return null; - nominal.AddChild(ChangeKind(Module, NodeKind.Module)); - } - - var ident = DemangleIdentifier(); - if (ident == null) - return null; - nominal.AddChild(ident); - - if (isProto && !NextIf('_')) - return null; - - if (!slice.IsAtEnd) - return null; - - return global; - } - - } -} diff --git a/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs b/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs deleted file mode 100644 index d102da65d299..000000000000 --- a/src/SwiftReflector/Demangling/Swift5NodeToTLDefinition.cs +++ /dev/null @@ -1,2138 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Demangling -{ - public class Swift5NodeToTLDefinition - { - static List nominalNodeKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol - }; - - static List nominalNodeAndModuleKinds = new List { - NodeKind.Class, NodeKind.Enum, NodeKind.Structure, NodeKind.Protocol, NodeKind.Module - }; - - static List identifierOrOperatorOrPrivateDecl = new List { - NodeKind.Identifier, NodeKind.PrefixOperator, NodeKind.InfixOperator, NodeKind.PostfixOperator, NodeKind.PrivateDeclName - }; - - static List boundGenericNominalNodeKinds = new List { - NodeKind.BoundGenericEnum, NodeKind.BoundGenericClass, NodeKind.BoundGenericStructure - }; - - string mangledName; - ulong offset; - - RuleRunner ruleRunner; - List rules; - - public Swift5NodeToTLDefinition(string mangledName, ulong offset = 0) - { - this.mangledName = mangledName; - this.offset = offset; - rules = BuildMatchRules(); - ruleRunner = new RuleRunner(rules); - } - - List BuildMatchRules() - { - return new List() { - new MatchRule { - Name = "TypeAlias", - NodeKind = NodeKind.TypeAlias, - Reducer = ConvertToTypeAlias - }, - new MatchRule { - Name = "ReturnType", - NodeKind = NodeKind.ReturnType, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "ArgumentTuple", - NodeKind = NodeKind.ArgumentTuple, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "AutoClosure", - NodeKind = NodeKind.AutoClosureType, - Reducer = ConvertToFunctionType - }, - new MatchRule { - Name = "Tuple", - NodeKind = NodeKind.Tuple, - Reducer = ConvertToTuple - }, - new MatchRule { - Name = "Structure", - NodeKind = NodeKind.Structure, - Reducer = ConvertToStruct - }, - new MatchRule { - Name = "ClassEnum", - NodeKindList = new List { NodeKind.Class, NodeKind.Enum }, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "Getter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToGetter, - ChildRules = new List () { - new MatchRule () { - Name = "GetterChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "Setter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSetter, - ChildRules = new List () { - new MatchRule () { - Name = "SetterChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "DispatchThunk", - NodeKind = NodeKind.DispatchThunk, - Reducer = ConvertToDispatchThunk, - ChildRules = new List () { } - }, - new MatchRule { - Name = "DynamicSelf", - NodeKind = NodeKind.DynamicSelf, - Reducer = ConvertFirstChildToSwiftType - }, - new MatchRule { - Name = "SubscriptModifier", - NodeKind = NodeKind.ModifyAccessor, - Reducer = ConvertToSubscriptModifier, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptModifierChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "SubscriptGetter", - NodeKind = NodeKind.Getter, - Reducer = ConvertToSubscriptGetter, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptSetterChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "SubscriptSetter", - NodeKind = NodeKind.Setter, - Reducer = ConvertToSubscriptSetter, - ChildRules = new List () { - new MatchRule () { - Name = "SubscriptSetterChild", - NodeKind = NodeKind.Subscript - } - } - }, - new MatchRule { - Name = "DidSet", - NodeKind = NodeKind.DidSet, - Reducer = ConvertToDidSet, - ChildRules = new List { - new MatchRule { - Name = "DidSetChild", - NodeKind = NodeKind.Variable, - }, - } - }, - new MatchRule { - Name = "WillSet", - NodeKind = NodeKind.WillSet, - Reducer = ConvertToWillSet, - ChildRules = new List { - new MatchRule { - Name = "DidSetChild", - NodeKind = NodeKind.Variable, - }, - } - }, - new MatchRule { - Name = "ModifyAccessor", - NodeKind = NodeKind.ModifyAccessor, - Reducer = ConvertToModifyAccessor, - ChildRules = new List () { - new MatchRule () { - Name = "ModifyAccessorChild", - NodeKind = NodeKind.Variable - } - } - - }, - new MatchRule { - Name = "CFunctionPointerType", - NodeKind = NodeKind.CFunctionPointer, - Reducer = ConvertToCFunctionPointerType, - ChildRules = new List { - new MatchRule { - Name = "CFunctionPointerChildArgumentTuple", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule { - Name = "CFunctionPointerChildReturnType", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule { - Name = "ProtocolList", - NodeKind = NodeKind.ProtocolList, - Reducer = ConvertToProtocolList, - ChildRules = new List { - new MatchRule { - Name = "TypeList", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "ProtocolListWithAnyObject", - NodeKind = NodeKind.ProtocolListWithAnyObject, - Reducer = ConvertToProtocolListAnyObject, - }, - new MatchRule { - Name = "Protocol", - NodeKind = NodeKind.Protocol, - Reducer = ConvertToClass - }, - new MatchRule { - Name = "TupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToTupleElement, - ChildRules = new List { - new MatchRule { - Name = "TupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "NamedTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToTupleElement, - ChildRules = new List { - new MatchRule { - Name = "TupleElementName", - NodeKind = NodeKind.TupleElementName - }, - new MatchRule { - Name = "TupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "VariadicTupleElement", - NodeKind = NodeKind.TupleElement, - Reducer = ConvertToVariadicTupleElement, - ChildRules = new List { - new MatchRule { - Name = "VariadicElementType", - NodeKind = NodeKind.VariadicMarker, - }, - new MatchRule { - Name = "NamedTupleElementType", - NodeKind = NodeKind.Type - } - } - }, - new MatchRule { - Name = "DependentGenericParameter", - NodeKind = NodeKind.DependentGenericParamType, - Reducer = ConvertToGenericReference, - ChildRules = new List { - new MatchRule { - Name = "Depth", - NodeKind = NodeKind.Index - }, - new MatchRule { - Name = "Index", - NodeKind = NodeKind.Index - } - } - }, - new MatchRule { - Name = "DependentMemberType", - NodeKind = NodeKind.DependentMemberType, - Reducer = ConvertToDependentMember, - ChildRules = new List { - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule { - Name = "Static", - NodeKind = NodeKind.Static, - Reducer = ConvertToStatic, - }, - new MatchRule { - Name = "BoundGenericNominal", - NodeKindList = boundGenericNominalNodeKinds, - Reducer = ConvertToBoundGeneric, - ChildRules = new List { - new MatchRule { - Name = "TypeChild", - NodeKind = NodeKind.Type - }, - new MatchRule { - Name = "TypeListChild", - NodeKind = NodeKind.TypeList - } - } - }, - new MatchRule { - Name = "ConstructorList", - NodeKind = NodeKind.Constructor, - Reducer = ConvertToNonAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ConstructorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorExtensionLableList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ExtensionChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "FunctionLabelListChild", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "ConstructorNoTypeList", - NodeKind = NodeKind.Constructor, - Reducer = ConvertToNonAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "ConstructorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKindList = nominalNodeKinds, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "AllocatorExtensionsNoTypeList", - NodeKind = NodeKind.Allocator, - Reducer = ConvertToAllocatingConstructor, - ChildRules = new List { - new MatchRule { - Name = "AllocatorNominalChild", - NodeKind = NodeKind.Extension, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.FunctionType - } - } - }, - } - }, - new MatchRule { - Name = "Destructor", - NodeKind = NodeKind.Destructor, - Reducer = ConvertToDestructor, - ChildRules = new List { - new MatchRule { - Name = "DestructorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "Deallocator", - NodeKind = NodeKind.Deallocator, - Reducer = ConvertToDeallocator, - ChildRules = new List { - new MatchRule { - Name = "DeallocatorNominalChild", - NodeKindList = nominalNodeKinds, - } - } - }, - new MatchRule { - Name = "InOutType", - NodeKind = NodeKind.Type, - Reducer = ConvertToReferenceType, - ChildRules = new List { - new MatchRule { - Name = "InOutChild", - NodeKind = NodeKind.InOut - } - } - }, - new MatchRule { - Name = "ProtocolWitnessTable", - NodeKindList = new List { - NodeKind.ProtocolWitnessTable, - NodeKind.ProtocolWitnessTableAccessor - }, - Reducer = ConvertToProtocolWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChild", - NodeKind = NodeKind.ProtocolConformance, - ChildRules = new List { - new MatchRule { - Name = "ProtocolWitnessChildTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildProtocolTypeChild", - NodeKind = NodeKind.Type, - }, - new MatchRule { - Name = "ProtocolWitnessChildModuleChild", - NodeKind = NodeKind.Module - } - } - } - } - }, - new MatchRule { - Name = "ValueWitnessTable", - NodeKind = NodeKind.ValueWitnessTable, - Reducer = ConvertToValueWitnessTable, - ChildRules = new List { - new MatchRule { - Name = "ValueWitnessTableChild", - NodeKind = NodeKind.Type - } - } - }, - // a Function is: - // Context Identifier [LabelList] Type FunctionType - new MatchRule () { - Name = "FunctionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTLContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "FunctionTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule () { - Name = "FunctionTLType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionExtensionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionExtension", - NodeKind = NodeKind.Extension, - }, - new MatchRule () { - Name = "FunctionExtTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionExtTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule () { - Name = "FunctionExtTLType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule { - Name = "GenericFunctionWithLabelList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List { - new MatchRule () { - Name = "GenFunctionTLContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "GenFunctionTLName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionTLLabelList", - NodeKind = NodeKind.LabelList, - }, - new MatchRule { - Name = "FunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "FunctionTypeChildChild", - NodeKind = NodeKind.DependentGenericType, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - } - } - }, - } - }, - new MatchRule { - Name = "DependentGenericFunctionType", - NodeKind = NodeKind.DependentGenericType, - Reducer = ConvertToGenericFunction, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericSignature", - NodeKind = NodeKind.DependentGenericSignature - }, - new MatchRule { - Name = "DependentGenericFunctionTypeChild", - NodeKind = NodeKind.Type, - ChildRules = new List { - new MatchRule { - Name = "DependentGenericFunctionChild", - NodeKind = NodeKind.FunctionType - } - } - } - } - }, - new MatchRule () { - Name = "FunctionNoTypeList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionContext", - NodeKindList = nominalNodeAndModuleKinds, - }, - new MatchRule () { - Name = "FunctionName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionExtensionNoTypeList", - NodeKind = NodeKind.Function, - Reducer = ConvertToFunction, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionExtension", - NodeKind = NodeKind.Extension, - }, - new MatchRule () { - Name = "FunctionName", - NodeKindList = identifierOrOperatorOrPrivateDecl - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.Type - }, - } - }, - new MatchRule () { - Name = "FunctionType", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "FunctionThrows", - NodeKind = NodeKind.FunctionType, - Reducer = ConvertToFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeThrows", - NodeKind = NodeKind.ThrowsAnnotation - }, - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "NoEscapeFunctionType", - NodeKind = NodeKind.NoEscapeFunctionType, - Reducer = ConvertToNoEscapeFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "NoEscapeFunctionTypeThrows", - NodeKind = NodeKind.NoEscapeFunctionType, - Reducer = ConvertToNoEscapeFunctionType, - ChildRules = new List () { - new MatchRule () { - Name = "FunctionTypeThrows", - NodeKind = NodeKind.ThrowsAnnotation - }, - new MatchRule () { - Name = "FunctionTypeArgs", - NodeKind = NodeKind.ArgumentTuple - }, - new MatchRule () { - Name = "FunctionTypeReturn", - NodeKind = NodeKind.ReturnType - } - } - }, - new MatchRule () { - Name = "Metatype", - NodeKind = NodeKind.Metatype, - Reducer = ConvertToMetatype, - }, - new MatchRule () { - Name = "ExistentialMetatype", - NodeKind = NodeKind.ExistentialMetatype, - Reducer = ConvertToExistentialMetatype, - MatchChildCount = false - }, - // Probably should be last - new MatchRule { - Name = "Type", - NodeKind = NodeKind.Type, - Reducer = ConvertFirstChildToSwiftType, - MatchChildCount = false - }, - }; - } - - public TLDefinition Convert(Node node) - { - Exceptions.ThrowOnNull(node, nameof(node)); - - - switch (node.Kind) - { - case NodeKind.Type: - return Convert(node.Children[0]); - case NodeKind.Static: - return ConvertStatic(node); - case NodeKind.Function: - return ConvertFunction(node, isMethodDescriptor: false, isEnumCase: false); - case NodeKind.MethodDescriptor: - return ConvertFunction(node.Children[0], isMethodDescriptor: true, isEnumCase: false); - case NodeKind.EnumCase: - return ConvertFunction(node.Children[0], isMethodDescriptor: false, isEnumCase: true); - case NodeKind.Constructor: - case NodeKind.Allocator: - return ConvertFunctionConstructor(node); - case NodeKind.Destructor: - case NodeKind.Deallocator: - return ConvertFunctionDestructor(node); - case NodeKind.Getter: - case NodeKind.Setter: - case NodeKind.DidSet: - case NodeKind.MaterializeForSet: - case NodeKind.WillSet: - case NodeKind.ModifyAccessor: - return ConvertFunctionProp(node); - case NodeKind.DispatchThunk: - return ConvertDispatchThunk(node); - case NodeKind.Variable: - return ConvertVariable(node, false); - case NodeKind.PropertyDescriptor: - return ConvertPropertyDescriptor(node); - case NodeKind.TypeMetadataAccessFunction: - return ConvertCCtor(node); - case NodeKind.TypeMetadata: - return ConvertMetadata(node); - case NodeKind.NominalTypeDescriptor: - return ConvertNominalTypeDescriptor(node); - case NodeKind.ProtocolConformanceDescriptor: - return ConvertProtocolConformanceDescriptor(node); - case NodeKind.ProtocolDescriptor: - return ConvertProtocolDescriptor(node); - case NodeKind.Initializer: - return ConvertInitializer(node); - case NodeKind.TypeMetadataLazyCache: - return ConvertLazyCacheVariable(node); - case NodeKind.ProtocolWitnessTable: - case NodeKind.ProtocolWitnessTableAccessor: - case NodeKind.ValueWitnessTable: - return ConvertProtocolWitnessTable(node); - case NodeKind.FieldOffset: - return ConvertFieldOffset(node); - case NodeKind.DefaultArgumentInitializer: - return ConvertDefaultArgumentInitializer(node); - case NodeKind.Metaclass: - return ConvertMetaclass(node); - case NodeKind.UnsafeMutableAddressor: - return ConvertUnsafeMutableAddressor(node); - case NodeKind.CurryThunk: - return ConvertCurryThunk(node); - case NodeKind.GenericTypeMetadataPattern: - return ConvertTypeMetadataPattern(node); - case NodeKind.Global: - return Convert(node); - case NodeKind.ModuleDescriptor: - return ConvertModuleDescriptor(node); - case NodeKind.ReflectionMetadataFieldDescriptor: - return ConvertMetadataFieldDescriptor(node, false); - case NodeKind.ReflectionMetadataBuiltinDescriptor: - return ConvertMetadataFieldDescriptor(node, true); - case NodeKind.ProtocolRequirementsBaseDescriptor: - return ConvertProtocolRequirementsBaseDescriptor(node); - case NodeKind.BaseConformanceDescriptor: - return ConvertBaseConformanceDescriptor(node); - case NodeKind.AssociatedTypeDescriptor: - return ConvertAssocatedTypeDescriptor(node); - case NodeKind.ClassMetadataBaseOffset: - return ConvertMetadataBaseOffset(node); - case NodeKind.MethodLookupFunction: - return ConvertMethodLookupFunction(node); - default: - return null; - } - } - - - TLDefinition ConvertDispatchThunk(Node node) - { - switch (node.Children[0].Kind) - { - case NodeKind.Getter: - case NodeKind.Setter: - case NodeKind.DidSet: - case NodeKind.MaterializeForSet: - case NodeKind.WillSet: - case NodeKind.ModifyAccessor: - return ConvertFunctionProp(node); - case NodeKind.Static: - return ConvertStaticDispatchThunk(node); - case NodeKind.Function: - case NodeKind.Allocator: - return ConvertFunction(node, isMethodDescriptor: false, isEnumCase: false); - default: - return null; - } - } - - TLDefinition ConvertStaticDispatchThunk(Node node) - { - if (node.Children[0].Children[0].Kind == NodeKind.Variable) - { - return ConvertStaticDispatchThunkVariable(node); - } - else - { - return ConvertStatic(node); - } - } - - TLDefinition ConvertStaticDispatchThunkVariable(Node node) - { - return null; - } - - - TLFunction ConvertFunction(Node node, bool isMethodDescriptor, bool isEnumCase) - { - var swiftType = ConvertToSwiftType(node, false, null); - var uncurriedFunction = swiftType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) - { - // method - var context = uncurriedFunction.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var functionName = new SwiftName(context.Last(), false); - return isMethodDescriptor ? - new TLMethodDescriptor(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset) : - isEnumCase ? - new TLEnumCase(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset) : - new TLFunction(mangledName, module, functionName, uncurriedFunction.UncurriedParameter as SwiftClassType, - uncurriedFunction, offset); - } - - var plainFunction = swiftType as SwiftFunctionType; - if (plainFunction != null) - { - var context = plainFunction.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context[context.Length - 2][0] == '|') - { - Enum.TryParse(context[context.Length - 2].Substring(1), out operatorType); - } - var functionName = new SwiftName(context.Last(), false); - return isMethodDescriptor ? - new TLMethodDescriptor(mangledName, module, functionName, null, plainFunction, offset, operatorType) : - new TLFunction(mangledName, module, functionName, null, plainFunction, offset, operatorType); - } - return null; - } - - TLDefinition ConvertStatic(Node node) - { - if (node.Children[0].Kind == NodeKind.Variable) - { - return ConvertVariable(node.Children[0], true); - } - var swiftType = ConvertToSwiftType(node, false, null); - var propType = swiftType as SwiftPropertyType; - if (propType != null) - { - var context = propType.DiscretionaryString.Split('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction(mangledName, new SwiftName(context[0], false), propType.Name, uncurriedParam, propType, offset); - } - - var staticFunction = swiftType as SwiftStaticFunctionType; - if (staticFunction != null) - { - var context = staticFunction.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var operatorType = OperatorType.None; - if (context.Length > 2 && context[context.Length - 2][0] == '|') - { - Enum.TryParse(context[context.Length - 2].Substring(1), out operatorType); - } - var functionName = new SwiftName(context.Last(), false); - return new TLFunction(mangledName, module, functionName, staticFunction.OfClass, staticFunction, offset, operatorType); - } - return null; - } - - TLFunction ConvertFunctionConstructor(Node node) - { - var swiftType = ConvertToSwiftType(node, false, null); - var constructor = swiftType as SwiftConstructorType; - if (constructor != null) - { - var context = constructor.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var functionName = constructor.Name; - var metaType = constructor.UncurriedParameter as SwiftMetaClassType; - return new TLFunction(mangledName, module, functionName, metaType.Class, constructor, offset); - } - return null; - } - - TLFunction ConvertFunctionDestructor(Node node) - { - var swiftType = ConvertToSwiftType(node, false, null); - var destructor = swiftType as SwiftDestructorType; - if (destructor != null) - { - var context = destructor.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var functionName = destructor.Name; - var className = destructor.Parameters as SwiftClassType; - if (className == null) - throw new NotSupportedException($"Expected a SwiftClassType as the parameter to the destructor bute got {destructor.Parameters.GetType().Name}"); - return new TLFunction(mangledName, module, functionName, className, destructor, offset); - } - return null; - } - - TLFunction ConvertFunctionProp(Node node) - { - var propType = ConvertToSwiftType(node, false, null) as SwiftPropertyType; - if (propType == null) - return null; - var context = propType.DiscretionaryString.Split('.'); - var uncurriedParam = propType.UncurriedParameter as SwiftClassType; - return new TLFunction(mangledName, new SwiftName(context[0], false), propType.Name, uncurriedParam, propType, offset); - } - - TLVariable ConvertVariable(Node node, bool isStatic) - { - // Variable - // - if (node.Children.Count != 3 && node.Children.Count != 4) - throw new ArgumentOutOfRangeException(nameof(node), $"Expected 3 or 4 children in a variable node, but got {node.Children.Count}"); - - if (node.Kind == NodeKind.Subscript) - { - var subFunc = ConvertToSubscriptEtter(node, false, null, PropertyType.Getter) as SwiftPropertyType; - var module = subFunc.DiscretionaryString.Split('.')[0]; - return new TLVariable(mangledName, new SwiftName(module, false), subFunc.UncurriedParameter as SwiftClassType, - new SwiftName("subscript", false), subFunc.OfType, isStatic, offset); - } - - if (node.Children[2].Kind == NodeKind.LabelList && node.Children[3].Kind == NodeKind.Type && - node.Children[3].Children[0].Kind == NodeKind.FunctionType) - { - var functionNode = new Node(NodeKind.Function); - functionNode.Children.AddRange(node.Children); - var function = ConvertFunction(functionNode, isMethodDescriptor: false, isEnumCase: false); - SwiftClassType classOn = null; - if (function.Signature is SwiftUncurriedFunctionType ucf) - { - classOn = ucf.UncurriedParameter as SwiftClassType; - } - return new TLVariable(mangledName, function.Module, classOn, function.Name, function.Signature, isStatic, offset); - } - else - { - var isExtension = node.Children[0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType context = null; - - - if (isExtension) - { - module = new SwiftName(node.Children[0].Children[0].Text, false); - extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); - if (extensionOn == null) - return null; - } - else - { - var nesting = new List(); - var nestingNames = new List(); - module = BuildMemberNesting(node.Children[0], nesting, nestingNames); - context = nesting.Count > 0 ? new SwiftClassType(new SwiftClassName(module, nesting, nestingNames), false) : null; - } - - var name = new SwiftName(node.Children[1].Text, false); - var variableType = ConvertToSwiftType(node.Children[2], false, null); - return new TLVariable(mangledName, module, context, name, variableType, isStatic, offset, extensionOn); - } - } - - TLPropertyDescriptor ConvertPropertyDescriptor(Node node) - { - var tlvar = ConvertVariable(node.Children[0], false); - if (tlvar == null) - return null; - return new TLPropertyDescriptor(tlvar.MangledName, tlvar.Module, tlvar.Class, tlvar.Name, tlvar.OfType, false, tlvar.Offset, tlvar.ExtensionOn); - } - - TLFunction ConvertCCtor(Node node) - { - var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - var metaType = new SwiftMetaClassType(classType, false); - var cctor = new SwiftClassConstructorType(metaType, false); - return new TLFunction(mangledName, classType.ClassName.Module, Decomposer.kSwiftClassConstructorName, classType, - cctor, offset); - } - - TLDefaultArgumentInitializer ConvertDefaultArgumentInitializer(Node node) - { - if (node.Children.Count != 2) - return null; - var baseFunction = ConvertToSwiftType(node.Children[0], false, null) as SwiftBaseFunctionType; - if (baseFunction == null) - return null; - var context = baseFunction.DiscretionaryString.Split('.'); - var module = new SwiftName(context[0], false); - var argumentIndex = (int)node.Children[1].Index; - return new TLDefaultArgumentInitializer(mangledName, module, baseFunction, argumentIndex, offset); - } - - TLFieldOffset ConvertFieldOffset(Node node) - { - if (node.Children.Count != 2 || node.Children[0].Kind != NodeKind.Directness) - return null; - var variable = ConvertVariable(node.Children[1], false) as TLVariable; - if (variable == null) - return null; - - return new TLFieldOffset(mangledName, variable.Module, variable.Class, node.Children[0].Index == 0, variable.Name, - variable.OfType, offset); - } - - TLDirectMetadata ConvertMetadata(Node node) - { - var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - return new TLDirectMetadata(mangledName, classType.ClassName.Module, classType, offset); - } - - TLNominalTypeDescriptor ConvertNominalTypeDescriptor(Node node) - { - var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - return new TLNominalTypeDescriptor(mangledName, classType.ClassName.Module, classType, offset); - } - - TLProtocolConformanceDescriptor ConvertProtocolConformanceDescriptor(Node node) - { - node = node.Children[0]; - if (node.Kind != NodeKind.ProtocolConformance) - return null; - if (node.Children.Count != 3) - return null; - var implementingType = ConvertToSwiftType(node.Children[0], false, null); - if (implementingType == null) - return null; - var forProtocol = ConvertToSwiftType(node.Children[1], false, null) as SwiftClassType; - if (forProtocol == null) - return null; - var module = new SwiftName(node.Children[2].Text, false); - return new TLProtocolConformanceDescriptor(mangledName, module, implementingType, forProtocol, offset); - } - - TLProtocolTypeDescriptor ConvertProtocolDescriptor(Node node) - { - var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - return new TLProtocolTypeDescriptor(mangledName, classType.ClassName.Module, classType, offset); - } - - TLUnsafeMutableAddressor ConvertUnsafeMutableAddressor(Node node) - { - if (node.Children[0].Kind != NodeKind.Variable) - throw new ArgumentOutOfRangeException($"Expected a Variable child but got a {node.Children[0].Kind}"); - var variable = ConvertVariable(node.Children[0], false); - return new TLUnsafeMutableAddressor(mangledName, variable.Module, null, variable.Name, variable.OfType, variable.Offset); - } - - TLMetaclass ConvertMetaclass(Node node) - { - if (node.Children[0].Kind != NodeKind.Type) - return null; - var classType = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; - if (classType == null) - return null; - var module = classType.ClassName.Module; - return new TLMetaclass(mangledName, module, classType, offset); - } - - TLGenericMetadataPattern ConvertTypeMetadataPattern(Node node) - { - var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLGenericMetadataPattern(mangledName, type.ClassName.Module, type, offset); - } - - TLFunction ConvertInitializer(Node node) - { - var variable = node.Children[0]; - var context = ConvertToSwiftType(variable.Children[0], false, null) as SwiftClassType; - if (context == null) - return null; - var privatePublicName = PrivateNamePublicName(variable.Children[1]); - var name = new SwiftName(privatePublicName.Item2, false); - var typeIndex = variable.Children[2].Kind == NodeKind.LabelList ? 3 : 2; - var type = ConvertToSwiftType(variable.Children[typeIndex], false, null); - var initializer = new SwiftInitializerType(InitializerType.Variable, type, context, name); - return new TLFunction(mangledName, context.ClassName.Module, name, initializer.Owner, initializer, offset); - } - - TLLazyCacheVariable ConvertLazyCacheVariable(Node node) - { - var classType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - return new TLLazyCacheVariable(mangledName, classType.ClassName.Module, classType, offset); - } - - TLFunction ConvertProtocolWitnessTable(Node node) - { - var witnessTable = ConvertToSwiftType(node, false, null) as SwiftWitnessTableType; - - var rebuiltWitnessTable = new SwiftWitnessTableType(witnessTable.WitnessType, witnessTable.ProtocolType, witnessTable.UncurriedParameter as SwiftClassType); - - return new TLFunction(mangledName, new SwiftName(witnessTable.DiscretionaryString, false), null, - witnessTable.UncurriedParameter as SwiftClassType, rebuiltWitnessTable, offset); - } - - TLThunk ConvertCurryThunk(Node node) - { - TLFunction func = ConvertFunction(node.Children[0], isMethodDescriptor: false, isEnumCase: false); - return new TLThunk(ThunkType.Curry, func.MangledName, func.Module, func.Class, func.Offset); - } - - TLModuleDescriptor ConvertModuleDescriptor(Node node) - { - var firstChild = node.Children[0]; - if (firstChild.Kind != NodeKind.Module) - return null; - return new TLModuleDescriptor(mangledName, new SwiftName(firstChild.Text, false), offset); - } - - TLMetadataDescriptor ConvertMetadataFieldDescriptor(Node node, bool isBuiltIn) - { - var ofType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (ofType == null) - return null; - return new TLMetadataDescriptor(ofType, isBuiltIn, mangledName, ofType.ClassName.Module, offset); - } - - TLProtocolRequirementsBaseDescriptor ConvertProtocolRequirementsBaseDescriptor(Node node) - { - var ofType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (ofType == null) - return null; - return new TLProtocolRequirementsBaseDescriptor(mangledName, ofType.ClassName.Module, ofType, offset); - } - - TLBaseConformanceDescriptor ConvertBaseConformanceDescriptor(Node node) - { - var protocol = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (protocol == null) - return null; - var requirement = ConvertToSwiftType(node.Children[1], false, null) as SwiftClassType; - if (requirement == null) - return null; - return new TLBaseConformanceDescriptor(mangledName, protocol.ClassName.Module, protocol, requirement, offset); - } - - TLAssociatedTypeDescriptor ConvertAssocatedTypeDescriptor(Node node) - { - var name = new SwiftName(node.Children[0].Text, false); - var protocol = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; - if (protocol == null) - return null; - return new TLAssociatedTypeDescriptor(mangledName, protocol.ClassName.Module, protocol, name, offset); - } - - TLMetadataBaseOffset ConvertMetadataBaseOffset(Node node) - { - var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLMetadataBaseOffset(mangledName, type.ClassName.Module, type, offset); - } - - TLMethodLookupFunction ConvertMethodLookupFunction(Node node) - { - var type = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - if (type == null) - return null; - return new TLMethodLookupFunction(mangledName, type.ClassName.Module, type, offset); - } - - - // ConvertToFunctions are usually called from rules. - - SwiftType ConvertToReferenceType(Node node, bool isReference, SwiftName name) - { - return ConvertToSwiftType(node.Children[0].Children[0], true, name); - } - - SwiftType ConvertToSwiftType(Node node, bool isReference, SwiftName name) - { - return ruleRunner.RunRules(node, isReference, name); - } - - SwiftType ConvertFirstChildToSwiftType(Node node, bool isReference, SwiftName name) - { - if (node.Children.Count == 0) - throw new ArgumentOutOfRangeException(nameof(node)); - return ConvertToSwiftType(node.Children[0], isReference, name); - } - - SwiftType ConvertToGeneralFunctionType(Node node, bool isReference, SwiftName name, bool isEscaping) - { - var throws = node.Children[0].Kind == NodeKind.ThrowsAnnotation; - var startIndex = throws ? 1 : 0; - var args = ConvertToSwiftType(node.Children[startIndex + 0], false, null); - var returnType = ConvertToSwiftType(node.Children[startIndex + 1], false, null); - return new SwiftFunctionType(args, returnType, isReference, throws, name, isEscaping: isEscaping); - } - - SwiftType ConvertToFunctionType(Node node, bool isReference, SwiftName name) - { - return ConvertToGeneralFunctionType(node, isReference, name, true); - } - - SwiftType ConvertToNoEscapeFunctionType(Node node, bool isReference, SwiftName name) - { - return ConvertToGeneralFunctionType(node, isReference, name, false); - } - - OperatorType ToOperatorType(NodeKind kind) - { - switch (kind) - { - default: - case NodeKind.Identifier: - return OperatorType.None; - case NodeKind.PrefixOperator: - return OperatorType.Prefix; - case NodeKind.InfixOperator: - return OperatorType.Infix; - case NodeKind.PostfixOperator: - return OperatorType.Postfix; - } - } - - SwiftType ConvertToAllocatingConstructor(Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor(node, isReference, name, true); - } - - SwiftType ConvertToNonAllocatingConstructor(Node node, bool isReference, SwiftName name) - { - return ConvertToConstructor(node, isReference, name, false); - } - - SwiftType ConvertToConstructor(Node node, bool isReference, SwiftName name, bool isAllocating) - { - var isExtension = node.Children[0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType instanceType = null; - - if (isExtension) - { - module = new SwiftName(node.Children[0].Children[0].Text, false); - extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); - if (extensionOn == null) - return null; - if (extensionOn is SwiftBuiltInType builtIn) - { - extensionOn = new SwiftClassType(SwiftClassName.FromFullyQualifiedName($"Swift.{builtIn.BuiltInType}", OperatorType.None, "V"), false); - } - instanceType = extensionOn as SwiftClassType; - } - else - { - instanceType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - module = instanceType.ClassName.Module; - } - - var metadata = new SwiftMetaClassType(instanceType, false, null); - var labels = node.Children[1].Kind == NodeKind.LabelList ? ToLabelList(node.Children[1]) : null; - var typeIndex = labels == null ? 1 : 2; - var functionType = node.Children[typeIndex].Children[0]; - var functionThrows = functionType.Children.Count == 3 && functionType.Children[0].Kind == NodeKind.ThrowsAnnotation ? 1 : 0; - var args = ConvertToSwiftType(functionType.Children[0 + functionThrows], false, null); - args = labels != null && labels.Count > 0 ? RenameFunctionParameters(args, labels) : args; - var ret = ConvertToSwiftType(functionType.Children[1 + functionThrows], false, null); - var constructor = new SwiftConstructorType(isAllocating, metadata, args, ret, isReference, functionThrows != 0, extensionOn); - - constructor.DiscretionaryString = $"{module.Name}.{instanceType.ClassName.ToFullyQualifiedName(false)}"; - return constructor; - } - - SwiftType ConvertToDestructor(Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor(node, isReference, name, false); - } - - SwiftType ConvertToDeallocator(Node node, bool isReference, SwiftName name) - { - return ConvertToDestructor(node, isReference, name, true); - } - - SwiftType ConvertToDestructor(Node node, bool isReference, SwiftName name, bool isDeallocating) - { - var instanceType = ConvertToSwiftType(node.Children[0], false, null); - var sct = instanceType as SwiftClassType; - if (sct == null) - throw new NotSupportedException($"Expected an SwiftClassType for the instance type in destructor but got {instanceType.GetType().Name}."); - var destructor = new SwiftDestructorType(isDeallocating, sct, isReference, false); - destructor.DiscretionaryString = sct.ClassName.ToFullyQualifiedName(true); - return destructor; - } - SwiftType ConvertToStruct(Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName(node); - var bit = TryAsBuiltInType(node, className, isReference, name); - return (SwiftType)bit ?? new SwiftClassType(className, isReference, name); - } - - SwiftType ConvertToTypeAlias(Node node, bool isReference, SwiftName name) - { - if (node.Children[0].Kind == NodeKind.Module && node.Children[0].Text == "__C") - { - var shamNode = new Node(NodeKind.Structure); - shamNode.Children.AddRange(node.Children); - var className = ToSwiftClassName(shamNode); - className = RemapTypeAlias(className); - return new SwiftClassType(className, isReference, name); - } - else - { - return null; - } - } - - SwiftType ConvertToClass(Node node, bool isReference, SwiftName name) - { - var className = ToSwiftClassName(node); - return new SwiftClassType(className, isReference, name); - } - - SwiftClassName ToSwiftClassName(Node node) - { - var memberNesting = new List(); - var nestingNames = new List(); - var moduleName = BuildMemberNesting(node, memberNesting, nestingNames); - - return PatchClassName(moduleName, memberNesting, nestingNames); - } - - SwiftType ConvertToDependentMember(Node node, bool isReference, SwiftName name) - { - // format should be - // DependentReferenceType - // Type - // GenericReference (depth, index) - // AssocPathItem (name) - // For multuple path elements, these get nested with the head being deepest. - // Weird flex, but OK. - var genericReference = ConvertFirstChildToSwiftType(node, isReference, name) as SwiftGenericArgReferenceType; - if (genericReference == null) - return null; - if (node.Children.Count < 2) - return genericReference; - var assocChild = node.Children[1]; - genericReference.AssociatedTypePath.Add(assocChild.Text); - return genericReference; - } - - SwiftType ConvertToCFunctionPointerType(Node node, bool isReference, SwiftName name) - { - var args = ConvertToSwiftType(node.Children[0], false, null); - var ret = ConvertToSwiftType(node.Children[1], false, null); - var function = new SwiftCFunctionPointerType(args, ret, isReference, false, name); - return function; - } - - SwiftType ConvertToTuple(Node node, bool isReference, SwiftName name) - { - var types = new List(); - if (node.Children.Count == 0) - { - return SwiftTupleType.Empty; - } - if (node.Children.Count == 1) - { - var onlyChild = ConvertFirstChildToSwiftType(node, false, null); - return new SwiftTupleType(isReference, name, onlyChild); - } - foreach (var child in node.Children) - { - var type = ConvertToSwiftType(child, false, null); - if (type == null) - return null; - types.Add(type); - } - return new SwiftTupleType(types, isReference, name); - } - - SwiftType ConvertToProtocolList(Node node, bool isReference, SwiftName name) - { - return ConvertToProtocolList(node, isReference, name, NodeKind.Type); - } - - SwiftType ConvertToProtocolListAnyObject(Node node, bool isReference, SwiftName name) - { - return ConvertToProtocolList(node.Children[0], isReference, name, node.Kind); - } - - SwiftType ConvertToProtocolList(Node node, bool isReference, SwiftName name, NodeKind nodeKind) - { - if (node.Children.Count != 1) - throw new NotSupportedException("ProtocolList node with more than 1 child not supported"); - if (node.Children[0].Kind != NodeKind.TypeList) - throw new NotSupportedException($"Given a ProtocolList node with child type {node.Children[0].Kind.ToString()} and {node.Children[0].Children.Count} children, but expected a TypeList with exactly 1 child."); - // If the number of elements is 0, it means that this is an "Any" type in swift. - // I'm assuming it's lodged here as a protocol list is that an empty protocol list is - // represented by an existential container which is also used to represent a protocol list. - if (node.Children[0].Children.Count == 0) - { - var anyName = nodeKind == NodeKind.ProtocolListWithAnyObject ? "Swift.AnyObject" : "Swift.Any"; - var anyProtocolType = nodeKind == NodeKind.ProtocolListWithAnyObject ? 'C' : 'P'; - var className = SwiftClassName.FromFullyQualifiedName(anyName, OperatorType.None, anyProtocolType); - var classType = new SwiftClassType(className, isReference, name); - return classType; - } - var typeList = ConvertTypeList(node.Children[0]).Select(t => t as SwiftClassType); - var protoListType = new SwiftProtocolListType(typeList, isReference, name); - if (protoListType.Protocols.Count == 1) - return protoListType.Protocols[0].RenamedCloneOf(name); - return protoListType; - } - - SwiftType ConvertToProtocolWitnessTable(Node node, bool isReference, SwiftName name) - { - var witnessType = node.Kind == NodeKind.ProtocolWitnessTable ? - WitnessType.Protocol : WitnessType.ProtocolAccessor; - var classType = ConvertToSwiftType(node.Children[0].Children[0], false, null) as SwiftClassType; - var protoType = ConvertToSwiftType(node.Children[0].Children[1], false, null) as SwiftClassType; - var protoWitness = new SwiftWitnessTableType(witnessType, protoType, classType); - protoWitness.DiscretionaryString = node.Children[0].Children[2].Text; - return protoWitness; - } - - SwiftType ConvertToValueWitnessTable(Node node, bool isReference, SwiftName name) - { - var valueType = ConvertToSwiftType(node.Children[0], false, null) as SwiftClassType; - var valueWitnessTable = new SwiftWitnessTableType(WitnessType.Value, null, valueType); - valueWitnessTable.DiscretionaryString = valueType.ClassName.Module.Name; - return valueWitnessTable; - } - - SwiftType ConvertToEtter(Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - var isExtension = node.Children[0].Kind == NodeKind.Extension; - SwiftName module = null; - SwiftType extensionOn = null; - SwiftClassType context = null; - SwiftClassName className = null; - - if (isExtension) - { - module = new SwiftName(node.Children[0].Children[0].Text, false); - extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); - if (extensionOn == null) - return null; - } - else - { - var nestings = new List(); - var names = new List(); - - module = BuildMemberNesting(node.Children[0], nestings, names); - if (module == null) - return null; - className = nestings.Count > 0 ? new SwiftClassName(module, nestings, names) : null; - context = className != null ? new SwiftClassType(className, false) : null; - } - - - var privatePublicName = PrivateNamePublicName(node.Children[1]); - var propName = new SwiftName(privatePublicName.Item2, false); - var privateName = privatePublicName.Item1 != null ? new SwiftName(privatePublicName.Item1, false) : null; - - var funcChildIndex = node.Children[2].Kind == NodeKind.LabelList ? 3 : 2; - - var getterType = ConvertToSwiftType(node.Children[funcChildIndex], false, propertyType == PropertyType.Setter ? new SwiftName("newValue", false) : null); - var prop = new SwiftPropertyType(context, propertyType, propName, privateName, - getterType, false, isReference, extensionOn); - prop.DiscretionaryString = context != null ? context.ClassName.ToFullyQualifiedName(true) - : $"{module.Name}.{propName.Name}"; - return prop; - - } - - SwiftType ConvertToGetter(Node node, bool isReference, SwiftName name) - { - // Getter - // Variable - // Context - // Type - return ConvertToEtter(node.Children[0], isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSetter(Node node, bool isReference, SwiftName name) - { - return ConvertToEtter(node.Children[0], isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToWillSet(Node node, bool isReference, SwiftName name) - { - return ConvertToEtter(node.Children[0], isReference, name, PropertyType.WillSet); - } - - SwiftType ConvertToDidSet(Node node, bool isReference, SwiftName name) - { - return ConvertToEtter(node.Children[0], isReference, name, PropertyType.DidSet); - } - - SwiftType ConvertToModifyAccessor(Node node, bool isReference, SwiftName name) - { - return ConvertToEtter(node.Children[0], isReference, name, PropertyType.ModifyAccessor); - } - - SwiftType ConvertToSubscriptEtter(Node node, bool isReference, SwiftName name, PropertyType propertyType) - { - var functionNode = new Node(NodeKind.Function); - functionNode.Children.AddRange(node.Children); - functionNode.Children.Insert(1, new Node(NodeKind.Identifier, "subscript")); - var theFunc = ConvertToFunction(functionNode, isReference, name) as SwiftBaseFunctionType; - if (theFunc == null) - return null; - - var uncurriedFunctionType = theFunc as SwiftUncurriedFunctionType; - - // if this is normal subscript, uncurriedFunctionType will be non-null - // if this is an extension, uncurriedFunctionType will be null. - - SwiftFunctionType accessor = null; - switch (propertyType) - { - case PropertyType.Setter: - // oh hooray! - // If I define an indexer in swift like this: - // public subscript(T index) -> U { - // get { return getSomeUValue(index); } - // set (someUValue) { setSomeUValue(index, someUValue); } - // } - // This signature of the function attached to both properties is: - // T -> U - // which makes bizarre sense - the subscript() declaration is T -> U and the getter is T -> U, but - // the setter is (T, U) -> void - // - // Since we have actual code that depends upon the signature, we need to "fix" this signature to reflect - // what's really happening. - - // need to change this so that the tail parameters get names? Maybe just the head? - var newParameters = theFunc.ParameterCount == 1 ? - new SwiftTupleType(false, null, theFunc.ReturnType, - theFunc.Parameters.RenamedCloneOf(new SwiftName(theFunc.ReturnType.Name == null || - theFunc.ReturnType.Name.Name != "a" ? "a" : "b", false))) - : new SwiftTupleType(Enumerable.Concat(theFunc.ReturnType.Yield(), theFunc.EachParameter), false, null); - accessor = new SwiftFunctionType(newParameters, SwiftTupleType.Empty, false, theFunc.CanThrow, theFunc.Name, theFunc.ExtensionOn); - break; - default: - // Because I decided to get clever and reuse existing code to demangle the underlying function, - // I get back either a SwiftFunctionType for an extension for a SwiftUncurriedFunctionType for - // an instance subscript. These types share a common base class, but are otherwise unrelated. - // I need a SwiftFunctionType, so here we are. - accessor = new SwiftFunctionType(theFunc.Parameters, theFunc.ReturnType, false, theFunc.IsReference, theFunc.Name, theFunc.ExtensionOn); - break; - } - - - var propType = theFunc.ReturnType; - var propName = theFunc.Name; - var prop = new SwiftPropertyType(uncurriedFunctionType?.UncurriedParameter, propertyType, propName, null, accessor, false, isReference); - prop.ExtensionOn = accessor.ExtensionOn; - prop.DiscretionaryString = theFunc.DiscretionaryString; - return prop; - } - - SwiftType ConvertToSubscriptGetter(Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.Getter); - } - - SwiftType ConvertToSubscriptSetter(Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.Setter); - } - - SwiftType ConvertToSubscriptModifier(Node node, bool isReference, SwiftName name) - { - return ConvertToSubscriptEtter(node.Children[0], isReference, name, PropertyType.ModifyAccessor); - } - - SwiftType ConvertToDispatchThunk(Node node, bool isReference, SwiftName name) - { - var thunkType = ConvertFirstChildToSwiftType(node, isReference, name); - if (thunkType == null) - return null; - if (thunkType is SwiftBaseFunctionType funcType) - return funcType.AsThunk(); - return null; - } - - SwiftType ConvertToTupleElement(Node node, bool isReference, SwiftName name) - { - name = node.Children[0].Kind == NodeKind.TupleElementName ? new SwiftName(node.Children[0].Text, false) : name; - var index = node.Children[0].Kind == NodeKind.TupleElementName ? 1 : 0; - return ConvertToSwiftType(node.Children[index], isReference, name); - } - - SwiftType ConvertToVariadicTupleElement(Node node, bool isReference, SwiftName name) - { - var type = ConvertToSwiftType(node.Children[1], false, null); - if (type == null) - return null; - - // in the past, this came through as an array with the variadic marker set. - // no longer is the case, so we synthesize the array and set the variadic marker. - var nesting = new List() { MemberNesting.Struct }; - var names = new List() { new SwiftName("Array", false) }; - var arrayName = new SwiftClassName(new SwiftName("Swift", false), nesting, names); - var container = new SwiftBoundGenericType(new SwiftClassType(arrayName, false), new List() { type }, isReference, name); - container.IsVariadic = true; - return container; - } - - SwiftType ConvertToGenericReference(Node node, bool isReference, SwiftName name) - { - long depth = node.Children[0].Index; - long index = node.Children[1].Index; - return new SwiftGenericArgReferenceType((int)depth, (int)index, isReference, name); - } - - SwiftType ConvertToBoundGeneric(Node node, bool isReference, SwiftName name) - { - var baseType = ConvertToSwiftType(node.Children[0], false, null); - var boundTypes = ConvertTypeList(node.Children[1]); - return new SwiftBoundGenericType(baseType, boundTypes, isReference, name); - } - - List ConvertTypeList(Node node) - { - var typeList = new List(node.Children.Count); - foreach (var childNode in node.Children) - { - typeList.Add(ConvertToSwiftType(childNode, false, null)); - } - return typeList; - } - - SwiftType ConvertToFunction(Node node, bool isReference, SwiftName name) - { - var isExtension = node.Children[0].Kind == NodeKind.Extension; - SwiftType extensionOn = null; - SwiftName module = null; - var nesting = new List(); - var names = new List(); - - if (isExtension) - { - module = new SwiftName(node.Children[0].Children[0].Text, false); - extensionOn = ConvertToSwiftType(node.Children[0].Children[1], false, null); - } - else - { - module = BuildMemberNesting(node.Children[0], nesting, names); - } - - var operatorType = ToOperatorType(node.Children[1].Kind); - var funcName = operatorType == OperatorType.None ? PrivateNamePublicName(node.Children[1]).Item2 : node.Children[1].Text; - var labelsList = node.Children[2].Kind == NodeKind.LabelList ? ToLabelList(node.Children[2]) : new List(); - var typeIndex = node.Children[2].Kind == NodeKind.LabelList ? 3 : 2; - var functionType = ConvertToSwiftType(node.Children[typeIndex], isReference, new SwiftName(funcName, false)) as SwiftFunctionType; - if (functionType == null) - return null; - - var args = labelsList.Count > 0 ? RenameFunctionParameters(functionType.Parameters, labelsList) : functionType.Parameters; - if (nesting.Count > 0) - { - var classType = new SwiftClassType(new SwiftClassName(module, nesting, names), false); - var methodName = classType.ClassName.ToFullyQualifiedName(true) + - (operatorType != OperatorType.None ? $".|{operatorType.ToString()}" : "") + - "." + funcName; - var uncurried = new SwiftUncurriedFunctionType(classType, args, functionType.ReturnType, - functionType.IsReference, functionType.CanThrow, new SwiftName(funcName, false)); - uncurried.DiscretionaryString = methodName; - uncurried.GenericArguments.AddRange(functionType.GenericArguments); - return uncurried; - } - var functionName = module + - (operatorType != OperatorType.None ? $".|{operatorType.ToString()}" : "") + - "." + funcName; - var generics = functionType.GenericArguments; - functionType = new SwiftFunctionType(args, functionType.ReturnType, functionType.IsReference, functionType.CanThrow, new SwiftName(funcName, false), extensionOn); - functionType.GenericArguments.AddRange(generics); - functionType.DiscretionaryString = functionName; - return functionType; - } - - SwiftType ConvertToStatic(Node node, bool isReference, SwiftName name) - { - var functionType = ConvertToSwiftType(node.Children[0], isReference, name); - if (functionType == null) - return null; - var propType = functionType as SwiftPropertyType; - if (propType != null) - { - return propType.RecastAsStatic(); - } - var uncurriedFunction = functionType as SwiftUncurriedFunctionType; - if (uncurriedFunction != null) - { - var staticFunction = new SwiftStaticFunctionType(uncurriedFunction.Parameters, uncurriedFunction.ReturnType, - uncurriedFunction.IsReference, uncurriedFunction.CanThrow, - uncurriedFunction.UncurriedParameter as SwiftClassType, uncurriedFunction.Name); - staticFunction.DiscretionaryString = uncurriedFunction.DiscretionaryString; - return staticFunction; - } - var baseFunctionType = functionType as SwiftBaseFunctionType; - if (baseFunctionType != null) - { - var staticFunction = new SwiftStaticFunctionType(baseFunctionType.Parameters, baseFunctionType.ReturnType, - baseFunctionType.IsReference, baseFunctionType.CanThrow, - null, baseFunctionType.Name); - staticFunction.DiscretionaryString = baseFunctionType.DiscretionaryString; - staticFunction.ExtensionOn = baseFunctionType.ExtensionOn; - return staticFunction; - } - var initializerType = functionType as SwiftInitializerType; - if (initializerType != null) - { - return initializerType; // this doesn't need a static recast? - } - throw new ArgumentOutOfRangeException($"Expected a SwiftUncurriedFunctionType, a SwiftPropertyType, a SwiftBaseFunctionType or a SwiftInitializerType in a static node, but got {functionType.GetType().Name}"); - } - - List ToLabelList(Node node) - { - var result = new List(); - foreach (var child in node.Children) - { - if (child.Kind == NodeKind.Identifier) - { - result.Add(new SwiftName(child.Text, false)); - } - else - { - result.Add(new SwiftName("_", false)); - } - } - return result; - } - - SwiftType ConvertToExistentialMetatype(Node node, bool isReference, SwiftName name) - { - var child = ConvertFirstChildToSwiftType(node, false, name); - var childType = child as SwiftProtocolListType; - if (child is SwiftClassType classType) - { - childType = new SwiftProtocolListType(classType, classType.IsReference, classType.Name); - } - if (childType == null) - return null; - return new SwiftExistentialMetaType(childType, isReference, null); - } - - SwiftType ConvertToMetatype(Node node, bool isReference, SwiftName name) - { - var child = ConvertFirstChildToSwiftType(node, false, name); - if (child is SwiftClassType cl) - { - return new SwiftMetaClassType(cl, isReference, name); - } - else if (child is SwiftGenericArgReferenceType classReference) - { - return new SwiftMetaClassType(classReference, isReference, name); - } - else - { - return null; - } - } - - SwiftType ConvertToGenericFunction(Node node, bool isReference, SwiftName name) - { - List args = GetGenericArguments(node); - var theFunction = ConvertToSwiftType(node.Children[1], isReference, name) as SwiftBaseFunctionType; - theFunction.GenericArguments.AddRange(args); - return theFunction; - } - - List GetGenericArguments(Node node) - { - var paramCountNode = node.Children[0].Children[0]; - if (paramCountNode.Kind != NodeKind.DependentGenericParamCount) - throw new NotSupportedException($"Expected a DependentGenericParamCount node but got a {paramCountNode.Kind.ToString()}"); - - var paramCount = (int)paramCountNode.Index; - List args = new List(paramCount); - for (int i = 0; i < paramCount; i++) - { - args.Add(new GenericArgument(0, i)); - } - if (node.Children[0].Children.Count > 1) - { - var dependentGenericSignature = node.Children[0]; - // the 0th child is the number of generic parameters (see above) - for (int i = 1; i < dependentGenericSignature.Children.Count; i++) - { - var genericParamReference = ConvertToSwiftType(dependentGenericSignature.Children[i].Children[0], false, null) as SwiftGenericArgReferenceType; - var genericConstraintType = ConvertToSwiftType(dependentGenericSignature.Children[i].Children[1], false, null) as SwiftClassType; - MarkGenericConstraint(args, genericParamReference, genericConstraintType); - } - } - return args; - } - - static void MarkGenericConstraint(List args, SwiftGenericArgReferenceType paramReference, SwiftClassType constraintType) - { - foreach (var genArg in args) - { - if (genArg.Depth == paramReference.Depth && genArg.Index == paramReference.Index) - { - genArg.Constraints.Add(constraintType); - return; - } - } - } - - static SwiftBuiltInType TryAsBuiltInType(Node node, SwiftClassName className, bool isReference, SwiftName name) - { - switch (className.ToFullyQualifiedName()) - { - case "Swift.Int": - return new SwiftBuiltInType(CoreBuiltInType.Int, isReference, name); - case "Swift.Float": - return new SwiftBuiltInType(CoreBuiltInType.Float, isReference, name); - case "Swift.Bool": - return new SwiftBuiltInType(CoreBuiltInType.Bool, isReference, name); - case "Swift.UInt": - return new SwiftBuiltInType(CoreBuiltInType.UInt, isReference, name); - case "Swift.Double": - return new SwiftBuiltInType(CoreBuiltInType.Double, isReference, name); - default: - return null; - } - } - - static SwiftName BuildMemberNesting(Node node, List nestings, List names) - { - if (node.Children.Count > 0 && node.Children[0].Kind == NodeKind.Extension) - node = node.Children[0].Children[1]; - var nesting = MemberNesting.Class; - switch (node.Kind) - { - case NodeKind.Class: - break; - case NodeKind.Structure: - nesting = MemberNesting.Struct; - break; - case NodeKind.Enum: - nesting = MemberNesting.Enum; - break; - case NodeKind.Protocol: - nesting = MemberNesting.Protocol; - break; - case NodeKind.Module: - return new SwiftName(node.Text, false); - default: - throw new ArgumentOutOfRangeException(nameof(node), $"Expected a nominal type node kind but got {node.Kind.ToString()}"); - } - - var privatePublicName = PrivateNamePublicName(node.Children[1]); - var className = new SwiftName(privatePublicName.Item2, false); - SwiftName moduleName = null; - if (node.Children[0].Kind == NodeKind.Identifier || node.Children[0].Kind == NodeKind.Module) - { - moduleName = new SwiftName(node.Children[0].Text, false); - } - else - { - // recurse before adding names. - moduleName = BuildMemberNesting(node.Children[0], nestings, names); - } - names.Add(className); - nestings.Add(nesting); - return moduleName; - } - - - static Tuple PrivateNamePublicName(Node node) - { - if (node.Kind == NodeKind.Identifier) - return new Tuple(null, node.Text); - if (node.Kind == NodeKind.PrivateDeclName) - return new Tuple(node.Children[1].Text, node.Children[0].Text); - throw new ArgumentOutOfRangeException(nameof(node)); - } - - static SwiftType RenameFunctionParameters(SwiftType parameters, List labels) - { - if (labels.Count < 1) - throw new ArgumentOutOfRangeException(nameof(parameters)); - - var oldTuple = parameters as SwiftTupleType; - if (oldTuple == null) - throw new NotSupportedException($"{parameters} is not a tuple, it's a {parameters.GetType().Name}"); - - var newTuple = new SwiftTupleType(oldTuple.Contents.Select((elem, index) => RenamedCloneOf(elem, labels[index])), - oldTuple.IsReference, oldTuple.Name); - return newTuple; - } - - static SwiftType RenamedCloneOf(SwiftType st, SwiftName newName) - { - return st.RenamedCloneOf(newName.Name == "_" ? new SwiftName("", false) : newName); - } - - - // Swift does...weird...things with some of the core types from C. - // The mangler doesn't put in the appropriate swift module, but instead lumps them all - // together into the module __C. - // The mangler also puts a number of Foundation types into the namespace __ObjC. - // Why? No idea. - // I determined this list of __ObjC types by running the following command on all the Apple built libraries: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "type metadata accessor for __ObjC" | awk '{print $7}' | sort | uniq - // which also includes a number of inner types which we don't care about (yet). - - // The command to do this for the __C namespace is: - // find . -name "*.dylib" -exec nm {} \; | xcrun swift-demangle | grep "_type metadata for __C" | awk '{print $6}' | sort | uniq - - struct ModuleOrType - { - public ModuleOrType(string replacementModule) - { - ReplacementModule = replacementModule; - ReplacementFullClassName = null; - ReplacementNesting = null; - } - - public ModuleOrType(string replacementFullClassName, string replacementNesting) - { - ReplacementFullClassName = replacementFullClassName; - ReplacementNesting = replacementNesting; - ReplacementModule = null; - } - - public string ReplacementModule; - public string ReplacementFullClassName; - public string ReplacementNesting; - } - - - static Dictionary classNameOntoModuleOrType = new Dictionary { - { "AVError", new ModuleOrType ("AVFoundation") }, - { "AudioBuffer", new ModuleOrType ("AudioToolbox") }, - { "AudioBufferList", new ModuleOrType ("AudioToolbox") }, - { "CATransform3D", new ModuleOrType ("CoreAnimation") }, - { "CGAffineTransform", new ModuleOrType ("CoreGraphics") }, - { "CGColorSapceModel", new ModuleOrType ("CoreGraphics") }, - { "CGPoint", new ModuleOrType ("CoreGraphics") }, - { "CGRect", new ModuleOrType ("CoreGraphics") }, - { "CGSize", new ModuleOrType ("CoreGraphics") }, - { "CGVector", new ModuleOrType ("CoreGraphics") }, - { "CLError", new ModuleOrType ("CoreLocation") }, - { "CMTime", new ModuleOrType ("CoreMedia") }, - { "CMTimeFlags", new ModuleOrType ("CoreMedia") }, - { "CMTimeMapping", new ModuleOrType ("CoreMedia") }, - { "CMTimeRange", new ModuleOrType ("CoreMedia") }, - { "NSComparisonResult", new ModuleOrType ("Foundation") }, - { "NSDecimal", new ModuleOrType ("Foundation") }, - { "NSEnumerationOptions", new ModuleOrType ("Foundation") }, - { "NSKeyValueChange", new ModuleOrType ("Foundation") }, - { "NSKeyValueObservingOptions", new ModuleOrType ("Foundation") }, - { "NSFastEnumerationState", new ModuleOrType ("Foundation") }, - { "NSKeyValueChangeKey", new ModuleOrType ("Foundation") }, - { "NSBundle", new ModuleOrType ("Foundation.Bundle", "C") }, - { "NSURL", new ModuleOrType ("Foundation") }, - { "StringTransform", new ModuleOrType ("Foundation") }, - { "URLFileResourceType", new ModuleOrType ("Foundation") }, - { "URLResourceKey", new ModuleOrType ("Foundation") }, - { "URLThumbnailDictionaryItem", new ModuleOrType ("Foundation") }, - { "URLUbiquitousItemDownloadingStatus", new ModuleOrType ("Foundation") }, - { "URLUbiquitousSharedItemPermissions", new ModuleOrType ("Foundation") }, - { "URLUbiquitousSharedItemRole", new ModuleOrType ("Foundation") }, - { "MKCoordinateSpan", new ModuleOrType ("MapKit") }, - { "NSAnimationEffect", new ModuleOrType ("AppKit") }, - { "SCNGeometryPrimitiveType", new ModuleOrType ("SceneKit") }, - { "SCNVector3", new ModuleOrType ("SceneKit") }, - { "SCNVector4", new ModuleOrType ("SceneKit") }, - { "UIContentSizeCategory", new ModuleOrType ("UIKit") }, - { "UIControlState", new ModuleOrType ("UIKit.UIControl.State", "CV") }, - { "UIDeviceOrientation", new ModuleOrType ("UIKit") }, - { "UIEdgeInsets", new ModuleOrType ("UIKit") }, - { "UIInterfaceOrientation", new ModuleOrType ("UIKit") }, - { "UIControlEvents", new ModuleOrType ("UIKit.UIControl.Event", "CV") }, - { "UIViewAnimationOptions", new ModuleOrType ("UIKit.UIView.AnimationOptions", "CV") }, - { "UIOffset", new ModuleOrType ("UIKit") }, - { "UIBlurEffectStyle", new ModuleOrType ("UIKit.UIBlurEffect.Style","CV") }, - { "UIColor", new ModuleOrType ("UIKit")}, - { "UIImage", new ModuleOrType ("UIImage") }, - { "UITableViewStyle", new ModuleOrType ("UIKit.UITableView.Style", "CV") }, - { "UIView", new ModuleOrType ("UIKit") }, - { "UIViewControllerConditioning", new ModuleOrType ("UIKit") }, - { "UIVisualEffectView", new ModuleOrType ("UIKit") }, - { "CKError", new ModuleOrType ("CloudKit") }, - { "CNError", new ModuleOrType ("Contacts") }, - { "MTLSamplePosition", new ModuleOrType ("Metal") }, - { "XCUIKeyboardKey", new ModuleOrType ("XCTest") }, - { "BNNSActivationFunction", new ModuleOrType ("Accelerate") }, - { "BNNSDataType", new ModuleOrType ("Accelerate") }, - { "simd_double2x2", new ModuleOrType ("Accelerate") }, - { "simd_double2x3", new ModuleOrType ("Accelerate") }, - { "simd_double2x4", new ModuleOrType ("Accelerate") }, - { "simd_double3x2", new ModuleOrType ("Accelerate") }, - { "simd_double3x3", new ModuleOrType ("Accelerate") }, - { "simd_double3x4", new ModuleOrType ("Accelerate") }, - { "simd_double4x2", new ModuleOrType ("Accelerate") }, - { "simd_double4x3", new ModuleOrType ("Accelerate") }, - { "simd_double4x4", new ModuleOrType ("Accelerate") }, - { "simd_float2x2", new ModuleOrType ("Accelerate") }, - { "simd_float2x3", new ModuleOrType ("Accelerate") }, - { "simd_float2x4", new ModuleOrType ("Accelerate") }, - { "simd_float3x2", new ModuleOrType ("Accelerate") }, - { "simd_float3x3", new ModuleOrType ("Accelerate") }, - { "simd_float3x4", new ModuleOrType ("Accelerate") }, - { "simd_float4x2", new ModuleOrType ("Accelerate") }, - { "simd_float4x3", new ModuleOrType ("Accelerate") }, - { "simd_float4x4", new ModuleOrType ("Accelerate") }, - { "simd_quatd", new ModuleOrType ("Accelerate") }, - { "simd_quatf", new ModuleOrType ("Accelerate") }, - }; - - static SwiftClassName PatchClassName(SwiftName moduleName, List nesting, List nestingNames) - { - // surprise! - // When we run XML reflection, the module name we get is ObjectiveC, but in the name mangled version - // it's __ObjC. This is the only place in this code where we make a module name, so it's a decent enough - // bottleneck to alias it. - if (moduleName.Name == "__ObjC") - moduleName = new SwiftName("Foundation", false); - if (moduleName.Name != "__C" || nestingNames.Count != 1) - return new SwiftClassName(moduleName, nesting, nestingNames); - if (classNameOntoModuleOrType.ContainsKey(nestingNames[0].Name)) - { - var moduleOrType = classNameOntoModuleOrType[nestingNames[0].Name]; - if (moduleOrType.ReplacementModule == null) - { - return SwiftClassName.FromFullyQualifiedName(moduleOrType.ReplacementFullClassName, OperatorType.None, moduleOrType.ReplacementNesting); - } - else - { - moduleName = new SwiftName(moduleOrType.ReplacementModule, false); - } - } - return new SwiftClassName(moduleName, nesting, nestingNames); - } - - static Dictionary aliasNameOntoClassName = new Dictionary { - { "__C.NSOperatingSystemVersion", SwiftClassName.FromFullyQualifiedName ("Foundation.OperatingSystemVersion", OperatorType.None, 'V') }, - }; - - static SwiftClassName RemapTypeAlias(SwiftClassName className) - { - SwiftClassName newName = null; - return aliasNameOntoClassName.TryGetValue(className.ToFullyQualifiedName(true), out newName) ? newName : className; - } - } -} diff --git a/src/SwiftReflector/Demangling/TLDefinition.cs b/src/SwiftReflector/Demangling/TLDefinition.cs deleted file mode 100644 index 64a5eaa03d1b..000000000000 --- a/src/SwiftReflector/Demangling/TLDefinition.cs +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Demangling -{ - public class TLDefinition - { - protected TLDefinition(CoreCompoundType type, string mangledName, SwiftName module, ulong offset) - { - if (module == null) - throw new ArgumentNullException(nameof(module)); - Type = type; - Module = module; - MangledName = Exceptions.ThrowOnNull(mangledName, nameof(mangledName)); - Offset = offset; - } - - public CoreCompoundType Type { get; private set; } - public SwiftName Module { get; private set; } - public string MangledName { get; private set; } - public ulong Offset { get; private set; } - } - - public class TLModuleDescriptor : TLDefinition - { - public TLModuleDescriptor(string mangledName, SwiftName module, ulong offset) - : base(CoreCompoundType.ModuleDescriptor, mangledName, module, offset) - { - } - } - - public class TLMetadataDescriptor : TLDefinition - { - public TLMetadataDescriptor(SwiftType ofType, bool isBuiltIn, string mangledName, SwiftName module, ulong offset) - : base(CoreCompoundType.MetadataDescriptor, mangledName, module, offset) - { - OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); - IsBuiltIn = isBuiltIn; - } - public SwiftType OfType { get; private set; } - public bool IsBuiltIn { get; private set; } - } - - public class TLClassElem : TLDefinition - { - protected TLClassElem(CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base(type, mangledName, module, offset) - { - Class = classType; - } - public SwiftClassType Class { get; private set; } - } - - public class TLThunk : TLClassElem - { - public TLThunk(ThunkType thunkType, string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base(CoreCompoundType.Thunk, mangledName, module, classType, offset) - { - Thunk = thunkType; - } - - public ThunkType Thunk { get; private set; } - } - - public class TLVariable : TLClassElem - { - public TLVariable(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn = null) - : this(CoreCompoundType.Variable, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) - { - } - - protected TLVariable(CoreCompoundType type, string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn) - : base(type, mangledName, module, classType, offset) - { - Name = Exceptions.ThrowOnNull(ident, nameof(ident)); - OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); - IsStatic = isStatic; - ExtensionOn = extensionOn; - } - public SwiftType OfType { get; private set; } - public SwiftType ExtensionOn { get; private set; } - public SwiftName Name { get; private set; } - public bool IsStatic { get; private set; } - } - - public class TLPropertyDescriptor : TLVariable - { - public TLPropertyDescriptor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, - bool isStatic, ulong offset, SwiftType extensionOn = null) - : base(CoreCompoundType.PropertyDescriptor, mangledName, module, classType, ident, ofType, isStatic, offset, extensionOn) - { - } - } - - public class TLUnsafeMutableAddressor : TLClassElem - { - public TLUnsafeMutableAddressor(string mangledName, SwiftName module, SwiftClassType classType, SwiftName ident, SwiftType ofType, ulong offset) - : base(CoreCompoundType.UnsafeMutableAddressor, mangledName, module, classType, offset) - { - Name = Exceptions.ThrowOnNull(ident, nameof(ident)); - OfType = Exceptions.ThrowOnNull(ofType, nameof(ofType)); - } - public SwiftType OfType { get; private set; } - public SwiftName Name { get; private set; } - } - - public class TLFieldOffset : TLClassElem - { - - public TLFieldOffset(string mangledName, SwiftName module, SwiftClassType classType, bool direct, SwiftName ident, SwiftType type, ulong offset) - : base(CoreCompoundType.FieldOffset, mangledName, module, classType, offset) - { - IsDirect = direct; - Identifier = ident; - FieldType = type; - } - - public bool IsDirect { get; private set; } - - public SwiftName Identifier { get; private set; } - public SwiftType FieldType { get; private set; } - } - - public class TLFunction : TLClassElem - { - public TLFunction(string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : this(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.Function) - { - } - - protected TLFunction(string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None, - CoreCompoundType type = CoreCompoundType.Function) - : base(type, mangledName, module, classType, offset) - { - Name = functionName; - Signature = signature; - Operator = oper; - } - - public SwiftName Name { get; private set; } - public SwiftBaseFunctionType Signature { get; private set; } - public OperatorType Operator { get; private set; } - - public bool IsTopLevelFunction { get { return Class == null || Class.ClassName.Nesting.Count == 0; } } - } - - public class TLMethodDescriptor : TLFunction - { - public TLMethodDescriptor(string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : base(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) - { - } - } - - public class TLEnumCase : TLFunction - { - public TLEnumCase(string mangledName, SwiftName module, SwiftName functionName, - SwiftClassType classType, SwiftBaseFunctionType signature, ulong offset, OperatorType oper = OperatorType.None) - : base(mangledName, module, functionName, classType, signature, offset, oper, CoreCompoundType.MethodDescriptor) - { - } - } - - public class TLDefaultArgumentInitializer : TLDefinition - { - public TLDefaultArgumentInitializer(string mangledName, SwiftName module, SwiftBaseFunctionType function, int index, ulong offset) - : base(CoreCompoundType.ArgumentInitializer, mangledName, module, offset) - { - Signature = Exceptions.ThrowOnNull(function, nameof(function)); - ArgumentIndex = index; - } - public SwiftBaseFunctionType Signature { get; private set; } - public int ArgumentIndex { get; private set; } - } - - public class TLLazyCacheVariable : TLClassElem - { - public TLLazyCacheVariable(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.LazyCache, mangledName, module, cl, offset) - { - } - } - - public class TLDirectMetadata : TLClassElem - { - public TLDirectMetadata(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) - { - } - } - - public class TLGenericMetadataPattern : TLClassElem - { - public TLGenericMetadataPattern(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.DirectMetadata, mangledName, module, cl, offset) - { - } - } - - public class TLMetaclass : TLClassElem - { - public TLMetaclass(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.MetaClass, mangledName, module, cl, offset) - { - } - } - - public class TLNominalTypeDescriptor : TLClassElem - { - public TLNominalTypeDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.NominalTypeDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLProtocolTypeDescriptor : TLClassElem - { - public TLProtocolTypeDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.ProtocolTypeDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLProtocolConformanceDescriptor : TLDefinition - { - public TLProtocolConformanceDescriptor(string mangledName, SwiftName module, SwiftType implementingType, - SwiftClassType forProtocol, ulong offset) - : base(CoreCompoundType.ProtocolConformanceDescriptor, mangledName, module, offset) - { - ImplementingType = Exceptions.ThrowOnNull(implementingType, nameof(implementingType)); - Protocol = forProtocol; - } - - public SwiftType ImplementingType { get; private set; } - public SwiftClassType Protocol { get; private set; } - } - - public class TLProtocolRequirementsBaseDescriptor : TLClassElem - { - public TLProtocolRequirementsBaseDescriptor(string mangledName, SwiftName module, SwiftClassType cl, ulong offset) - : base(CoreCompoundType.ProtocolRequirementsBaseDescriptor, mangledName, module, cl, offset) - { - } - } - - public class TLBaseConformanceDescriptor : TLClassElem - { - public TLBaseConformanceDescriptor(string mangledName, SwiftName module, SwiftClassType protocol, SwiftClassType requirement, ulong offset) - : base(CoreCompoundType.BaseConformanceDescriptor, mangledName, module, protocol, offset) - { - ProtocolRequirement = Exceptions.ThrowOnNull(requirement, nameof(requirement)); - } - public SwiftClassType ProtocolRequirement { get; private set; } - } - - public class TLAssociatedTypeDescriptor : TLClassElem - { - public TLAssociatedTypeDescriptor(string mangledName, SwiftName module, SwiftClassType protocol, SwiftName associatedTypeName, ulong offset) - : base(CoreCompoundType.AssociatedTypeDescriptor, mangledName, module, protocol, offset) - { - AssociatedTypeName = associatedTypeName; - } - - public SwiftName AssociatedTypeName { get; private set; } - } - - public class TLMetadataBaseOffset : TLClassElem - { - public TLMetadataBaseOffset(string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base(CoreCompoundType.MetadataOffset, mangledName, module, classType, offset) - { - } - } - - public class TLMethodLookupFunction : TLClassElem - { - public TLMethodLookupFunction(string mangledName, SwiftName module, SwiftClassType classType, ulong offset) - : base(CoreCompoundType.MethodLookupFunction, mangledName, module, classType, offset) - { - - } - } -} - diff --git a/src/SwiftReflector/ErrorHandling.cs b/src/SwiftReflector/ErrorHandling.cs index e7e420d5e72c..1b3bb494578c 100644 --- a/src/SwiftReflector/ErrorHandling.cs +++ b/src/SwiftReflector/ErrorHandling.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -//#define CRASH_ON_EXCEPTION - using System; using System.Collections.Generic; using System.Linq; @@ -63,11 +61,7 @@ public void Add(Exception exception) { lock (messagesLock) { -#if CRASH_ON_EXCEPTION - ExceptionDispatchInfo.Capture (exception).Throw (); -#else messages.Add(new ReflectorError(exception)); -#endif } } diff --git a/src/SwiftReflector/Extensions.cs b/src/SwiftReflector/Extensions.cs index d5b7fc8b97ff..1f1e852a1e06 100644 --- a/src/SwiftReflector/Extensions.cs +++ b/src/SwiftReflector/Extensions.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Xamarin; +// using Xamarin; using System.Text; using SyntaxDynamo; using System.Collections; @@ -13,32 +13,6 @@ namespace SwiftReflector { public static class Extensions { - public static IEnumerable Yield(this T elem) - { - yield return elem; - } - - public static bool IsSwiftEntryPoint(this NListEntry entry) - { - return !String.IsNullOrEmpty(entry.str) && (entry.str.StartsWith("__T", StringComparison.Ordinal) || - entry.str.StartsWith("_$s", StringComparison.Ordinal) || entry.str.StartsWith("_$S", StringComparison.Ordinal)); - } - - public static IEnumerable SwiftEntryPoints(this IEnumerable entries) - { - return entries.Where(IsSwiftEntryPoint); - } - - public static IEnumerable SwiftEntryPointNames(this IEnumerable entries) - { - return entries.SwiftEntryPoints().Select(nle => nle.str); - } - - public static string DePunyCode(this string s) - { - return PunyCode.PunySingleton.Decode(s); - } - public static Tuple SplitModuleFromName(this string s) { int dotIndex = s.IndexOf('.'); @@ -59,130 +33,6 @@ public static string NameWithoutModule(this string s) return s.SplitModuleFromName().Item2; } - public static string[] DecomposeClangTarget(this string s) - { - if (String.IsNullOrEmpty(s)) - throw new ArgumentNullException(nameof(s)); - string[] parts = s.Split('-'); - // catalyst adds cpu-platform-ios-macabi - if (parts.Length != 3 && parts.Length != 4) - throw new ArgumentOutOfRangeException(nameof(s), s, "target should be in the form cpu-platform-os"); - - var shortestIndex = parts.Length == 3 ? - IndexOfMin(parts[0].Length, parts[1].Length, parts[2].Length) : - IndexOfMin(parts[0].Length, parts[1].Length, parts[2].Length, parts[3].Length); - - if (parts[shortestIndex].Length == 0) - { - var missingPart = new string[] { "cpu", "platform", "os", "os" }[shortestIndex]; - throw new ArgumentException($"target (cpu-platform-os) has an empty {missingPart} component."); - } - - return parts; - } - - static int IndexOfMin(params int[] values) - { - var min = values.Min(); - return Array.IndexOf(values, min); - } - - public static string ClangTargetCpu(this string s) - { - return s.DecomposeClangTarget()[0]; - } - - public static string ClangTargetPlatform(this string s) - { - return s.DecomposeClangTarget()[1]; - } - - public static string ClangTargetOS(this string s) - { - var clangTarget = s.DecomposeClangTarget(); - if (clangTarget.Length == 3) - return clangTarget[2]; - if (clangTarget.Length == 4) - return $"{clangTarget[2]}-{clangTarget[3]}"; - throw new ArgumentException($"Clang target {s} should have 3 or 4 parts", nameof(s)); - } - - static int IndexOfFirstDigit(string s) - { - int index = 0; - foreach (char c in s) - { - if (Char.IsDigit(c)) - return index; - index++; - } - return -1; - } - - public static string ClangOSNoVersion(this string s) - { - var clangTarget = s.DecomposeClangTarget(); - var os = clangTarget[2]; - return OSNoVersion(os); - } - - static string OSNoVersion(string s) - { - var firstNumber = IndexOfFirstDigit(s); - return firstNumber < 0 ? s : s.Substring(0, firstNumber); - } - - public static string ClangOSVersion(this string s) - { - var clangTarget = s.DecomposeClangTarget(); - var os = clangTarget[2]; - var firstNumber = IndexOfFirstDigit(os); - return os.Substring(firstNumber); - } - - public static string MinimumClangVersion(IEnumerable targets) - { - var osVersion = targets.Select(t => new Version(ClangOSVersion(t))).Min(); - return osVersion.ToString(); - } - - public static string ClangSubstituteOSVersion(this string s, string replacementVersion) - { - var clangTarget = s.DecomposeClangTarget(); - var os = OSNoVersion(clangTarget[2]) + replacementVersion; - clangTarget[2] = os; - return clangTarget.InterleaveStrings("-"); - } - - public static bool ClangTargetIsSimulator(this string s) - { - var parts = s.DecomposeClangTarget(); - if (parts.Length == 4 && parts[3] == "simulator") - return true; - var osNoVersion = OSNoVersion(parts[2]); - if (osNoVersion == "macosx") - return false; - var cpu = parts[0]; - return cpu == "i386" || cpu == "x86-64"; - } - - public static void Merge(this HashSet to, IEnumerable from) - { - Exceptions.ThrowOnNull(from, nameof(from)); - foreach (T val in from) - to.Add(val); - } - - public static void DisposeAll(this IEnumerable coll) where T : IDisposable - { - Exceptions.ThrowOnNull(coll, nameof(coll)); - foreach (T obj in coll) - { - if ((IDisposable)obj != null) - obj.Dispose(); - } - } - public static string InterleaveStrings(this IEnumerable elements, string separator, bool includeSepFirst = false) { StringBuilder sb = new StringBuilder(); @@ -195,50 +45,6 @@ public static string InterleaveCommas(this IEnumerable elements) { return elements.InterleaveStrings(", "); } - - public static bool IsSwift3(this Version vers) - { - return vers.Major == 3; - } - - public static bool IsSwift4(this Version vers) - { - return vers.Major == 4; - } - - public static int ErrorCount(this List errors) - { - var count = 0; - foreach (var error in errors) - { - if (!error.IsWarning) - ++count; - } - return count; - } - - public static int WarningCount(this List errors) - { - return errors.Count - errors.ErrorCount(); - } - - public static List CloneAndPrepend(this List source, T item) - { - var result = new List(source.Count + 1); - result.Add(item); - result.AddRange(source); - return result; - } - - public static T[] And(this T[] first, T[] second) - { - Exceptions.ThrowOnNull(first, nameof(first)); - Exceptions.ThrowOnNull(second, nameof(second)); - var result = new T[first.Length + second.Length]; - Array.Copy(first, result, first.Length); - Array.Copy(second, 0, result, first.Length, second.Length); - return result; - } } } diff --git a/src/SwiftReflector/IOUtils/ExecAndCollect.cs b/src/SwiftReflector/IOUtils/ExecAndCollect.cs deleted file mode 100644 index b4e6539fdcaa..000000000000 --- a/src/SwiftReflector/IOUtils/ExecAndCollect.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Text; -using System.Threading; - -namespace SwiftReflector.IOUtils -{ - public class ExecAndCollect - { - public static string Run(string path, string args, string workingDirectory = null, bool verbose = false) - { - var output = new StringBuilder(); - var exitCode = RunCommand(path, args, output: output, verbose: verbose, workingDirectory: workingDirectory); - if (exitCode != 0) - throw new Exception($"Failed to execute (exit code {exitCode}): {path} {string.Join(" ", args)}\n{output.ToString()}"); - return output.ToString(); - } - - static void ReadStream(Stream stream, StringBuilder sb, ManualResetEvent completed) - { - var encoding = Encoding.UTF8; - var decoder = encoding.GetDecoder(); - var buffer = new byte[1024]; - var characters = new char[encoding.GetMaxCharCount(buffer.Length)]; - - AsyncCallback callback = null; - callback = new AsyncCallback((IAsyncResult ar) => - { - var read = stream.EndRead(ar); - - var chars = decoder.GetChars(buffer, 0, read, characters, 0); - lock (sb) - sb.Append(characters, 0, chars); - - if (read > 0) - { - stream.BeginRead(buffer, 0, buffer.Length, callback, null); - } - else - { - completed.Set(); - } - }); - stream.BeginRead(buffer, 0, buffer.Length, callback, null); - } - - public static int RunCommand(string path, string args, IDictionary env = null, StringBuilder output = null, bool verbose = false, string workingDirectory = null) - { - var info = new ProcessStartInfo(path, args); - info.UseShellExecute = false; - info.RedirectStandardInput = false; - info.RedirectStandardOutput = true; - info.RedirectStandardError = true; - if (workingDirectory != null) - info.WorkingDirectory = workingDirectory; - - if (output == null) - output = new StringBuilder(); - - if (env != null) - { - foreach (var kvp in env) - { - if (kvp.Value == null) - { - if (info.EnvironmentVariables.ContainsKey(kvp.Key)) - info.EnvironmentVariables.Remove(kvp.Key); - } - else - { - info.EnvironmentVariables[kvp.Key] = kvp.Value; - } - } - } - - if (info.EnvironmentVariables.ContainsKey("XCODE_DEVELOPER_DIR_PATH")) - { - // VSfM adds this key, which confuses Xcode mightily if it doesn't match the value of xcode-select. - // So just remove it, we don't need it for anything. - info.EnvironmentVariables.Remove("XCODE_DEVELOPER_DIR_PATH"); - } - - - if (verbose) - { - var envOut = new StringBuilder(); - foreach (var key in info.EnvironmentVariables.Keys) - { - var value = info.EnvironmentVariables[key as string]; - envOut.AppendLine($"export {key}={value}"); - } - envOut.AppendLine($"{path} {args}"); - Console.Write(envOut.ToString()); - Console.WriteLine("{0} {1}", path, args); - } - - using (var p = Process.Start(info)) - { - var error_output = new StringBuilder(); - var stdout_completed = new ManualResetEvent(false); - var stderr_completed = new ManualResetEvent(false); - - ReadStream(p.StandardOutput.BaseStream, output, stdout_completed); - ReadStream(p.StandardError.BaseStream, error_output, stderr_completed); - - p.WaitForExit(); - - stderr_completed.WaitOne(TimeSpan.FromMinutes(1)); - stdout_completed.WaitOne(TimeSpan.FromMinutes(1)); - - if (verbose) - { - if (output.Length > 0) - Console.WriteLine(output); - if (error_output.Length > 0) - Console.WriteLine(error_output); - if (p.ExitCode != 0) - Console.Error.WriteLine($"Process exited with code {p.ExitCode}"); - } - if (p.ExitCode != 0 && error_output.Length > 0) - output.Append(error_output); - return p.ExitCode; - } - } - } -} diff --git a/src/SwiftReflector/IOUtils/IFileProvider.cs b/src/SwiftReflector/IOUtils/IFileProvider.cs deleted file mode 100644 index 8ec5e5db4c66..000000000000 --- a/src/SwiftReflector/IOUtils/IFileProvider.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace SwiftReflector.IOUtils -{ - public interface IFileProvider - { - string ProvideFileFor(T thing); - void NotifyFileDone(T thing, string stm); - } -} - diff --git a/src/SwiftReflector/IOUtils/OffsetStream.cs b/src/SwiftReflector/IOUtils/OffsetStream.cs deleted file mode 100644 index f2ab332b1366..000000000000 --- a/src/SwiftReflector/IOUtils/OffsetStream.cs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; - -namespace SwiftReflector.IOUtils -{ - public class OffsetStream : Stream - { - Stream stm; - long offset; - public OffsetStream(Stream stm, long offset) - { - this.stm = stm; - this.offset = offset; - stm.Seek(offset, SeekOrigin.Begin); - } - - public override bool CanRead - { - get - { - return stm.CanRead; - } - } - - public override bool CanSeek - { - get - { - return stm.CanSeek; - } - } - - public override bool CanTimeout - { - get - { - return stm.CanTimeout; - } - } - - public override bool CanWrite - { - get - { - return stm.CanWrite; - } - } - - public override void Close() - { - stm.Close(); - base.Close(); - } - - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - return stm.BeginRead(buffer, offset, count, callback, state); - } - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - return stm.BeginWrite(buffer, offset, count, callback, state); - } - - public override System.Threading.Tasks.Task CopyToAsync(Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) - { - return stm.CopyToAsync(destination, bufferSize, cancellationToken); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - stm.Dispose(); - base.Dispose(); - } - - public override int EndRead(IAsyncResult asyncResult) - { - return stm.EndRead(asyncResult); - } - - public override void EndWrite(IAsyncResult asyncResult) - { - stm.EndWrite(asyncResult); - } - - public override void Flush() - { - stm.Flush(); - } - - public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) - { - return stm.FlushAsync(cancellationToken); - } - - public override long Length - { - get - { - return stm.Length - offset; - } - } - - public override long Position - { - get - { - return stm.Position - offset; - } - set - { - stm.Position = value + offset; - } - } - - public override int Read(byte[] buffer, int offset, int count) - { - return stm.Read(buffer, offset, count); - } - - public override System.Threading.Tasks.Task ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) - { - return stm.ReadAsync(buffer, offset, count, cancellationToken); - } - - public override int ReadByte() - { - return stm.ReadByte(); - } - - public override int ReadTimeout - { - get - { - return stm.ReadTimeout; - } - set - { - stm.ReadTimeout = value; - } - } - - public override long Seek(long offset, SeekOrigin origin) - { - switch (origin) - { - case SeekOrigin.Begin: - return stm.Seek(offset + this.offset, origin) - this.offset; - case SeekOrigin.Current: - return stm.Seek(offset, origin) - this.offset; - case SeekOrigin.End: - return stm.Seek(offset, origin) - this.offset; - default: - return 0; - } - } - - public override void SetLength(long value) - { - stm.SetLength(value); - } - - public override void Write(byte[] buffer, int offset, int count) - { - stm.Write(buffer, offset, count); - } - } -} - diff --git a/src/SwiftReflector/Inventory/ClassContents.cs b/src/SwiftReflector/Inventory/ClassContents.cs deleted file mode 100644 index 2378ca2d78bf..000000000000 --- a/src/SwiftReflector/Inventory/ClassContents.cs +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.Linq; -using System.Collections.Generic; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class ClassContents - { - int sizeofMachinePointer; - public ClassContents(SwiftClassName className, int sizeofMachiinePointer) - { - this.sizeofMachinePointer = sizeofMachiinePointer; - Constructors = new FunctionInventory(sizeofMachinePointer); - ClassConstructor = new FunctionInventory(sizeofMachinePointer); - Methods = new FunctionInventory(sizeofMachinePointer); - Properties = new PropertyInventory(sizeofMachinePointer); - StaticProperties = new PropertyInventory(sizeofMachiinePointer); - PrivateProperties = new PropertyInventory(sizeofMachinePointer); - StaticPrivateProperties = new PropertyInventory(sizeofMachinePointer); - Subscripts = new List(sizeofMachinePointer); - PrivateSubscripts = new List(sizeofMachinePointer); - StaticFunctions = new FunctionInventory(sizeofMachinePointer); - Destructors = new FunctionInventory(sizeofMachinePointer); - EnumCases = new FunctionInventory(sizeofMachiinePointer); - WitnessTable = new WitnessInventory(sizeofMachinePointer); - FunctionsOfUnknownDestination = new List(); - DefinitionsOfUnknownDestination = new List(); - Variables = new VariableInventory(sizeofMachinePointer); - Initializers = new FunctionInventory(sizeofMachinePointer); - Name = className; - ProtocolConformanceDescriptors = new List(); - MethodDescriptors = new FunctionInventory(sizeofMachinePointer); - PropertyDescriptors = new List(); - } - - public void Add(TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) - { - if (IsConstructor(tlf.Signature, tlf.Class)) - { - AddOrChainInNewThunk(Constructors, tlf, srcStm); - } - else if (tlf.Signature is SwiftClassConstructorType) - { - if (ClassConstructor.Values.Count() == 0) - AddOrChainInNewThunk(ClassConstructor, tlf, srcStm); - else - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 12, $"multiple type metadata accessors for {tlf.Class.ClassName.ToFullyQualifiedName()}"); - } - else if (IsDestructor(tlf.Signature, tlf.Class)) - { - AddOrChainInNewThunk(Destructors, tlf, srcStm); - } - else if (tlf is TLEnumCase) - { - AddOrChainInNewThunk(EnumCases, tlf, srcStm); - } - else if (IsProperty(tlf.Signature, tlf.Class)) - { - if (IsSubscript(tlf.Signature, tlf.Class)) - { - if (IsPrivateProperty(tlf.Signature, tlf.Class)) - PrivateSubscripts.Add(tlf); - else - Subscripts.Add(tlf); - } - else - { - if (IsStaticProperty(tlf.Signature, tlf.Class)) - { - if (IsPrivateProperty(tlf.Signature, tlf.Class)) - StaticPrivateProperties.Add(tlf, srcStm); - else - StaticProperties.Add(tlf, srcStm); - } - else - { - if (IsPrivateProperty(tlf.Signature, tlf.Class)) - PrivateProperties.Add(tlf, srcStm); - else - Properties.Add(tlf, srcStm); - } - } - } - else if (IsMethodOnClass(tlf.Signature, tlf.Class)) - { - if (tlf is TLMethodDescriptor) - MethodDescriptors.Add(tlf, srcStm); - else - { - AddOrChainInNewThunk(Methods, tlf, srcStm); - } - } - else if (IsStaticMethod(tlf.Signature, tlf.Class)) - { - AddOrChainInNewThunk(StaticFunctions, tlf, srcStm); - } - else if (IsWitnessTable(tlf.Signature, tlf.Class)) - { - WitnessTable.Add(tlf, srcStm); - } - else if (IsInitializer(tlf.Signature, tlf.Class)) - { - AddOrChainInNewThunk(Initializers, tlf, srcStm); - } - else - { - FunctionsOfUnknownDestination.Add(tlf); - } - return; - } - var meta = tld as TLDirectMetadata; - if (meta != null) - { - if (DirectMetadata != null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 13, $"duplicate direct metadata in class {DirectMetadata.Class.ClassName.ToFullyQualifiedName()}"); - DirectMetadata = meta; - return; - } - var lazy = tld as TLLazyCacheVariable; - if (lazy != null) - { - if (LazyCacheVariable != null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 14, $"duplicate lazy cache variable in class {LazyCacheVariable.Class.ClassName.ToFullyQualifiedName()}"); - LazyCacheVariable = lazy; - return; - } - var mc = tld as TLMetaclass; - if (mc != null) - { - if (Metaclass != null) - { - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 15, $"duplicate type meta data descriptor in class {Metaclass.Class.ClassName.ToFullyQualifiedName()}"); - } - Metaclass = mc; - return; - } - var nom = tld as TLNominalTypeDescriptor; - if (nom != null) - { - if (TypeDescriptor != null) - { - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 16, $"duplicate nominal type descriptor in class {TypeDescriptor.Class.ClassName.ToFullyQualifiedName()}"); - } - TypeDescriptor = nom; - return; - } - var tlvar = tld as TLVariable; - if (tlvar != null) - { - if (tlvar is TLPropertyDescriptor tlpropDesc) - PropertyDescriptors.Add(tlpropDesc); - else - Variables.Add(tlvar, srcStm); - return; - } - var tlprot = tld as TLProtocolConformanceDescriptor; - if (tlprot != null) - { - ProtocolConformanceDescriptors.Add(tlprot); - return; - } - DefinitionsOfUnknownDestination.Add(tld); - } - - static void AddOrChainInNewThunk(FunctionInventory inventory, TLFunction newTLF, Stream sourceStream) - { - var oldTLF = inventory.ContainsEquivalentFunction(newTLF); - if (oldTLF == null) - inventory.Add(newTLF, sourceStream); - else - { - var newSig = newTLF.Signature; - var oldSig = oldTLF.Signature; - if (oldSig.IsThunk) - { - newSig.Thunk = oldSig; - inventory.ReplaceFunction(oldTLF, newTLF); - } - else - { - oldSig.Thunk = newSig; - } - } - } - - public bool IsFinal(TLFunction func) - { - string funcMangledSuffix = func.MangledName.Substring(3); // drop the __T - - foreach (string mangledWitnessEntry in WitnessTable.MangledNames) - { - if (mangledWitnessEntry.EndsWith(funcMangledSuffix)) - return false; - } - return true; - } - - static bool IsConstructor(SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - SwiftConstructorType des = signature as SwiftConstructorType; - if (des == null) - return false; - return des.Name.Equals(Decomposer.kSwiftAllocatingConstructorName) - || des.Name.Equals(Decomposer.kSwiftNonAllocatingConstructorName); - } - - static bool IsDestructor(SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - SwiftDestructorType des = signature as SwiftDestructorType; - if (des == null) - return false; - return des.Name.Equals(Decomposer.kSwiftDeallocatingDestructorName) - || des.Name.Equals(Decomposer.kSwiftNonDeallocatingDestructorName); - } - - public static bool IsWitnessTable(SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - return signature is SwiftWitnessTableType; - } - - public static bool IsInitializer(SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - return signature is SwiftInitializerType; - } - - static bool IsProperty(SwiftType signature, SwiftClassType cl) - { - return signature is SwiftPropertyType; - } - - static bool IsSubscript(SwiftType signature, SwiftClassType cl) - { - SwiftPropertyType prop = signature as SwiftPropertyType; - return prop != null && prop.IsSubscript; - } - - static bool IsPrivateProperty(SwiftType signature, SwiftClassType cl) - { - SwiftPropertyType pt = signature as SwiftPropertyType; - return pt != null && pt.IsPrivate; - } - - static bool IsStaticProperty(SwiftType signature, SwiftClassType classType) - { - SwiftPropertyType pt = signature as SwiftPropertyType; - return pt != null && pt.IsStatic; - } - - static bool IsMethodOnClass(SwiftType signature, SwiftClassType cl) - { - if (cl == null) - return false; - if (signature is SwiftWitnessTableType) - return false; - SwiftUncurriedFunctionType ucf = signature as SwiftUncurriedFunctionType; - if (ucf == null) - return false; - return ucf.UncurriedParameter is SwiftClassType && ucf.UncurriedParameter.Equals(cl); - } - - static bool IsStaticMethod(SwiftType signature, SwiftClassType cl) - { - return signature is SwiftStaticFunctionType; - } - - public IEnumerable AllPropertiesWithName(string name) - { - PropertyContents prop = null; - if (Properties.TryGetValue(name, out prop)) - yield return prop; - if (PrivateProperties.TryGetValue(name, out prop)) - yield return prop; - if (StaticProperties.TryGetValue(name, out prop)) - yield return prop; - if (StaticPrivateProperties.TryGetValue(name, out prop)) - yield return prop; - } - - public TLFunction SoleMetadataAccessor - { - get - { - if (ClassConstructor == null || ClassConstructor.Values.Count() == 0) - return null; - var elem = ClassConstructor.Values.ElementAt(0); - if (elem.Functions.Count == 0) - return null; - return elem.Functions[0]; - } - } - - - public SwiftClassName Name { get; private set; } - public FunctionInventory Constructors { get; private set; } - public FunctionInventory ClassConstructor { get; private set; } - public FunctionInventory Destructors { get; private set; } - public FunctionInventory EnumCases { get; private set; } - public PropertyInventory Properties { get; private set; } - public PropertyInventory StaticProperties { get; private set; } - public PropertyInventory PrivateProperties { get; private set; } - public PropertyInventory StaticPrivateProperties { get; private set; } - public List Subscripts { get; private set; } - public List PrivateSubscripts { get; private set; } - public FunctionInventory Methods { get; private set; } - public FunctionInventory StaticFunctions { get; private set; } - public WitnessInventory WitnessTable { get; private set; } - public TLLazyCacheVariable LazyCacheVariable { get; private set; } - public TLDirectMetadata DirectMetadata { get; private set; } - public TLMetaclass Metaclass { get; private set; } - public TLNominalTypeDescriptor TypeDescriptor { get; private set; } - public List FunctionsOfUnknownDestination { get; private set; } - public List DefinitionsOfUnknownDestination { get; private set; } - public VariableInventory Variables { get; private set; } - public List PropertyDescriptors { get; private set; } - public FunctionInventory Initializers { get; private set; } - public List ProtocolConformanceDescriptors { get; private set; } - public FunctionInventory MethodDescriptors { get; private set; } - - public int SizeInBytes - { - get - { - ValueWitnessTable vat = WitnessTable.ValueWitnessTable; - return vat != null ? (int)vat.Size : 0; - } - } - public int StrideInBytes - { - get - { - ValueWitnessTable vat = WitnessTable.ValueWitnessTable; - return vat != null ? (int)vat.Stride : 0; - } - } - } - -} - diff --git a/src/SwiftReflector/Inventory/ClassInventory.cs b/src/SwiftReflector/Inventory/ClassInventory.cs deleted file mode 100644 index 0fb8c7b3af96..000000000000 --- a/src/SwiftReflector/Inventory/ClassInventory.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class ClassInventory : Inventory - { - int sizeofMachinePointer; - public ClassInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public override void Add(TLDefinition tld, Stream srcStm) - { - // ignoring these - we don't/can't use them - if (tld is TLDefaultArgumentInitializer) - return; - SwiftName className = ToClassName(tld); - SwiftClassName formalName = ToFormalClassName(tld); - lock (valuesLock) - { - ClassContents contents = null; - if (!values.TryGetValue(className, out contents)) - { - contents = new ClassContents(formalName, sizeofMachinePointer); - values.Add(className, contents); - } - contents.Add(tld, srcStm); - } - } - - public static SwiftClassName ToFormalClassName(TLDefinition tld) - { - TLClassElem elem = tld as TLClassElem; - if (elem != null) - { - if (elem.Class == null) - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 2, $"Expected a top level definition to have a class name."); - return elem.Class.ClassName; - } - if (tld is TLProtocolConformanceDescriptor protocolDesc) - { - if (protocolDesc.ImplementingType is SwiftClassType swiftClass) - return swiftClass.ClassName; - if (protocolDesc.ImplementingType is SwiftBoundGenericType boundGen) - { - var baseType = boundGen.BaseType as SwiftClassType; - if (baseType != null) - return baseType.ClassName; - } - else if (protocolDesc.ImplementingType is SwiftBuiltInType builtInType) - { - return SwiftClassName.FromFullyQualifiedName($"Swift.{builtInType.BuiltInType}", OperatorType.None, "V"); - } - } - - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 0, $"unknown top level definition {tld.GetType().Name}"); - } - - public static SwiftName ToClassName(TLDefinition tld) - { - SwiftClassName cln = ToFormalClassName(tld); - return new SwiftName(cln.ToFullyQualifiedName(), false); - } - } - -} - diff --git a/src/SwiftReflector/Inventory/FunctionInventory.cs b/src/SwiftReflector/Inventory/FunctionInventory.cs deleted file mode 100644 index 9df5858a7840..000000000000 --- a/src/SwiftReflector/Inventory/FunctionInventory.cs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.Collections.Generic; -using System.Linq; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class FunctionInventory : Inventory - { - int sizeofMachinePointer; - public FunctionInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - public override void Add(TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 10, $"expected a top-level function but got a {tld.GetType().Name}"); - - lock (valuesLock) - { - OverloadInventory overloads = null; - if (!values.TryGetValue(tlf.Name, out overloads)) - { - overloads = new OverloadInventory(tlf.Name, sizeofMachinePointer); - values.Add(tlf.Name, overloads); - } - overloads.Add(tlf, srcStm); - } - } - - public TLFunction ContainsEquivalentFunction(TLFunction func) - { - // for finding a func with the same name and signature which may or may not be a thunk - var nameMatched = MethodsWithName(func.Signature.Name); - if (nameMatched.Count == 0) - return null; - foreach (var candidate in nameMatched) - { - if (ArgumentsMatch(candidate, func) && ReturnsMatch(candidate, func) && candidate.Signature.CanThrow == func.Signature.CanThrow) - return candidate; - } - return null; - } - - public void ReplaceFunction(TLFunction original, TLFunction replacement) - { - var overloads = values[original.Name]; - if (overloads == null) - throw new ArgumentException("original function name must be in the inventory"); - if (!overloads.Functions.Remove(original)) - throw new ArgumentException("original function not found"); - overloads.Functions.Add(replacement); - } - - static bool ArgumentsMatch(TLFunction candidate, TLFunction func) - { - if (candidate.Signature.ParameterCount != func.Signature.ParameterCount) - return false; - - for (int i = 0; i < candidate.Signature.ParameterCount; i++) - { - if (!candidate.Signature.GetParameter(i).Equals(func.Signature.GetParameter(i))) - return false; - } - return true; - } - - static bool ReturnsMatch(TLFunction candidate, TLFunction func) - { - return candidate.Signature.ReturnType.Equals(func.Signature.ReturnType); - } - - public IEnumerable> AllMethodsNoCDTor() - { - foreach (SwiftName key in values.Keys) - { - OverloadInventory oi = values[key]; - foreach (TLFunction tlf in oi.Functions) - yield return new Tuple(key, tlf); - } - } - - public List MethodsWithName(SwiftName name) - { - var result = new List(); - foreach (var oi in Values) - { - if (oi.Name.Name == name.Name) - result.AddRange(oi.Functions); - } - return result; - } - - public List MethodsWithName(string name) - { - SwiftName sn = new SwiftName(name, false); - return MethodsWithName(sn); - } - - public List AllocatingConstructors() - { - return MethodsWithName(Decomposer.kSwiftAllocatingConstructorName); - } - - public List DeallocatingDestructors() - { - return MethodsWithName(Decomposer.kSwiftDeallocatingDestructorName); - } - } - -} - diff --git a/src/SwiftReflector/Inventory/Inventory.cs b/src/SwiftReflector/Inventory/Inventory.cs deleted file mode 100644 index 764ab6d94f51..000000000000 --- a/src/SwiftReflector/Inventory/Inventory.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.IO; -using SwiftReflector.Demangling; - - -namespace SwiftReflector.Inventory -{ - public abstract class Inventory - { - protected object valuesLock = new object(); - protected Dictionary values = new Dictionary(); - - public IEnumerable Names { get { return values.Keys; } } - public IEnumerable Values { get { return values.Values; } } - - public abstract void Add(TLDefinition tlf, Stream srcStm); - - public bool ContainsName(SwiftName name) - { - lock (valuesLock) - { - return values.ContainsKey(name); - } - } - public bool ContainsName(string name) - { - return ContainsName(new SwiftName(name, false)); - } - - public bool TryGetValue(SwiftName name, out T value) - { - lock (valuesLock) - { - return values.TryGetValue(name, out value); - } - } - - public bool TryGetValue(string name, out T value) - { - return TryGetValue(new SwiftName(name, false), out value); - } - } -} - diff --git a/src/SwiftReflector/Inventory/ModuleContents.cs b/src/SwiftReflector/Inventory/ModuleContents.cs deleted file mode 100644 index 18310067331e..000000000000 --- a/src/SwiftReflector/Inventory/ModuleContents.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.IO; -using SwiftReflector.Demangling; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Inventory -{ - public class ModuleContents - { - public ModuleContents(SwiftName name, int sizeofMachinePointer) - { - Name = Exceptions.ThrowOnNull(name, nameof(name)); - Classes = new ClassInventory(sizeofMachinePointer); - Functions = new FunctionInventory(sizeofMachinePointer); - Variables = new VariableInventory(sizeofMachinePointer); - WitnessTables = new WitnessInventory(sizeofMachinePointer); - Protocols = new ProtocolInventory(sizeofMachinePointer); - Extensions = new FunctionInventory(sizeofMachinePointer); - MetadataFieldDescriptor = new List(); - MetadataBuiltInDescriptor = new List(); - PropertyDescriptors = new VariableInventory(sizeofMachinePointer); - ExtensionDescriptors = new List(); - } - - public void Add(TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) - { - if (tlf.Signature.IsExtension) - { - Extensions.Add(tlf, srcStm); - } - else if (tlf.IsTopLevelFunction) - { - if (tlf.Signature is SwiftAddressorType) - { - Variables.Add(tlf, srcStm); - } - else if (tlf.Signature is SwiftWitnessTableType) - { - WitnessTables.Add(tld, srcStm); - } - else - { - Functions.Add(tlf, srcStm); - } - } - else - { - if (tlf.Class.EntityKind == MemberNesting.Protocol) - { - Protocols.Add(tlf, srcStm); - } - else - { - Classes.Add(tld, srcStm); - } - } - } - else - { - if (tld is TLVariable tlvar && ((TLVariable)tld).Class == null) - { - if (tlvar is TLPropertyDescriptor propDesc) - { - if (propDesc.ExtensionOn != null) - ExtensionDescriptors.Add(propDesc); - else - PropertyDescriptors.Add(tlvar, srcStm); - } - else - { - Variables.Add(tld, srcStm); - } - } - else if (tld is TLProtocolTypeDescriptor || tld is TLProtocolRequirementsBaseDescriptor) - { - Protocols.Add(tld, srcStm); - } - else if (tld is TLModuleDescriptor module) - { - ModuleDescriptor = module; - } - else if (tld is TLMetadataDescriptor metadata) - { - if (metadata.IsBuiltIn) - MetadataBuiltInDescriptor.Add(metadata); - else - MetadataFieldDescriptor.Add(metadata); - } - else - { - // global unsafe mutable addressors get ignored. We don't need/use them. - if (tld is TLUnsafeMutableAddressor addressor && addressor.Class == null) - return; - Classes.Add(tld, srcStm); - } - } - } - - public TLModuleDescriptor ModuleDescriptor { get; private set; } - public SwiftName Name { get; private set; } - - public WitnessInventory WitnessTables { get; private set; } - public ProtocolInventory Protocols { get; private set; } - public ClassInventory Classes { get; private set; } - public FunctionInventory Functions { get; private set; } - public VariableInventory Variables { get; private set; } - public VariableInventory PropertyDescriptors { get; private set; } - public List ExtensionDescriptors { get; private set; } - public FunctionInventory Extensions { get; private set; } - public List MetadataFieldDescriptor { get; private set; } - public List MetadataBuiltInDescriptor { get; private set; } - } - -} - diff --git a/src/SwiftReflector/Inventory/ModuleInventory.cs b/src/SwiftReflector/Inventory/ModuleInventory.cs deleted file mode 100644 index 54e493e7d35c..000000000000 --- a/src/SwiftReflector/Inventory/ModuleInventory.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Linq; -using System.Collections.Generic; -using System.IO; -using SwiftReflector.ExceptionTools; -using SwiftReflector.IOUtils; -using SwiftReflector.Demangling; -using Xamarin; -using SwiftRuntimeLibrary; -using System.Threading.Tasks; - -namespace SwiftReflector.Inventory -{ - public class ModuleInventory : Inventory - { - public MachO.Architectures Architecture { get; private set; } - public int SizeofMachinePointer - { - get - { - return Architecture == MachO.Architectures.x86_64 || - Architecture == MachO.Architectures.ARM64 ? 8 : 4; - } - } - - public override void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - ModuleContents module = null; - if (!values.TryGetValue(tld.Module, out module)) - { - module = new ModuleContents(tld.Module, SizeofMachinePointer); - values.Add(tld.Module, module); - } - module.Add(tld, srcStm); - } - } - - public static ModuleInventory FromFile(string pathToDynamicLibrary, ErrorHandling errors) - { - Exceptions.ThrowOnNull(pathToDynamicLibrary, nameof(pathToDynamicLibrary)); - FileStream stm = null; - try - { - stm = new FileStream(pathToDynamicLibrary, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 57, e, "unable to open file {0}: {1}\n", pathToDynamicLibrary, e.Message)); - } - try - { - return FromStream(stm, errors, pathToDynamicLibrary); - } - finally - { - stm.Dispose(); - } - } - - public static async Task FromFilesAsync(IEnumerable pathsToLibraryFiles, ErrorHandling errors) - { - var streams = pathsToLibraryFiles.Select(path => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)).ToList(); - if (streams.Count == 0) - return null; - var inventory = new ModuleInventory(); - try - { - var tasks = streams.Select(stm => FromStreamIntoAsync(stm, inventory, errors, stm.Name)); - await Task.WhenAll(tasks); - } - finally - { - foreach (var stm in streams) - { - stm.Dispose(); - } - } - return inventory; - } - - public static ModuleInventory FromFiles(IEnumerable pathsToLibraryFiles, ErrorHandling errors) - { - ModuleInventory inventory = null; - foreach (string path in pathsToLibraryFiles) - { - if (inventory == null) - inventory = new ModuleInventory(); - using (FileStream stm = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - FromStreamInto(stm, inventory, errors, path); - } - } - return inventory; - } - - static async Task FromStreamIntoAsync(Stream stm, ModuleInventory inventory, - ErrorHandling errors, string fileName = null) - { - return await Task.Run(() => - { - return FromStreamInto(stm, inventory, errors, fileName); - }); - } - - static ModuleInventory FromStreamInto(Stream stm, ModuleInventory inventory, - ErrorHandling errors, string fileName = null) - { - // Exceptions.ThrowOnNull (errors, "errors"); - Exceptions.ThrowOnNull(stm, "stm"); - OffsetStream osstm = null; - List entries = null; - try - { - List macho = MachO.Read(stm, null).ToList(); - MachOFile file = macho[0]; - - List symbols = file.load_commands.OfType().ToList(); - NListEntryType nlet = symbols[0].nlist[0].EntryType; - entries = symbols[0].nlist. - Where((nle, i) => nle.IsPublic && nle.EntryType == NListEntryType.InSection).ToList(); - inventory.Architecture = file.Architecture; - osstm = new OffsetStream(stm, file.StartOffset); - } - catch (Exception e) - { - errors.Add(ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 58, e, "Unable to retrieve functions from {0}: {1}", - fileName ?? "stream", e.Message)); - return inventory; - } - - bool isOldVersion = IsOldVersion(entries); - - foreach (var entry in entries) - { - if (!entry.IsSwiftEntryPoint()) - continue; - TLDefinition def = null; - def = Decomposer.Decompose(entry.str, isOldVersion, Offset(entry)); - if (def != null) - { - // this skips over privatized names - var tlf = def as TLFunction; - if (tlf != null && tlf.Name != null && tlf.Name.Name.Contains("...")) - continue; - try - { - inventory.Add(def, osstm); - } - catch (RuntimeException e) - { - e = new RuntimeException(e.Code, e.Error, $"error dispensing top level definition of type {def.GetType().Name} decomposed from {entry.str}: {e.Message}"); - errors.Add(e); - } - } - else - { - var ex = ErrorHelper.CreateWarning(ReflectorError.kInventoryBase + 18, $"entry {entry.str} uses an unsupported swift feature, skipping."); - errors.Add(ex); - } - } - - return inventory; - } - - public static ModuleInventory FromStream(Stream stm, ErrorHandling errors, string fileName = null) - { - ModuleInventory inventory = new ModuleInventory(); - return FromStreamInto(stm, inventory, errors, fileName); - } - - static ulong Offset(NListEntry entry) - { - NListEntry32 nl32 = entry as NListEntry32; - return nl32 != null ? nl32.n_value : ((NListEntry64)entry).n_value; - } - - static bool IsOldVersion(List entries) - { - foreach (NListEntry entry in entries) - { - if (entry.str.StartsWith("__TMd", StringComparison.Ordinal)) - return true; - } - return false; - } - } -} - diff --git a/src/SwiftReflector/Inventory/OverloadInventory.cs b/src/SwiftReflector/Inventory/OverloadInventory.cs deleted file mode 100644 index aea92806ad8e..000000000000 --- a/src/SwiftReflector/Inventory/OverloadInventory.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using SwiftReflector.ExceptionTools; -using System.IO; -using SwiftReflector.Demangling; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Inventory -{ - public class OverloadInventory : Inventory> - { - int sizeofMachinePointer; - public OverloadInventory(SwiftName name, int sizeofMachinePointer) - { - Name = Exceptions.ThrowOnNull(name, nameof(name)); - Functions = new List(); - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public override void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 11, $"expected a top-level function but got a {tld.GetType().Name}"); - if (Functions.Exists(f => tlf.MangledName == f.MangledName)) - { - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 12, $"duplicate function found for {tlf.MangledName}"); - } - else - { - Functions.Add(tlf); - } - } - } - - public List Functions { get; private set; } - - public SwiftName Name { get; private set; } - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } - -} - diff --git a/src/SwiftReflector/Inventory/PropertyContents.cs b/src/SwiftReflector/Inventory/PropertyContents.cs deleted file mode 100644 index 3c25cc0ccf12..000000000000 --- a/src/SwiftReflector/Inventory/PropertyContents.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using SwiftReflector.Demangling; -using SwiftRuntimeLibrary; - -namespace SwiftReflector.Inventory -{ - public class PropertyContents - { - int sizeofMachinePointer; - public PropertyContents(SwiftClassType ofClass, SwiftName propName, int sizeofMachinePointer) - { - Class = Exceptions.ThrowOnNull(ofClass, nameof(ofClass)); - Name = Exceptions.ThrowOnNull(propName, nameof(propName)); - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public SwiftClassType Class { get; private set; } - - public SwiftName Name { get; private set; } - - public void Add(TLFunction tlf, SwiftPropertyType prop) - { - var method = tlf as TLMethodDescriptor; - if (method != null) - { - switch (prop.PropertyType) - { - case PropertyType.Getter: - TLFGetterDescriptor = method; - break; - case PropertyType.Setter: - TLFSetterDescriptor = method; - break; - case PropertyType.Materializer: - TLFMaterializerDescriptor = method; - break; - case PropertyType.DidSet: - TLFDidSetDescriptor = method; - break; - case PropertyType.WillSet: - TLFWillSetDescriptor = method; - break; - case PropertyType.ModifyAccessor: - TLFModifyDescriptor = method; - break; - default: - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 68, $"Unexpected property descriptor {prop.PropertyType.ToString()}"); - } - } - else - { - switch (prop.PropertyType) - { - case PropertyType.Getter: - var oldget = Getter; - Getter = ConditionalChainThunk(prop, oldget); - TLFGetter = oldget == null || Getter != prop ? tlf : TLFGetter; - break; - case PropertyType.Setter: - var oldset = Setter; - Setter = ConditionalChainThunk(prop, oldset); - TLFSetter = oldset == null || Setter != prop ? tlf : TLFSetter; - break; - case PropertyType.Materializer: - var oldmaterialize = Materializer; - Materializer = ConditionalChainThunk(prop, oldmaterialize); - TLFMaterializer = oldmaterialize == null || Materializer != prop ? tlf : TLFMaterializer; - break; - case PropertyType.DidSet: - var olddidset = DidSet; - DidSet = ConditionalChainThunk(prop, olddidset); - TLFDidSet = olddidset == null || DidSet != prop ? tlf : TLFDidSet; - break; - case PropertyType.WillSet: - var oldwillset = WillSet; - WillSet = ConditionalChainThunk(prop, oldwillset); - TLFWillSet = oldwillset == null || WillSet != prop ? tlf : TLFWillSet; - break; - case PropertyType.ModifyAccessor: - var oldmodify = WillSet; - ModifyAccessor = ConditionalChainThunk(prop, oldmodify); - TLFModifyAccessor = oldmodify == null || ModifyAccessor != prop ? tlf : TLFModifyAccessor; - break; - default: - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 2, $"Unexpected property element {prop.PropertyType.ToString()}"); - } - } - } - - static SwiftPropertyType ConditionalChainThunk(SwiftPropertyType newProp, SwiftPropertyType oldProp) - { - if (oldProp == null) - { - return newProp; - } - if (oldProp.IsThunk) - { - newProp.Thunk = oldProp; - return newProp; - } - else if (newProp.IsThunk) - { - oldProp.Thunk = newProp; - return oldProp; - } - else - { - throw new NotImplementedException("At least one needs to be a thunk - should never happen"); - } - } - - SwiftPropertyType getter; - public SwiftPropertyType Getter - { - get - { - return getter; - } - set - { - ThrowOnExistingProperty(getter, "getter"); - getter = value; - } - } - public TLFunction TLFGetter { get; set; } - public TLMethodDescriptor TLFGetterDescriptor { get; set; } - - SwiftPropertyType setter; - public SwiftPropertyType Setter - { - get - { - return setter; - } - set - { - ThrowOnExistingProperty(setter, "setter"); - setter = value; - } - } - public TLFunction TLFSetter { get; set; } - public TLMethodDescriptor TLFSetterDescriptor { get; set; } - - SwiftPropertyType materializer; - public SwiftPropertyType Materializer - { - get - { - return materializer; - } - set - { - ThrowOnExistingProperty(materializer, "materializer"); - materializer = value; - } - } - public TLFunction TLFMaterializer { get; set; } - public TLMethodDescriptor TLFMaterializerDescriptor { get; set; } - - SwiftPropertyType modifyAccessor; - public SwiftPropertyType ModifyAccessor - { - get { return modifyAccessor; } - set - { - ThrowOnExistingProperty(modifyAccessor, "modifyAccessor"); - modifyAccessor = value; - } - } - public TLFunction TLFModifyAccessor { get; set; } - public TLMethodDescriptor TLFModifyDescriptor { get; set; } - - SwiftPropertyType didSet; - public SwiftPropertyType DidSet - { - get - { - return didSet; - } - set - { - ThrowOnExistingProperty(didSet, "did set"); - didSet = value; - } - } - public TLFunction TLFDidSet { get; set; } - public TLMethodDescriptor TLFDidSetDescriptor { get; set; } - - SwiftPropertyType willSet; - public SwiftPropertyType WillSet - { - get - { - return willSet; - } - set - { - ThrowOnExistingProperty(willSet, "will set"); - willSet = value; - } - } - public TLFunction TLFWillSet { get; set; } - public TLMethodDescriptor TLFWillSetDescriptor { get; set; } - - void ThrowOnExistingProperty(SwiftPropertyType prop, string propType) - { - if (prop != null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 6, $"Already have a {propType} entry for property {Name} in {Class.ClassName.ToFullyQualifiedName()}"); - } - - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } - -} - diff --git a/src/SwiftReflector/Inventory/PropertyInventory.cs b/src/SwiftReflector/Inventory/PropertyInventory.cs deleted file mode 100644 index 82c1dd28d48c..000000000000 --- a/src/SwiftReflector/Inventory/PropertyInventory.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.Collections.Generic; -using System.Linq; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class PropertyInventory : Inventory - { - int sizeofMachinePointer; - public PropertyInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public override void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 7, $"Expected a TLFunction for a property but got a {tld.GetType().Name}."); - - SwiftPropertyType prop = tlf.Signature as SwiftPropertyType; - if (prop == null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 8, $"Expected a function of property type but got a {tlf.Signature.GetType().Name}."); - - PropertyContents contents = null; - SwiftName nameToUse = prop.PrivateName ?? prop.Name; - if (!values.TryGetValue(nameToUse, out contents)) - { - contents = new PropertyContents(tlf.Class, nameToUse, sizeofMachinePointer); - values.Add(nameToUse, contents); - } - contents.Add(tlf, prop); - } - } - - public PropertyContents PropertyWithName(SwiftName name) - { - PropertyContents pc = Values.Where(oi => oi.Name.Equals(name)).FirstOrDefault(); - return pc; - } - - public PropertyContents PropertyWithName(string name) - { - SwiftName sn = new SwiftName(name, false); - return PropertyWithName(sn); - } - - } -} - diff --git a/src/SwiftReflector/Inventory/ProtocolContents.cs b/src/SwiftReflector/Inventory/ProtocolContents.cs deleted file mode 100644 index 86ef1e89c2f3..000000000000 --- a/src/SwiftReflector/Inventory/ProtocolContents.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; -using System.Collections.Generic; -using SwiftReflector.ExceptionTools; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class ProtocolContents - { - int sizeofMachinePointer; - public ProtocolContents(SwiftClassName className, int sizeofMachiinePointer) - { - this.sizeofMachinePointer = sizeofMachiinePointer; - WitnessTable = new WitnessInventory(sizeofMachinePointer); - FunctionsOfUnknownDestination = new List(); - DefinitionsOfUnknownDestination = new List(); - BaseDescriptors = new List(); - BaseConformanceDescriptors = new List(); - Name = className; - - } - - public TLMetaclass Metaclass { get; private set; } - public TLDirectMetadata DirectMetadata { get; private set; } - public TLProtocolTypeDescriptor TypeDescriptor { get; private set; } - public WitnessInventory WitnessTable { get; private set; } - public List FunctionsOfUnknownDestination { get; private set; } - public List DefinitionsOfUnknownDestination { get; private set; } - public List BaseDescriptors { get; private set; } - public List BaseConformanceDescriptors { get; private set; } - public SwiftClassName Name { get; private set; } - - public void Add(TLDefinition tld, Stream srcStm) - { - TLFunction tlf = tld as TLFunction; - if (tlf != null) - { - if (ClassContents.IsWitnessTable(tlf.Signature, tlf.Class)) - { - WitnessTable.Add(tlf, srcStm); - } - FunctionsOfUnknownDestination.Add(tlf); - return; - } - - TLDirectMetadata meta = tld as TLDirectMetadata; - if (meta != null) - { - if (DirectMetadata != null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 1, $"duplicate direct metadata in protocol {DirectMetadata.Class.ClassName.ToFullyQualifiedName()}"); - DirectMetadata = meta; - return; - } - TLMetaclass mc = tld as TLMetaclass; - if (mc != null) - { - if (Metaclass != null) - { - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 2, $"duplicate type meta data descriptor in protocol {Metaclass.Class.ClassName.ToFullyQualifiedName()}"); - } - Metaclass = mc; - return; - } - - TLProtocolTypeDescriptor ptd = tld as TLProtocolTypeDescriptor; - if (ptd != null) - { - if (TypeDescriptor != null) - { - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 3, $"duplicate protocol type descriptor in protocol {TypeDescriptor.Class.ClassName.ToFullyQualifiedName()}"); - } - TypeDescriptor = ptd; - return; - } - - if (tld is TLProtocolRequirementsBaseDescriptor baseDescriptor) - { - BaseDescriptors.Add(baseDescriptor); - return; - } - - if (tld is TLBaseConformanceDescriptor baseConformanceDescriptor) - { - BaseConformanceDescriptors.Add(baseConformanceDescriptor); - return; - } - - DefinitionsOfUnknownDestination.Add(tld); - } - } -} - diff --git a/src/SwiftReflector/Inventory/ProtocolInventory.cs b/src/SwiftReflector/Inventory/ProtocolInventory.cs deleted file mode 100644 index aef78d2f85f0..000000000000 --- a/src/SwiftReflector/Inventory/ProtocolInventory.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class ProtocolInventory : Inventory - { - int sizeofMachinePointer; - public ProtocolInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public override void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - SwiftName className = ClassInventory.ToClassName(tld); - SwiftClassName formalName = ClassInventory.ToFormalClassName(tld); - ProtocolContents contents = null; - if (!values.TryGetValue(className, out contents)) - { - contents = new ProtocolContents(formalName, sizeofMachinePointer); - values.Add(className, contents); - } - contents.Add(tld, srcStm); - } - } - } -} - diff --git a/src/SwiftReflector/Inventory/VariableContents.cs b/src/SwiftReflector/Inventory/VariableContents.cs deleted file mode 100644 index bd4cbb994f10..000000000000 --- a/src/SwiftReflector/Inventory/VariableContents.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class VariableContents - { - int sizeofMachinePointer; - public VariableContents(SwiftName name, int sizeofMachinePointer) - { - Name = name; - Addressors = new List(); - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public TLVariable Variable { get; set; } - public List Addressors { get; private set; } - public SwiftName Name { get; private set; } - public int SizeofMachinePointer { get { return sizeofMachinePointer; } } - } -} - diff --git a/src/SwiftReflector/Inventory/VariableInventory.cs b/src/SwiftReflector/Inventory/VariableInventory.cs deleted file mode 100644 index 3979951b8af5..000000000000 --- a/src/SwiftReflector/Inventory/VariableInventory.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class VariableInventory : Inventory - { - int sizeofMachinePointer; - public VariableInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - public override void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - TLVariable vari = tld as TLVariable; - if (vari != null) - { - VariableContents contents = GoGetIt(vari.Name); - if (contents.Variable != null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 4, $"duplicate variable {vari.Name.Name}."); - contents.Variable = vari; - return; - } - - TLFunction tlf = tld as TLFunction; - if (tlf != null) - { - VariableContents contents = GoGetIt(tlf.Name); - contents.Addressors.Add(tlf); - return; - } - - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 5, $"expected a top-level function or top-level variable but got a {tld.GetType().Name}"); - } - - } - - VariableContents GoGetIt(SwiftName name) - { - VariableContents vari = null; - if (!values.TryGetValue(name, out vari)) - { - vari = new VariableContents(name, sizeofMachinePointer); - values.Add(name, vari); - } - return vari; - } - } -} - diff --git a/src/SwiftReflector/Inventory/WitnessInventory.cs b/src/SwiftReflector/Inventory/WitnessInventory.cs deleted file mode 100644 index 42d7c2d327bf..000000000000 --- a/src/SwiftReflector/Inventory/WitnessInventory.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.ExceptionTools; -using System.Collections.Generic; -using System.Linq; -using System.IO; -using SwiftReflector.Demangling; - -namespace SwiftReflector.Inventory -{ - public class WitnessInventory - { - object valuesLock = new object(); - Dictionary values = new Dictionary(); - int sizeofMachinePointer; - - public WitnessInventory(int sizeofMachinePointer) - { - this.sizeofMachinePointer = sizeofMachinePointer; - } - - public void Add(TLDefinition tld, Stream srcStm) - { - lock (valuesLock) - { - TLFunction tlf = tld as TLFunction; - if (tlf == null) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 9, $"Expected a TLFunction for a witness table but got a {tld.GetType().Name}."); - - if (values.ContainsKey(tlf.MangledName)) - throw ErrorHelper.CreateError(ReflectorError.kInventoryBase + 10, $"Already received witness table entry for {tlf.MangledName}."); - values.Add(tlf.MangledName, tlf); - LoadWitnessTable(tlf, srcStm); - } - } - - public IEnumerable MangledNames { get { return values.Keys; } } - public IEnumerable Functions { get { return values.Values; } } - public IEnumerable WitnessEntriesOfType(WitnessType wit) - { - return Functions.Where(fn => (fn.Signature is SwiftWitnessTableType) && ((SwiftWitnessTableType)fn.Signature).WitnessType == wit); - } - - public ValueWitnessTable ValueWitnessTable { get; private set; } - - void LoadWitnessTable(TLFunction tlf, Stream stm) - { - WitnessType type = FromTLF(tlf); - switch (type) - { - case WitnessType.Value: - ValueWitnessTable = ValueWitnessTable.FromStream(stm, tlf, sizeofMachinePointer); - break; - default: - break; - } - } - - WitnessType FromTLF(TLFunction tlf) - { - SwiftWitnessTableType wit = tlf.Signature as SwiftWitnessTableType; - if (wit == null) - throw new ArgumentException("tlf"); - return wit.WitnessType; - } - } - -} - diff --git a/src/SwiftReflector/MachOHawley.cs b/src/SwiftReflector/MachOHawley.cs deleted file mode 100644 index 4fe851bd0525..000000000000 --- a/src/SwiftReflector/MachOHawley.cs +++ /dev/null @@ -1,1434 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; -using System.Linq; -using System.Collections; - -#if MTOUCH -using MonoTouch; -#endif - -namespace Xamarin -{ - public class MachO - { - /* definitions from: /usr/include/mach-o/loader.h */ - /* Constant for the magic field of the mach_header (32-bit architectures) */ - internal const uint MH_MAGIC = 0xfeedface; /* the mach magic number */ - internal const uint MH_CIGAM = 0xcefaedfe; /* NXSwapInt(MH_MAGIC) */ - - /* Constant for the magic field of the mach_header_64 (64-bit architectures) */ - internal const uint MH_MAGIC_64 = 0xfeedfacf; /* the 64-bit mach magic number */ - internal const uint MH_CIGAM_64 = 0xcffaedfe; /* NXSwapInt(MH_MAGIC_64) */ - - /* definitions from: /usr/include/mach-o/fat.h */ - internal const uint FAT_MAGIC = 0xcafebabe; - internal const uint FAT_CIGAM = 0xbebafeca; /* NXSwapLong(FAT_MAGIC) */ - - public enum Architectures - { - None = 0, - i386 = 1, - ARMv6 = 2, - ARMv7 = 4, - ARMv7s = 8, - ARM64 = 16, - x86_64 = 32, - ARM64e = 64, - ARM64_32 = 128, - } - - public enum LoadCommands : uint - { - //#define LC_REQ_DYLD 0x80000000 - ReqDyld = 0x80000000, - // - // /* Constants for the cmd field of all load commands, the type */ - //#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ - Segment = 0x1, - //#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ - SymTab = 0x2, - //#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ - SymSeg = 0x3, - //#define LC_THREAD 0x4 /* thread */ - Thread = 0x4, - //#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ - UnixThread = 0x5, - //#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */ - LoadFVMLib = 0x6, - //#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */ - IDFVMLib = 0x7, - //#define LC_IDENT 0x8 /* object identification info (obsolete) */ - Ident = 0x8, - //#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */ - FVMFile = 0x9, - //#define LC_PREPAGE 0xa /* prepage command (internal use) */ - Prepage = 0xa, - //#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */ - DySymTab = 0x0b, - - //#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */ - LoadDylib = 0xc, - //#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */ - IdDylib = 0xd, - //#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */ - LoadDylinker = 0xe, - //#define LC_ID_DYLINKER 0xf /* dynamic linker identification */ - IdDylinker = 0xf, - //#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */ - PreboundDylib = 0x10, - // /* linked shared library */ - //#define LC_ROUTINES 0x11 /* image routines */ - Routines = 0x11, - //#define LC_SUB_FRAMEWORK 0x12 /* sub framework */ - SubFramework = 0x12, - //#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */ - SubUmbrella = 0x13, - //#define LC_SUB_CLIENT 0x14 /* sub client */ - SubClient = 0x14, - //#define LC_SUB_LIBRARY 0x15 /* sub library */ - SubLibrary = 0x15, - //#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */ - TwolevelHints = 0x16, - //#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */ - PrebindChecksum = 0x17, - // - // /* - // * load a dynamically linked shared library that is allowed to be missing - // * (all symbols are weak imported). - // */ - //#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD) - LoadWeakDylib = 0x18 | ReqDyld, - // - //#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be - Segment64 = 0x19, - // mapped */ - //#define LC_ROUTINES_64 0x1a /* 64-bit image routines */ - Routines64 = 0x1a, - //#define LC_UUID 0x1b /* the uuid */ - Uuid = 0x1b, - //#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */ - RPath = 0x1c | ReqDyld, - //#define LC_CODE_SIGNATURE 0x1d /* local of code signature */ - CodeSignature = 0x1d, - //#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */ - SegmentSplitInfo = 0x1e, - //#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */ - ReexportDylib = 0x1f | ReqDyld, - //#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */ - LazyLoadDylib = 0x20, - //#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */ - EncryptionInfo = 0x21, - //#define LC_DYLD_INFO 0x22 /* compressed dyld information */ - DyldInfo = 0x22, - //#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ - DyldInfoOnly = 0x22 | ReqDyld, - //#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */ - LoadUpwardDylib = 0x23 | ReqDyld, - //#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */ - VersionMinMacOS = 0x24, - //#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */ - VersionMinIPhoneOS = 0x25, - //#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */ - FunctionStarts = 0x26, - //#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat - DyldEnvironment = 0x27, - // like environment variable */ - //#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */ - Main = 0x28 | ReqDyld, - //#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */ - DataInCode = 0x29, - //#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */ - SourceVersion = 0x2a, - //#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */ - DylibCodeSignDrs = 0x2b, - //#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */ - EncryptionInfo64 = 0x2c, - //#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */ - VersionMinTVOS = 0x2f, - //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ - VersionMinWatchOS = 0x30, - //#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */ - Note = 0x31, - //#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */ - BuildVersion = 0x32, - //#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */ - DyldExportsTrie = 0x33 | ReqDyld, - //#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */ - DyldChainedFixups = 0x34 | ReqDyld, - } - - public enum Platform : uint - { - MacOS = 1, - IOS = 2, - TvOS = 3, - WatchOS = 4, - BridgeOS = 5, - IOSSimulator = 7, - TvOSSimulator = 8, - WatchOSSimulator = 9, - } - - internal static uint FromBigEndian(uint number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static int FromBigEndian(int number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static uint ToBigEndian(uint number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - internal static int ToBigEndian(int number) - { - return (((number >> 24) & 0xFF) - | ((number >> 08) & 0xFF00) - | ((number << 08) & 0xFF0000) - | ((number << 24))); - } - - static IDisposable ReadFile(ReaderParameters parameters) - { - var reader = parameters.Reader; - var magic = reader.ReadUInt32(); - reader.BaseStream.Position = 0; - switch (magic) - { - case MH_MAGIC: - case MH_MAGIC_64: - var mf = new MachOFile(parameters); - mf.Read(); - return mf; - case FAT_MAGIC: // little-endian fat binary - case FAT_CIGAM: // big-endian fat binary - { - var f = new FatFile(parameters); - f.Read(); - return f; - } - default: - throw new Exception(string.Format("File format not recognized: {0} (magic: 0x{1})", parameters.Filename ?? "(no file name available)", magic.ToString("X"))); - } - } - - public static MachOFileCollection Read(string filename, ReadingMode mode) - { - var parameters = new ReaderParameters(); - parameters.Filename = filename; - parameters.ReadingMode = mode; - parameters.Reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8, false); - try - { - return GetMachOFiles(parameters, ReadFile(parameters)); - } - finally - { - if (mode == ReadingMode.Immediate) - parameters.Dispose(); - } - } - - static MachOFileCollection GetMachOFiles(ReaderParameters parameters, IDisposable readOutput) - { - var rv = new MachOFileCollection(parameters); - if (readOutput is FatFile fatfile) - { - foreach (var ff in fatfile.entries) - rv.Add(ff.entry); - } - else - { - rv.Add((MachOFile)readOutput); - } - return rv; - } - - public static IEnumerable Read(Stream stm, string filename = null) - { - if (stm == null) - throw new ArgumentNullException(nameof(stm)); - using (var parameters = new ReaderParameters()) - { - parameters.ReadingMode = ReadingMode.Immediate; - parameters.Reader = new BinaryReader(stm, Encoding.UTF8, true); - parameters.Filename = filename; - return GetMachOFiles(parameters, ReadFile(parameters)); - } - } - - public static bool IsMachoFile(string filename) - { - using (FileStream stm = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - return IsMachoFile(stm); - } - } - - public static bool IsMachoFile(Stream stm) - { - using (var reader = new BinaryReader(stm, UTF8Encoding.UTF8, true)) - { - var magic = reader.ReadUInt32(); - reader.BaseStream.Position = 0; - switch (magic) - { - case MH_MAGIC: - case MH_MAGIC_64: - case FAT_MAGIC: // little-endian fat binary - case FAT_CIGAM: // big-endian fat binary - return true; - default: - return false; - } - } - } - - - -#if MTOUCH - // Removes all architectures from the target file, except for those in 'architectures'. - // This method doesn't do anything if the target file is a thin mach-o file. - // Also it doesn't do anything if the result is an empty file (i.e. none of the - // selected architectures match any of the architectures in the file) - this is - // only because I haven't investigated what would be needed elsewhere in the link - // process when the entire file is removed. FIXME <--. - public static void SelectArchitectures (string filename, ICollection abis) - { - var architectures = GetArchitectures (abis); - var tmpfile = filename + ".tmp"; - - if (abis.Count == 0) - return; - - using (var fsr = new FileStream (filename, FileMode.Open, FileAccess.Read)) { - using (var reader = new BinaryReader (fsr)) { - var file = ReadFile (filename); - if (file is MachOFile) { - MTouch.Log (2, "Skipping architecture selecting of '{0}', since it only contains 1 architecture.", filename); - return; - } - - var fatfile = (FatFile) file; - bool any_removed = false; - - // remove architectures we don't want - for (int i = fatfile.entries.Count - 1; i >= 0; i--) { - var ff = fatfile.entries [i]; - if (!architectures.Contains (ff.entry.Architecture)) { - any_removed = true; - fatfile.entries.RemoveAt (i); - fatfile.nfat_arch--; - MTouch.Log (2, "Removing architecture {0} from {1}", ff.entry.Architecture, filename); - } - } - - if (!any_removed) { - MTouch.Log (2, "Architecture selection of '{0}' didn't find any architectures to remove.", filename); - return; - } - - if (fatfile.nfat_arch == 0) { - MTouch.Log (2, "Skipping architecture selection of '{0}', none of the selected architectures match any of the architectures in the archive.", filename, architectures [0]); - return; - } - - if (fatfile.nfat_arch == 1) { - // Thin file - var entry = fatfile.entries [0]; - using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { - using (var writer = new BinaryWriter (fsw)) { - entry.WriteFile (writer, reader, entry.offset); - } - } - } else { - // Fat file - // Re-calculate header data - var read_offset = new List (fatfile.entries.Count); - read_offset.Add (fatfile.entries [0].offset); - fatfile.entries [0].offset = (uint) (1 << (int) fatfile.entries [0].align); - for (int i = 1; i < fatfile.entries.Count; i++) { - read_offset.Add (fatfile.entries [i].offset); - fatfile.entries [i].offset = fatfile.entries [i - 1].offset + fatfile.entries [i - 1].size; - var alignSize = (1 << (int) fatfile.entries [i].align); - var align = (int) fatfile.entries [i].offset % alignSize; - if (align != 0) - fatfile.entries [i].offset += (uint) (alignSize - align); - } - // Write out the fat file - using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { - using (var writer = new BinaryWriter (fsw)) { - // write headers - fatfile.WriteHeaders (writer); - // write data - for (int i = 0; i < fatfile.entries.Count; i++) { - fatfile.entries [i].Write (writer, reader, read_offset [i]); - } - } - } - } - } - } - - File.Delete (filename); - File.Move (tmpfile, filename); - } -#endif - - static Dictionary> native_dependencies = new Dictionary>(); - - public static IEnumerable GetNativeDependencies(string libraryName) - { - IEnumerable result; - lock (native_dependencies) - { - if (native_dependencies.TryGetValue(libraryName, out result)) - return result; - } - - var macho_files = Read(libraryName, ReadingMode.Deferred); - var dependencies = new HashSet(); - foreach (var macho_file in macho_files) - { - foreach (var lc in macho_file.load_commands) - { - var dyld_lc = lc as Xamarin.DylibLoadCommand; - if (dyld_lc != null) - { - dependencies.Add(dyld_lc.name); - } - } - } - result = dependencies; - lock (native_dependencies) - native_dependencies.Add(libraryName, result); - return result; - } - -#if MTOUCH - public static List GetArchitectures (string file) - { - var result = new List (); - - // https://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html - - using (var fs = File.OpenRead (file)) { - using (var reader = new BinaryReader (fs)) { - int magic = reader.ReadInt32 (); - int architectures; - switch ((uint) magic) { - case 0xCAFEBABE: // little-endian fat binary - architectures = reader.ReadInt32 (); - for (int i = 0; i < architectures; i++) { - result.Add (GetArch (reader.ReadInt32 (), reader.ReadInt32 ())); - // skip to next entry - reader.ReadInt32 (); // offset - reader.ReadInt32 (); // size - reader.ReadInt32 (); // align - } - break; - case 0xBEBAFECA: - architectures = System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()); - for (int i = 0; i < architectures; i++) { - result.Add (GetArch (System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()), System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()))); - // skip to next entry - reader.ReadInt32 (); // offset - reader.ReadInt32 (); // size - reader.ReadInt32 (); // align - } - break; - case 0xFEEDFACE: // little-endian mach-o header - case 0xFEEDFACF: // little-endian 64-big mach-o header - result.Add (GetArch (reader.ReadInt32 (), reader.ReadInt32 ())); - break; - case 0xCFFAEDFE: - case 0xCEFAEDFE: - result.Add (GetArch (System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()), System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()))); - break; - default: - Console.WriteLine ("File '{0}' is neither a Universal binary nor a Mach-O binary (magic: 0x{1})", file, magic.ToString ("x")); - break; - } - } - } - - return result; - } - - public static List GetArchitectures (ICollection abi) - { - var rv = new List (abi.Count); - foreach (var a in abi) { - rv.Add ((Architectures) (a & Abi.ArchMask)); - } - return rv; - } - - static Abi GetArch (int cputype, int cpusubtype) - { - switch (cputype) { - case 12: // arm - switch (cpusubtype) { - case 6: - return Abi.ARMv6; - case 9: - return Abi.ARMv7; - case 11: - return Abi.ARMv7s; - default: - return Abi.None; - } - case 12 | 0x01000000: - return Abi.ARM64; - case 7: // x86 - return Abi.i386; - case 7 | 0x01000000: // x64 - return Abi.x86_64; - } - - return Abi.None; - } -#endif - } - - public class StaticLibrary - { - public static bool IsStaticLibrary(BinaryReader reader) - { - var pos = reader.BaseStream.Position; - - var bytes = reader.ReadBytes(8); - var rv = bytes[0] == '!' && bytes[1] == '<' && bytes[2] == 'a' && bytes[3] == 'r' && bytes[4] == 'c' && bytes[5] == 'h' && bytes[6] == '>' && bytes[7] == 0xa; - reader.BaseStream.Position = pos; - - return rv; - } - } - - public enum ReadingMode - { - Immediate = 1, - Deferred = 2, - } - - sealed class ReaderParameters : IDisposable - { - public BinaryReader Reader; - public string Filename; - public ReadingMode ReadingMode { get; set; } - - #region IDisposable Support - void Dispose(bool disposing) - { - Reader?.Dispose(); - } - - ~ReaderParameters() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #endregion - } - - public class MachOFileCollection : List, IDisposable - { - internal ReaderParameters Parameters { get; private set; } - - internal MachOFileCollection(ReaderParameters parameters) - { - Parameters = parameters; - } - - #region IDisposable Support - protected virtual void Dispose(bool disposing) - { - Parameters.Dispose(); - } - - ~MachOFileCollection() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #endregion - } - - public class MachOFile : IDisposable - { - internal ReaderParameters parameters { get; private set; } - public uint magic; - public int cputype; - public int cpusubtype; - public uint filetype; - public uint ncmds; - public uint sizeofcmds; - public uint flags; - public uint reserved; - - public List load_commands; - - internal MachOFile(ReaderParameters parameters) - { - this.parameters = parameters; - } - - internal void WriteHeader(BinaryWriter writer) - { - writer.Write(magic); - writer.Write(cputype); - writer.Write(cpusubtype); - writer.Write(filetype); - writer.Write(ncmds); - writer.Write(sizeofcmds); - writer.Write((uint)flags); - if (magic == MachO.MH_MAGIC_64) - writer.Write(reserved); - } - - internal static bool IsMachOLibrary(BinaryReader reader) - { - var pos = reader.BaseStream.Position; - var magic = reader.ReadUInt32(); - var rv = false; - switch (magic) - { - case MachO.MH_CIGAM: - case MachO.MH_MAGIC: - case MachO.MH_CIGAM_64: - case MachO.MH_MAGIC_64: - rv = true; - break; - default: - rv = false; - break; - } - reader.BaseStream.Position = pos; - return rv; - } - - internal void Read() - { - /* definitions from: /usr/include/mach-o/loader.h */ - /* - * The 32-bit mach header appears at the very beginning of the object file for - * 32-bit architectures. - */ - // struct mach_header { - // uint32_t magic; /* mach magic number identifier */ - // cpu_type_t cputype; /* cpu specifier */ - // cpu_subtype_t cpusubtype; /* machine specifier */ - // uint32_t filetype; /* type of file */ - // uint32_t ncmds; /* number of load commands */ - // uint32_t sizeofcmds; /* the size of all the load commands */ - // uint32_t flags; /* flags */ - // }; - - /* - * The 64-bit mach header appears at the very beginning of object files for - * 64-bit architectures. - */ - // struct mach_header_64 { - // uint32_t magic; /* mach magic number identifier */ - // cpu_type_t cputype; /* cpu specifier */ - // cpu_subtype_t cpusubtype; /* machine specifier */ - // uint32_t filetype; /* type of file */ - // uint32_t ncmds; /* number of load commands */ - // uint32_t sizeofcmds; /* the size of all the load commands */ - // uint32_t flags; /* flags */ - // uint32_t reserved; /* reserved */ - // }; - var reader = parameters.Reader; - StartOffset = reader.BaseStream.Position; - if (!MachOFile.IsMachOLibrary(reader)) - { - if (StaticLibrary.IsStaticLibrary(reader)) - { - throw new Exception("Static libraries are not supported (yet)."); - } - throw new Exception($"Unknown format for fat entry at position {StartOffset}"); - } - magic = reader.ReadUInt32(); - cputype = reader.ReadInt32(); - cpusubtype = reader.ReadInt32(); - filetype = reader.ReadUInt32(); - ncmds = reader.ReadUInt32(); - sizeofcmds = reader.ReadUInt32(); - flags = reader.ReadUInt32(); - if (magic == MachO.MH_MAGIC_64) - reserved = reader.ReadUInt32(); - var cmds = new List((int)ncmds); - for (int i = 0; i < ncmds; i++) - { - var cmd = (MachO.LoadCommands)reader.ReadUInt32(); - reader.BaseStream.Position -= 4; - LoadCommand lc; - switch (cmd) - { - case MachO.LoadCommands.LoadDylib: - case MachO.LoadCommands.LoadWeakDylib: - case MachO.LoadCommands.ReexportDylib: - lc = DylibLoadCommand.FromBinaryReader(reader); - break; - case MachO.LoadCommands.SymTab: - lc = SymTabLoadCommand.FromBinaryReader(this, StartOffset); - break; - case MachO.LoadCommands.VersionMinTVOS: - case MachO.LoadCommands.VersionMinMacOS: - case MachO.LoadCommands.VersionMinIPhoneOS: - case MachO.LoadCommands.VersionMinWatchOS: - lc = VersionMinOSLoadCommand.FromBinaryReader(reader); - break; - case MachO.LoadCommands.BuildVersion: - var buildVer = new BuildVersionCommand(); - buildVer.cmd = reader.ReadUInt32(); - buildVer.cmdsize = reader.ReadUInt32(); - buildVer.platform = reader.ReadUInt32(); - buildVer.minos = reader.ReadUInt32(); - buildVer.sdk = reader.ReadUInt32(); - buildVer.ntools = reader.ReadUInt32(); - buildVer.tools = new BuildVersionCommand.BuildToolVersion[buildVer.ntools]; - for (int j = 0; j < buildVer.ntools; j++) - { - var buildToolVer = new BuildVersionCommand.BuildToolVersion(); - buildToolVer.tool = reader.ReadUInt32(); - buildToolVer.version = reader.ReadUInt32(); - buildVer.tools[j] = buildToolVer; - } - lc = buildVer; - break; - default: - lc = new LoadCommand(); - lc.cmd = reader.ReadUInt32(); - lc.cmdsize = reader.ReadUInt32(); - reader.BaseStream.Position += lc.cmdsize - 8; - break; - } - cmds.Add(lc); - } - load_commands = cmds; - } - - public MachO.Architectures Architecture - { - get - { - switch (cputype) - { - case 12: // arm - switch (cpusubtype) - { - case 6: - return MachO.Architectures.ARMv6; - case 9: - return MachO.Architectures.ARMv7; - case 11: - return MachO.Architectures.ARMv7s; - default: - return MachO.Architectures.None; - } - case 12 | 0x01000000: - switch (cpusubtype) - { - case 2: - return MachO.Architectures.ARM64e; - case 0: - default: - return MachO.Architectures.ARM64; - } - case 12 | 0x02000000: - switch (cpusubtype & ~0xff000000) - { - case 1: - return MachO.Architectures.ARM64_32; - default: - return MachO.Architectures.ARM64; - } - case 7: // x86 - return MachO.Architectures.i386; - case 7 | 0x01000000: // x64 - return MachO.Architectures.x86_64; - } - - return MachO.Architectures.None; - } - } - - public bool Is32Bit - { - get - { - switch (Architecture) - { - case MachO.Architectures.ARMv6: - case MachO.Architectures.ARMv7: - case MachO.Architectures.ARMv7s: - case MachO.Architectures.i386: - case MachO.Architectures.None: // not sure what to do with None. - return true; - default: - return false; - } - } - } - - public long StartOffset { get; private set; } - - public class MinOSVersion - { - public Version Version; - public string OSName - { - get - { - switch (Platform) - { - case MachO.Platform.IOS: - case MachO.Platform.IOSSimulator: - return "ios"; - case MachO.Platform.MacOS: - return "macosx"; - case MachO.Platform.TvOS: - case MachO.Platform.TvOSSimulator: - return "tvos"; - case MachO.Platform.WatchOS: - case MachO.Platform.WatchOSSimulator: - return "watchos"; - default: - throw new ArgumentOutOfRangeException(Platform.ToString()); - } - } - } - public MachO.Platform Platform; - public Version Sdk; - } - - public MinOSVersion MinOS - { - get - { - uint? version = null; - uint? sdk = null; - MachO.Platform platform = (MachO.Platform)0; - foreach (var lc in load_commands) - { - if (lc is VersionMinOSLoadCommand min_lc) - { - if (version.HasValue) - throw new NotSupportedException("File has multiple minOS load commands."); - version = min_lc.version; - sdk = min_lc.sdk; - - switch (min_lc.Command) - { - case MachO.LoadCommands.VersionMinMacOS: - platform = MachO.Platform.MacOS; - break; - case MachO.LoadCommands.VersionMinIPhoneOS: - platform = MachO.Platform.IOS; - break; - case MachO.LoadCommands.VersionMinTVOS: - platform = MachO.Platform.TvOS; - break; - case MachO.LoadCommands.VersionMinWatchOS: - platform = MachO.Platform.WatchOS; - break; - default: - throw new ArgumentOutOfRangeException(nameof(min_lc.Command)); - } - } - else if (lc is BuildVersionCommand build_lc) - { - if (version.HasValue) - throw new NotSupportedException("File has multiple minOS load commands."); - version = build_lc.minos; - sdk = build_lc.sdk; - platform = build_lc.Platform; - } - } - if (!version.HasValue) - return null; - - return new MinOSVersion - { - Version = BuildVersionCommand.DeNibble(version.Value), - Platform = platform, - Sdk = BuildVersionCommand.DeNibble(sdk.Value) - }; - } - } - - #region IDisposable Support - protected virtual void Dispose(bool disposing) - { - parameters?.Dispose(); - } - - ~MachOFile() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #endregion - } - - public class FatFile : IDisposable - { - internal ReaderParameters parameters { get; private set; } - public uint magic; - public uint nfat_arch; - - public List entries; - internal FatFile(ReaderParameters parameters) - { - this.parameters = parameters; - } - - internal bool is_big_endian - { - get { return magic == MachO.FAT_CIGAM; } - } - - internal void WriteHeader(BinaryWriter writer) - { - writer.Write(magic); - if (is_big_endian) - { - writer.Write(MachO.ToBigEndian(nfat_arch)); - } - else - { - writer.Write(nfat_arch); - } - } - - internal void WriteHeaders(BinaryWriter writer) - { - WriteHeader(writer); - for (int i = 0; i < entries.Count; i++) - { - entries[i].WriteHeader(writer); - } - } - - internal void Read() - { - var reader = parameters.Reader; - magic = reader.ReadUInt32(); - nfat_arch = reader.ReadUInt32(); - if (is_big_endian) - nfat_arch = MachO.FromBigEndian(nfat_arch); - - entries = new List((int)nfat_arch); - for (int i = 0; i < (int)nfat_arch; i++) - { - var entry = new FatEntry(this); - entry.Read(); - entries.Add(entry); - } - foreach (var entry in entries) - entry.ReadEntry(); - } - - #region IDisposable Support - protected virtual void Dispose(bool disposing) - { - parameters.Dispose(); - } - - ~FatFile() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #endregion - } - - public class FatEntry - { - FatFile parent; - public int cputype; - public int cpusubtype; - public uint offset; - public uint size; - public uint align; - - public MachOFile entry; - - public FatEntry(FatFile parent) - { - this.parent = parent; - } - - internal void WriteHeader(BinaryWriter writer) - { - if (parent.is_big_endian) - { - writer.Write(MachO.ToBigEndian(cputype)); - writer.Write(MachO.ToBigEndian(cpusubtype)); - writer.Write(MachO.ToBigEndian(offset)); - writer.Write(MachO.ToBigEndian(size)); - writer.Write(MachO.ToBigEndian(align)); - } - else - { - writer.Write(cputype); - writer.Write(cpusubtype); - writer.Write(offset); - writer.Write(size); - writer.Write(align); - } - } - - internal void Write(BinaryWriter writer, BinaryReader reader, uint reader_offset) - { - writer.BaseStream.Position = offset; - // write data - WriteFile(writer, reader, reader_offset); - } - - internal void WriteFile(BinaryWriter writer, BinaryReader reader, uint reader_offset) - { - // write data - var ofs = writer.BaseStream.Position; - reader.BaseStream.Position = reader_offset; - var buffer = new byte[1 << (int)align]; - var left = (int)size; - while (left > 0) - { - var read = reader.Read(buffer, 0, Math.Min(buffer.Length, left)); - writer.Write(buffer, 0, read); - left -= read; - } - writer.BaseStream.Position = ofs; // restore to the post-header location. - } - - internal void Read() - { - var reader = parent.parameters.Reader; - cputype = reader.ReadInt32(); - cpusubtype = reader.ReadInt32(); - offset = reader.ReadUInt32(); - size = reader.ReadUInt32(); - align = reader.ReadUInt32(); - - if (parent.is_big_endian) - { - cputype = MachO.FromBigEndian(cputype); - cpusubtype = MachO.FromBigEndian(cpusubtype); - offset = MachO.FromBigEndian(offset); - size = MachO.FromBigEndian(size); - align = MachO.FromBigEndian(align); - } - } - - internal void ReadEntry() - { - var reader = parent.parameters.Reader; - reader.BaseStream.Position = offset; - entry = new MachOFile(parent.parameters); - entry.Read(); - } - } - - public class LoadCommand - { - public uint cmd; - public uint cmdsize; - - public MachO.LoadCommands Command - { - get { return (MachO.LoadCommands)cmd; } - } - -#if DEBUG - public virtual void Dump() - { - Console.WriteLine(" cmd: {0}", cmd); - Console.WriteLine(" cmdsize: {0}", cmdsize); - } -#endif - - public override string ToString() - { - return Command.ToString(); - } - } - - public class DylibLoadCommand : LoadCommand - { - public string name; - public uint timestamp; - public uint current_version; - public uint compatibility_version; - - public static LoadCommand FromBinaryReader(BinaryReader reader) - { - var dlc = new DylibLoadCommand(); - dlc.cmd = reader.ReadUInt32(); - dlc.cmdsize = reader.ReadUInt32(); - /*var nameofs = */ - reader.ReadUInt32(); - dlc.timestamp = reader.ReadUInt32(); - dlc.current_version = reader.ReadUInt32(); - dlc.compatibility_version = reader.ReadUInt32(); - var namelength = dlc.cmdsize - 6 * 4; - var namechars = reader.ReadBytes((int)namelength); - // strip off any null characters at the end. - for (int n = namechars.Length - 1; n >= 0; n--) - { - if (namechars[n] == 0) - namelength--; - else - break; - } - dlc.name = System.Text.UTF8Encoding.UTF8.GetString(namechars, 0, (int)namelength); - return dlc; - } - -#if DEBUG - public override void Dump() - { - base.Dump(); - Console.WriteLine(" name: {0}", name); - Console.WriteLine(" timestamp: {0}", timestamp); - Console.WriteLine(" current_version: {0}", current_version); - Console.WriteLine(" compatibility_version: {0}", compatibility_version); - } -#endif - } - - public class VersionMinOSLoadCommand : LoadCommand - { - public uint version; - public uint sdk; - public static LoadCommand FromBinaryReader(BinaryReader reader) - { - var vmlc = new VersionMinOSLoadCommand(); - vmlc.cmd = reader.ReadUInt32(); - vmlc.cmdsize = reader.ReadUInt32(); - vmlc.version = reader.ReadUInt32(); - vmlc.sdk = reader.ReadUInt32(); - return vmlc; - } - string ToConventionalString(uint val) - { - uint major = val >> 16; - uint minor = (val >> 8) & 0xff; - uint sub = val & 0xff; - if (sub == 0) - return $"{major}.{minor}"; - else - return $"{major}.{minor}.{sub}"; - } - string ToOperatingSystemString(uint theCmd) - { - switch ((MachO.LoadCommands)theCmd) - { - case MachO.LoadCommands.VersionMinMacOS: - return "macosx"; - case MachO.LoadCommands.VersionMinIPhoneOS: - return "ios"; - case MachO.LoadCommands.VersionMinTVOS: - return "tvos"; - case MachO.LoadCommands.VersionMinWatchOS: - return "watchos"; - default: - throw new ArgumentOutOfRangeException(nameof(theCmd)); - } - } - - public string ToOSVersionString() - { - return $"{ToConventionalString(version)}"; - } - - public string ToOSString(bool isx8664) - { - return $"{ToOperatingSystemString(cmd)}{ToConventionalString(version)}"; - } - } - - - - public class SymTabLoadCommand : LoadCommand - { - MachOFile file; - long startOffset; - - public uint symoff; /* symbol table offset */ - public uint nsyms; /* number of symbol table entries */ - public uint stroff; /* string table offset */ - public uint strsize; /* string table size in bytes */ - NListEntry[] _nlist; - - public NListEntry[] nlist - { - get - { - if (_nlist == null) - ReadNList(); - return _nlist; - } - } - - public static LoadCommand FromBinaryReader(MachOFile file, long startOffset) - { - var parameters = file.parameters; - var reader = parameters.Reader; - - var stc = new SymTabLoadCommand(); - stc.file = file; - stc.startOffset = startOffset; - stc.cmd = reader.ReadUInt32(); - stc.cmdsize = reader.ReadUInt32(); - stc.symoff = reader.ReadUInt32(); - stc.nsyms = reader.ReadUInt32(); - stc.stroff = reader.ReadUInt32(); - stc.strsize = reader.ReadUInt32(); - if (parameters.ReadingMode == ReadingMode.Immediate) - stc.ReadNList(); - return stc; - } - - public void ReadNList() - { - var reader = file.parameters.Reader; - _nlist = new NListEntry[nsyms]; - long savePos = reader.BaseStream.Position; - try - { - reader.BaseStream.Seek(startOffset + symoff, SeekOrigin.Begin); - for (uint i = 0; i < nsyms; i++) - _nlist[i] = NListEntry.FromBinaryReader(reader, file.Is32Bit); - - for (uint i = 0; i < nsyms; i++) - { - var entry = _nlist[i]; - reader.BaseStream.Seek(startOffset + stroff + entry.n_strx, SeekOrigin.Begin); - entry.str = ReadStringEntry(reader); - } - } - finally - { - reader.BaseStream.Seek(savePos, SeekOrigin.Begin); - } - } - - - static string ReadStringEntry(BinaryReader reader) - { - StringBuilder builder = new StringBuilder(); - byte b; - while ((b = reader.ReadByte()) != 0) - { - builder.Append((char)b); - } - return builder.ToString(); - } - - IEnumerable PublicSymbols - { - get - { - return nlist.Where((nle, i) => nle.IsPublic && !nle.IsSymbolicDebuggerEntry); - } - } - -#if DEBUG - public override void Dump() - { - base.Dump(); - Console.WriteLine(" symoff: {0}", symoff); - Console.WriteLine(" nsyms: {0}", nsyms); - Console.WriteLine(" stroff: {0}", stroff); - Console.WriteLine(" strsize: {0}", strsize); - } -#endif - } - - public class BuildVersionCommand : LoadCommand - { - public uint platform; - public uint minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ - public uint sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ - public uint ntools; - public BuildToolVersion[] tools; - - public class BuildToolVersion - { - public uint tool; - public uint version; - } - - public static Version DeNibble(uint value) - { - var major = (int)(value >> 16); - var minor = (int)((value >> 8) & 0xff); - var sub = (int)(value & 0xff); - if (sub == 0) - { - // This makes sure the string version is a two-part version (X.Y) when the 'sub' version is 0, - // otherwise various toolchain tools (swiftc among others) will complain. - return new Version(major, minor); - } - else - { - // Here we have no choice but to be a three-part version (X.Y.Z). - return new Version(major, minor, sub); - } - } - - public Version MinOS - { - get { return DeNibble(minos); } - } - - public Version Sdk - { - get { return DeNibble(sdk); } - } - - public MachO.Platform Platform - { - get { return (MachO.Platform)platform; } - } - } - - // #define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */ - // #define N_ABS 0x2 /* absolute, n_sect == NO_SECT */ - // #define N_SECT 0xe /* defined in section number n_sect */ - // #define N_PBUD 0xc /* prebound undefined (defined in a dylib) */ - // #define N_INDR 0xa /* indirect */ - - public enum NListEntryType - { - Undefined = 0, - Absolute = 0x2, - InSection = 0xe, - PreboundUndefined = 0x0c, - Indirect = 0x0a - }; - - public class NListEntry - { - const int kSymbolTableMask = 0xe0, - kPrivateExternalMask = 0x10, - kTypeMask = 0x0e, - kExternalMask = 0x01; - - // from nlist.h - public int n_strx; - public byte n_type; - public byte n_sect; - public short n_desc; - public string str; - - public static NListEntry FromBinaryReader(BinaryReader reader, bool is32Bit) - { - NListEntry entry = is32Bit ? (NListEntry)new NListEntry32() : (NListEntry)new NListEntry64(); - return entry.FromBinaryReader(reader); - } - - protected virtual NListEntry FromBinaryReader(BinaryReader reader) - { - n_strx = reader.ReadInt32(); - n_type = reader.ReadByte(); - n_sect = reader.ReadByte(); - n_desc = reader.ReadInt16(); - return this; - } - - public NListEntryType EntryType - { - get - { - switch (n_type & kTypeMask) - { - case 0x2: - return NListEntryType.Absolute; - case 0xa: - return NListEntryType.Indirect; - case 0xc: - return NListEntryType.PreboundUndefined; - case 0xe: - return NListEntryType.InSection; - default: - return NListEntryType.Undefined; - } - } - } - - public bool IsSymbolicDebuggerEntry { get { return (n_type & kSymbolTableMask) != 0; } } - public bool IsPublic { get { return (n_type & kExternalMask) != 0; } } - public bool IsPrivate { get { return (n_type & kPrivateExternalMask) != 0; } } - - public override string ToString() - { - return str ?? ""; - } - } - - public class NListEntry32 : NListEntry - { - public uint n_value; - - protected override NListEntry FromBinaryReader(BinaryReader reader) - { - base.FromBinaryReader(reader); - n_value = reader.ReadUInt32(); - return this; - } - } - - public class NListEntry64 : NListEntry - { - public ulong n_value; - protected override NListEntry FromBinaryReader(BinaryReader reader) - { - base.FromBinaryReader(reader); - n_value = reader.ReadUInt64(); - return this; - } - } -} - diff --git a/src/SwiftReflector/MarshalEngine.cs b/src/SwiftReflector/MarshalEngine.cs deleted file mode 100644 index e85e1abd52e2..000000000000 --- a/src/SwiftReflector/MarshalEngine.cs +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using SyntaxDynamo.CSLang; -using System.Text; -using System.Linq; -using SwiftRuntimeLibrary; -using SwiftReflector.TypeMapping; -using SyntaxDynamo; -using SwiftReflector.SwiftXmlReflection; -using SwiftReflector.Demangling; - -namespace SwiftReflector -{ - public class MarshalEngine - { - CSUsingPackages use; - List identifiersUsed; - TypeMapper typeMapper; - public bool skipThisParameterPremarshal = false; - List fixedChain = new List(); - Version swiftLangVersion; - public Func genericReferenceNamer = null; - - public MarshalEngine(CSUsingPackages use, List identifiersUsed, TypeMapper typeMapper, Version swiftLangVersion) - { - this.use = use; - this.identifiersUsed = identifiersUsed; - absolutelyMustBeFirst = new List(); - preMarshalCode = new List(); - postMarshalCode = new List(); - - this.typeMapper = typeMapper; - this.swiftLangVersion = swiftLangVersion; - } - - public IEnumerable MarshalFunctionCall(FunctionDeclaration wrapperFuncDecl, bool isExtension, string pinvokeCall, - CSParameterList pl, - BaseDeclaration typeContext, - TypeSpec swiftReturnType, - CSType returnType, - TypeSpec swiftInstanceType, - CSType instanceType, - bool includeCastToReturnType, - FunctionDeclaration originalFunction, - bool includeIntermediateCastToLong = false, - int passedInIndexOfReturn = -1, - bool originalThrows = false, - bool restoreDynamicSelf = false) - { - RequiredUnsafeCode = false; - preMarshalCode.Clear(); - postMarshalCode.Clear(); - fixedChain.Clear(); - returnLine = null; - functionCall = null; - - var parms = new CSParameterList(pl); // work with local copy - CSIdentifier returnIdent = null, returnIntPtr = null, returnProtocol = null; - var indexOfReturn = passedInIndexOfReturn; - - var originalReturn = swiftReturnType; - - int indexOfInstance = (swiftReturnType != null && (typeMapper.MustForcePassByReference(typeContext, swiftReturnType)) && !swiftReturnType.IsDynamicSelf) || originalThrows ? - 1 : 0; - var instanceIsSwiftProtocol = false; - var instanceIsObjC = false; - - if (swiftInstanceType != null) - { - var entity = typeMapper.GetEntityForTypeSpec(swiftInstanceType); - instanceIsSwiftProtocol = entity.EntityType == EntityType.Protocol; - instanceIsObjC = entity.Type.IsObjC; - var thisIdentifier = isExtension ? new CSIdentifier("self") : CSIdentifier.This; - parms.Insert(0, new CSParameter(instanceType, thisIdentifier, wrapperFuncDecl.ParameterLists.Last()[indexOfInstance].IsInOut ? - CSParameterKind.Ref : CSParameterKind.None)); - } - - var hasReturn = returnType != null && returnType != CSSimpleType.Void; - - if (hasReturn) - returnType = ReworkTypeWithNamer(returnType); - - var isExtensionMethod = pl.Count() > 0 && pl[0].ParameterKind == CSParameterKind.This; - var returnIsScalar = returnType != null && TypeMapper.IsScalar(swiftReturnType); - var returnEntity = hasReturn && !typeContext.IsTypeSpecGenericReference(swiftReturnType) ? typeMapper.GetEntityForTypeSpec(swiftReturnType) : null; - var returnIsTrivialEnum = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.TrivialEnum; - var returnIsGenericClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class && swiftReturnType.ContainsGenericParameters; - var returnIsClass = hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Class; - var returnIsNonTrivialTuple = hasReturn && swiftReturnType is TupleTypeSpec && ((TupleTypeSpec)swiftReturnType).Elements.Count > 1; - var returnIsClosure = hasReturn && swiftReturnType is ClosureTypeSpec; - var returnIsGeneric = hasReturn && typeContext.IsTypeSpecGeneric(swiftReturnType) && !returnIsClosure; - var returnIsAssocPath = hasReturn && typeContext.IsProtocolWithAssociatedTypesFullPath(swiftReturnType as NamedTypeSpec, typeMapper); - var returnIsNonScalarStruct = hasReturn && !returnIsScalar && returnEntity != null && - (returnEntity.EntityType == EntityType.Struct || returnEntity.EntityType == EntityType.Enum); - var returnIsSelf = hasReturn && swiftReturnType.IsDynamicSelf; - - var retSimple = returnType as CSSimpleType; - var returnIsInterfaceFromProtocol = - hasReturn && returnEntity != null && returnEntity.EntityType == EntityType.Protocol && retSimple != null; - var returnIsProtocolList = hasReturn && swiftReturnType is ProtocolListTypeSpec; - var returnIsObjCProtocol = hasReturn && returnEntity != null && returnEntity.IsObjCProtocol; - var returnNeedsPostProcessing = (hasReturn && (returnIsClass || returnIsProtocolList || returnIsInterfaceFromProtocol || returnIsNonTrivialTuple || - returnIsGeneric || returnIsNonScalarStruct || returnIsAssocPath || (returnIsSelf && !restoreDynamicSelf))) || originalThrows - || returnIsTrivialEnum; - - includeCastToReturnType = includeCastToReturnType || returnIsTrivialEnum; - includeIntermediateCastToLong = includeIntermediateCastToLong || returnIsTrivialEnum; - - var filteredTypeSpec = FilterParams(parms, wrapperFuncDecl, originalThrows); - - var callParameters = new List(parms.Count); - - var offsetToOriginalArgs = 0; - if ((hasReturn && indexOfReturn >= 0) || originalThrows) - offsetToOriginalArgs++; - if (swiftInstanceType != null) - offsetToOriginalArgs++; - if (isExtensionMethod && swiftInstanceType == null) - offsetToOriginalArgs++; - - for (int i = 0; i < parms.Count; i++) - { - var p = parms[i]; - // if it's the instance, pass that - // if it's the return, pass that - // otherwise take it from the original functions primary parameter list - TypeSpec originalParm = null; - - if (i == indexOfInstance && swiftInstanceType != null) - { - originalParm = swiftInstanceType; - } - else if ((hasReturn && i == indexOfReturn) || (originalThrows && i == indexOfReturn)) - { - originalParm = swiftReturnType; - } - else if (isExtensionMethod && p.ParameterKind == CSParameterKind.This) - { - originalParm = originalFunction.IsExtension ? originalFunction.ParentExtension.ExtensionOnType : - new NamedTypeSpec(originalFunction.Parent.ToFullyQualifiedNameWithGenerics()); - } - else - { - var index = i - offsetToOriginalArgs; - originalParm = originalFunction.ParameterLists.Last()[i - offsetToOriginalArgs].TypeSpec; - } - callParameters.Add(Marshal(typeContext, wrapperFuncDecl, p, filteredTypeSpec[i], instanceIsSwiftProtocol && i == indexOfInstance, - indexOfReturn >= 0 && i == indexOfReturn, originalParm)); - } - - - var call = new CSFunctionCall(pinvokeCall, false, callParameters.ToArray()); - - // Post marshal code demands an intermediate return value - if (postMarshalCode.Count > 0 && ((object)returnIdent) == null && (returnType != null && returnType != CSSimpleType.Void)) - { - returnIdent = new CSIdentifier(Uniqueify("retval", identifiersUsed)); - identifiersUsed.Add(returnIdent.Name); - preMarshalCode.Add(CSVariableDeclaration.VarLine(returnType, returnIdent, returnType.Default())); - } - - - if (((object)returnIdent) != null) - { - // if returnIntPtr is non-null, then the function returns a pointer to a class - // If this is the case, we have post marshal code which will assign it to - // retval. - - if (typeMapper.MustForcePassByReference(typeContext, swiftReturnType) || returnIsNonTrivialTuple || returnIsProtocolList) - { - this.functionCall = new CSLine(call); - } - else - { - CSBaseExpression callExpr = call; - if (includeCastToReturnType && returnType != null && returnType != CSSimpleType.Void) - { - if (includeIntermediateCastToLong) - { - callExpr = new CSCastExpression(CSSimpleType.Long, callExpr); - } - callExpr = new CSCastExpression(returnType, callExpr); - } - this.functionCall = CSAssignment.Assign((returnIntPtr ?? returnProtocol) ?? returnIdent, callExpr); - } - this.returnLine = CSReturn.ReturnLine(returnIdent); - } - else - { - if (returnType != null && returnType != CSSimpleType.Void) - { - if (includeCastToReturnType) - { - CSBaseExpression expr = call; - if (includeIntermediateCastToLong) - { - expr = new CSCastExpression(CSSimpleType.Long, expr); - } - expr = new CSCastExpression(returnType, expr); - this.functionCall = CSReturn.ReturnLine(expr); - } - else - { - this.functionCall = CSReturn.ReturnLine((ICSExpression)call); - } - } - else - this.functionCall = new CSLine(call); - } - - foreach (var l in absolutelyMustBeFirst) - yield return l; - foreach (var l in preMarshalCode) - yield return l; - yield return functionCall; - foreach (var l in postMarshalCode) - yield return l; - if (returnLine != null) - yield return returnLine; - } - - CSParameter ReworkParameterWithNamer(CSParameter p) - { - if (GenericReferenceNamer == null) - return p; - var pClone = ReworkTypeWithNamer(p.CSType); - return new CSParameter(pClone, p.Name, p.ParameterKind, p.DefaultValue); - } - - CSType ReworkTypeWithNamer(CSType ty) - { - if (ty is CSGenericReferenceType genRef) - { - var newGen = new CSGenericReferenceType(genRef.Depth, genRef.Index); - newGen.ReferenceNamer = GenericReferenceNamer; - return newGen; - } - else if (ty is CSSimpleType simple) - { - if (simple.GenericTypes == null) - return simple; - var genSubTypes = new CSType[simple.GenericTypes.Length]; - for (int i = 0; i < genSubTypes.Length; i++) - { - genSubTypes[i] = ReworkTypeWithNamer(simple.GenericTypes[i]); - } - var simpleClone = new CSSimpleType(simple.GenericTypeName, simple.IsArray, genSubTypes); - return simpleClone; - } - else - { - throw new NotImplementedException($"Unable to rework type {ty.GetType().Name} {ty.ToString()} as generic reference"); - } - } - - CSBaseExpression Marshal(BaseDeclaration typeContext, FunctionDeclaration funcDecl, CSParameter p, TypeSpec swiftType, - bool marshalProtocolAsValueType, bool isReturnVariable, TypeSpec originalType) - { - p = ReworkParameterWithNamer(p); - - var entityType = typeMapper.GetEntityTypeForTypeSpec(swiftType); - switch (entityType) - { - case EntityType.Scalar: - return MarshalScalar (p); - case EntityType.Tuple: - case EntityType.None: - // Add more types - break; - } - throw new NotImplementedException($"Uh-oh - not ready for {swiftType.ToString()}, a {entityType}."); - } - - CSBaseExpression MarshalScalar (CSParameter p) - { - return ParmName (p); - } - - static CSIdentifier ParmName (CSParameter parm) - { - return ParmName (parm.Name.Name, parm.ParameterKind); - } - - static CSIdentifier ParmName (string ident, CSParameterKind parmKind) - { - string prefix = ""; - switch (parmKind) { - case CSParameterKind.Out: - prefix = "out "; - break; - case CSParameterKind.Ref: - prefix = "ref "; - break; - default: - break; - } - return new CSIdentifier (String.Format ("{0}{1}", prefix, ident)); - } - - public static string Uniqueify(string name, IEnumerable names) - { - int thisTime = 0; - var sb = new StringBuilder(name); - while (names.Contains(sb.ToString())) - { - sb.Clear().Append(name).Append(thisTime++); - } - return sb.ToString(); - } - - TypeSpec[] FilterParams(CSParameterList parms, FunctionDeclaration wrapperFunc, bool originalThrows) - { - var results = new TypeSpec[parms.Count]; - var parameterList = wrapperFunc.ParameterLists.Last(); - for (int i = 0; i < parms.Count; i++) - { - var currType = parameterList[i].TypeSpec; - results[i] = currType; - } - return results; - } - - List absolutelyMustBeFirst; - List preMarshalCode; - CSLine functionCall; - List postMarshalCode; - CSLine returnLine; - - public bool MarshalProtocolsDirectly { get; set; } - public bool RequiredUnsafeCode { get; private set; } - public bool MarshalingConstructor { get; set; } - public Func GenericReferenceNamer { get; set; } - public CSType ProtocolInterfaceType { get; set; } - - } -} - diff --git a/src/SwiftReflector/Parser/ISwiftParser.cs b/src/SwiftReflector/Parser/ISwiftParser.cs new file mode 100644 index 000000000000..4a86efe948ba --- /dev/null +++ b/src/SwiftReflector/Parser/ISwiftParser.cs @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using SwiftReflector.SwiftXmlReflection; + +namespace SwiftReflector.Parser +{ + public interface ISwiftParser + { + public ModuleDeclaration GetModuleDeclaration(string filePath, ErrorHandling errors); + } +} \ No newline at end of file diff --git a/src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs b/src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs new file mode 100644 index 000000000000..cd5258f00e03 --- /dev/null +++ b/src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using Newtonsoft.Json; +using SwiftReflector.SwiftXmlReflection; + +namespace SwiftReflector.Parser +{ + public class ABIRootNode + { + [JsonProperty("ABIRoot")] + public RootNode ABIRoot { get; set; } + } + + public class RootNode + { + public string Kind { get; set; } + public string Name { get; set; } + public string PrintedName { get; set; } + public List Children { get; set; } + } + + public class Node + { + public string Kind { get; set; } + public string Name { get; set; } + public string MangledName { get; set; } + public string ModuleName { get; set; } + public string PrintedName { get; set; } + public List Children { get; set; } + } + + public class SwiftABIParser : ISwiftParser + { + public ModuleDeclaration GetModuleDeclaration(string filePath, ErrorHandling errors) + { + string jsonContent = File.ReadAllText(filePath); + var abiRoot = JsonConvert.DeserializeObject(jsonContent); + + var stack = new Stack(); + foreach (var child in abiRoot.ABIRoot.Children) + { + stack.Push(child); + } + + string moduleName = Path.GetFileNameWithoutExtension(filePath); + if (moduleName.EndsWith(".abi", StringComparison.OrdinalIgnoreCase)) + moduleName = moduleName.Substring(0, moduleName.Length - 4); + + ModuleDeclaration moduleDeclaration = new ModuleDeclaration(moduleName); + while (stack.Count > 0) + { + var node = stack.Pop(); + + switch (node.Kind) + { + case "Function": + var decl = CreateFunctionDecl(node); + decl.Module = moduleDeclaration; + moduleDeclaration.Declarations.Add(decl); + break; + default: + errors.Add(new NotImplementedException()); + break; + + } + + if (node.Children != null) + { + foreach (var child in node.Children) + { + stack.Push(child); + } + } + } + + return moduleDeclaration; + } + + public FunctionDeclaration CreateFunctionDecl(Node decl) + { + FunctionDeclaration functionDeclaration = new FunctionDeclaration(); + functionDeclaration.Name = decl.Name; + functionDeclaration.MangledName = decl.MangledName; + functionDeclaration.IsStatic = true; + + switch (decl.Children[0].Name) + { + case "Void": + functionDeclaration.ReturnTypeSpec = new TupleTypeSpec(); + break; + default: + functionDeclaration.ReturnTypeSpec = new NamedTypeSpec(decl.Children[0].PrintedName); + break; + } + + if (decl.Children.Count == 0) + functionDeclaration.ParameterLists.Add(new List()); + else { + var funcSignature = decl.PrintedName.Split("(")[1].Split(")")[0].Split(":", StringSplitOptions.RemoveEmptyEntries); + for (int i = 1; i < decl.Children.Count; i++) + { + var param = decl.Children[i]; + ParameterItem parameterItem = new ParameterItem(); + parameterItem.TypeSpec = new NamedTypeSpec(param.PrintedName); + if (funcSignature.Length > i - 1) + parameterItem.PublicName = funcSignature[i - 1]; + functionDeclaration.ParameterLists.Add(new List { parameterItem }); + } + } + return functionDeclaration; + } + } +} \ No newline at end of file diff --git a/src/SwiftReflector/Parser/SwiftInterfaceParser/.gitkeep b/src/SwiftReflector/Parser/SwiftInterfaceParser/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/src/SwiftReflector/PunyCode.cs b/src/SwiftReflector/PunyCode.cs deleted file mode 100644 index fa792b740d0c..000000000000 --- a/src/SwiftReflector/PunyCode.cs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SwiftReflector -{ - public class PunyCode - { - const string kEncodingStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"; - - Dictionary decodeTable; - const int kBase = 36; - const int tMin = 1; - const int tMax = 26; - const int skew = 38; - const int damp = 700; - const int initialBias = 72; - const int initialN = 0x80; - const char delimiter = '_'; - - public PunyCode() - { - decodeTable = MakeDecodeTable(kEncodingStr); - } - - public Dictionary MakeDecodeTable(string s) - { - var table = new Dictionary(); - for (int i = 0; i < s.Length; i++) - { - table[s[i]] = i; - } - return table; - } - - static int Adapt(int delta, int numPoints, bool firstTime) - { - delta = delta / (firstTime ? damp : 2); - - delta += delta / numPoints; - int k = 0; - while (delta > ((kBase - tMin) * tMax) / 2) - { - delta = delta / (kBase - tMin); - k = k + kBase; - } - k += ((kBase - tMin + 1) * delta) / (delta + skew); - return k; - } - - public string Decode(string input) - { - - int n = initialN; - int i = 0; - int bias = initialBias; - var output = new StringBuilder(); - - int pos = 0; - var delim = input.LastIndexOf('_'); - if (delim > 0) - { - output.Append(input.Substring(0, delim)); - pos = delim + 1; - } - - int outputLength = output.Length; - int inputLength = input.Length; - while (pos < inputLength) - { - int oldi = i; - int w = 1; - for (int k = kBase; ; k += kBase) - { - int digit = decodeTable[input[pos++]]; - i = i + (digit * w); - int t = Math.Max(Math.Min(k - bias, tMax), tMin); - if (digit < t) - { - break; - } - w = w * (kBase - t); - } - bias = Adapt(i - oldi, ++outputLength, (oldi == 0)); - n = n + i / outputLength; - i = i % outputLength; - if (n >= 0xd800 && n <= 0xdfff) - output.Insert(i, (char)n); - else - output.Insert(i, Char.ConvertFromUtf32(n)); - i++; - } - return output.ToString(); - } - - static int digit_index(char value) - { - if (value >= 'a' && value <= 'z') - return value - 'a'; - if (value >= 'A' && value <= 'J') - return value - 'A' + 26; - return -1; - } - - // I'm leaving this here for possible future need. - // This is a port of Apple's decode which is more or less equivalent to - // the above Decode. They both have their plusses and minuses, but I like Apple's - // lees, so it's not (currently) active. - - public string AppleDecode(string inputPunyCode) - { - var output = new StringBuilder(); - int i = 0; - var n = initialN; - var bias = initialBias; - - var lastDelimiter = inputPunyCode.LastIndexOf(delimiter); - if (lastDelimiter > 0) - { - for (int x = 0; x < lastDelimiter; x++) - { - if (inputPunyCode[x] > 0x7f) - return output.ToString(); - output.Append(inputPunyCode[x]); - } - } - - var inputPunySlice = new StringSlice(inputPunyCode.Substring(lastDelimiter + 1)); - - while (!inputPunySlice.IsAtEnd) - { - var oldi = i; - var w = 1; - for (int k = kBase; ; k += kBase) - { - if (inputPunySlice.IsAtEnd) - return output.ToString(); - var codePoint = inputPunySlice.Advance(); - - var digit = digit_index(codePoint); - if (digit < 0) - return output.ToString(); - - i = i + digit * w; - var t = k <= bias ? tMin - : (k >= bias + tMax ? tMax : k - bias); - if (digit < t) - break; - w = w * (kBase - t); - } - bias = Adapt(i - oldi, output.Length + 1, oldi == 0); - n = n + i / (output.Length + 1); - i = i % (output.Length + 1); - if (n < 0x80) - return output.ToString(); - if (n >= 0xd800 && n <= 0xdfff) - output.Insert(i, (char)n); - else - output.Insert(i, Char.ConvertFromUtf32(n)); - i++; - } - return output.ToString(); - } - - static PunyCode _puny = new PunyCode(); - public static PunyCode PunySingleton { get { return _puny; } } - } -} - diff --git a/src/SwiftReflector/StringSlice.cs b/src/SwiftReflector/StringSlice.cs deleted file mode 100644 index 38f2e0c8264a..000000000000 --- a/src/SwiftReflector/StringSlice.cs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Text; -using System.Collections.Generic; -using SwiftRuntimeLibrary; - -namespace SwiftReflector -{ - public class StringSlice - { - string slice; - - public StringSlice(string s) - { - slice = Exceptions.ThrowOnNull(s, "s"); - } - - public bool StartsWith(char c) - { - return Current == c; - } - - public bool StartsWith(string s) - { - if (s == null) - throw new ArgumentNullException(nameof(s)); - if (s == "") - return true; // I guess? - if (s.Length > Length) - return false; - for (int i = 0; i < s.Length; i++) - { - if (s[i] != this[i]) - return false; - } - return true; - } - - public char Current - { - get - { - // returns the current character in the slice - // this[0] always points to the character (see - // the indexer). - if (IsAtEnd) - throw new ArgumentException("at end"); - return this[0]; - } - } - - public bool IsAtEnd { get { return Position == slice.Length; } } - - public int Position { get; private set; } - public int Length { get { return slice.Length - Position; } } - - public string Original { get { return slice; } } - - public override string ToString() - { - if (IsAtEnd) - return ""; - return Position == 0 ? slice : slice.Substring(Current); - } - - public char Advance() - { - if (IsAtEnd) - { - throw new IndexOutOfRangeException(); - } - char c = Current; - Position++; - return c; - } - - public bool AdvanceIfEquals(char c) - { - return AdvanceIf(sl => sl.Current == c); - } - - public bool AdvanceIf(Predicate pred) - { - if (pred == null) - throw new ArgumentNullException(); - bool eq = pred(this); - if (eq) - Advance(); - return eq; - } - - public string Advance(int n) - { - if (n < 0 || n + Position > slice.Length) - throw new ArgumentOutOfRangeException(nameof(n)); - if (n == 0) - return ""; - string sub = slice.Substring(Position, n); - Position += n; - return sub; - } - - public void Rewind() - { - if (Position <= 0) - throw new InvalidOperationException("Can't rewind a slice already at the start."); - Position -= 1; - } - - public char this[int index] - { - get - { - if (index + Position >= slice.Length) - throw new IndexOutOfRangeException(); - return slice[index + Position]; - } - } - - static bool IsNameStart(char c) - { - return Char.IsDigit(c) || c == 'X'; - } - - public bool IsNameNext - { - get - { - return !IsAtEnd && IsNameStart(Current); - } - } - - public string ConsumeRemaining() - { - if (IsAtEnd) - return ""; - var result = slice.Substring(Position); - Advance(result.Length); - return result; - } - - public string Substring(int position, int length) - { - return slice.Substring(position, length); - } - - public string ExtractSwiftString(out bool isPunyCode) - { - if (!IsNameNext) - { - isPunyCode = false; - return null; - } - - int count = 0; - - if ((isPunyCode = Current == 'X')) - Advance(); - - while (!IsAtEnd && Char.IsDigit(Current)) - { - count = count * 10 + Advance() - '0'; - } - return Advance(count); - } - - public SwiftName ExtractSwiftName() - { - bool isPunyCode = false; - string s = ExtractSwiftString(out isPunyCode); - if (s == null) - return null; - return new SwiftName(s, isPunyCode); - } - - public SwiftName ExtractSwiftNameMaybeOperator(out OperatorType oper) - { - oper = OperatorType.None; - if (StartsWith('o')) - { - Advance(); - char c = Advance(); - switch (c) - { - case 'p': - oper = OperatorType.Prefix; - break; - case 'P': - oper = OperatorType.Postfix; - break; - case 'i': - oper = OperatorType.Infix; - break; - default: - break; - } - } - bool isPunyCode = false; - string s = ExtractSwiftString(out isPunyCode); - if (s == null) - return null; - if (oper != OperatorType.None) - { - s = DecodeOperatorName(s); - } - return new SwiftName(s, isPunyCode); - } - - static string _opChars = "& @/= > <*!|+?%-~ ^ ."; - static string DecodeOperatorName(string s) - { - var sb = new StringBuilder(); - foreach (char c in s) - { - if (c > 32767) - { - sb.Append(c); - continue; - } - if (c < 'a' || c > 'z') - throw new ArgumentOutOfRangeException(nameof(s), String.Format("operator name '{0}' contains illegal characters", s)); - char o = _opChars[c - 'a']; - sb.Append(o); - } - return sb.ToString(); - } - - - } -} - diff --git a/src/SwiftReflector/SwiftClassName.cs b/src/SwiftReflector/SwiftClassName.cs index e1bbf672dec2..8f5ef62269ab 100644 --- a/src/SwiftReflector/SwiftClassName.cs +++ b/src/SwiftReflector/SwiftClassName.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using SwiftReflector.Demangling; using SwiftRuntimeLibrary; namespace SwiftReflector @@ -21,26 +20,6 @@ public SwiftClassName(SwiftName module, IList nesting, IList nestingNames = parts.Skip(1).Select(name => new SwiftName(name, false)).ToList(); - List actualNesting = nesting.Select(c => Decomposer.ToMaybeMemberNesting(c, true).Value).ToList(); - return new SwiftClassName(module, actualNesting, nestingNames, oper); - } - - public static SwiftClassName FromFullyQualifiedName(string fullyQualifiedName, OperatorType oper, string nesting) - { - return FromFullyQualifiedName(fullyQualifiedName, oper, nesting.ToArray()); - } - public SwiftName Module { get; private set; } public IList Nesting { get; private set; } public IList NestingNames { get; private set; } diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs deleted file mode 100644 index 07d5302b6611..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceBaseListener.cs +++ /dev/null @@ -1,2131 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// ANTLR Version: 4.9.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// Generated from SwiftInterface.g4 by ANTLR 4.9.1 - -// Unreachable code detected -#pragma warning disable 0162 -// The variable '...' is assigned but its value is never used -#pragma warning disable 0219 -// Missing XML comment for publicly visible type or member '...' -#pragma warning disable 1591 -// Ambiguous reference in cref attribute -#pragma warning disable 419 - - -using Antlr4.Runtime.Misc; -using IErrorNode = Antlr4.Runtime.Tree.IErrorNode; -using ITerminalNode = Antlr4.Runtime.Tree.ITerminalNode; -using IToken = Antlr4.Runtime.IToken; -using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; - -/// -/// This class provides an empty implementation of , -/// which can be extended to create a listener which only needs to handle a subset -/// of the available methods. -/// -[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] -[System.Diagnostics.DebuggerNonUserCode] -// [System.CLSCompliant(false)] -public partial class SwiftInterfaceBaseListener : ISwiftInterfaceListener { - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterStatement([NotNull] SwiftInterfaceParser.StatementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitStatement([NotNull] SwiftInterfaceParser.StatementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterComment([NotNull] SwiftInterfaceParser.CommentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitComment([NotNull] SwiftInterfaceParser.CommentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterParameter([NotNull] SwiftInterfaceParser.ParameterContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitParameter([NotNull] SwiftInterfaceParser.ParameterContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAttribute([NotNull] SwiftInterfaceParser.AttributeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAttribute([NotNull] SwiftInterfaceParser.AttributeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAttributes([NotNull] SwiftInterfaceParser.AttributesContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAttributes([NotNull] SwiftInterfaceParser.AttributesContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterPattern([NotNull] SwiftInterfaceParser.PatternContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitPattern([NotNull] SwiftInterfaceParser.PatternContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context) { } - /// - /// Enter a parse tree produced by the dict_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context) { } - /// - /// Exit a parse tree produced by the dict_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context) { } - /// - /// Enter a parse tree produced by the any_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context) { } - /// - /// Exit a parse tree produced by the any_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context) { } - /// - /// Enter a parse tree produced by the identifier_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context) { } - /// - /// Exit a parse tree produced by the identifier_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context) { } - /// - /// Enter a parse tree produced by the func_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context) { } - /// - /// Exit a parse tree produced by the func_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context) { } - /// - /// Enter a parse tree produced by the arr_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context) { } - /// - /// Exit a parse tree produced by the arr_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context) { } - /// - /// Enter a parse tree produced by the meta_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context) { } - /// - /// Exit a parse tree produced by the meta_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context) { } - /// - /// Enter a parse tree produced by the boxed_protocol_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context) { } - /// - /// Exit a parse tree produced by the boxed_protocol_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context) { } - /// - /// Enter a parse tree produced by the optional_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context) { } - /// - /// Exit a parse tree produced by the optional_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context) { } - /// - /// Enter a parse tree produced by the self_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context) { } - /// - /// Exit a parse tree produced by the self_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context) { } - /// - /// Enter a parse tree produced by the unwrapped_optional_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context) { } - /// - /// Exit a parse tree produced by the unwrapped_optional_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context) { } - /// - /// Enter a parse tree produced by the proto_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context) { } - /// - /// Exit a parse tree produced by the proto_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context) { } - /// - /// Enter a parse tree produced by the tup_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context) { } - /// - /// Exit a parse tree produced by the tup_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context) { } - /// - /// Enter a parse tree produced by the self_long - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context) { } - /// - /// Exit a parse tree produced by the self_long - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context) { } - /// - /// Enter a parse tree produced by the proto_comp_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context) { } - /// - /// Exit a parse tree produced by the proto_comp_type - /// labeled alternative in . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterType_name([NotNull] SwiftInterfaceParser.Type_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitType_name([NotNull] SwiftInterfaceParser.Type_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterLiteral([NotNull] SwiftInterfaceParser.LiteralContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitLiteral([NotNull] SwiftInterfaceParser.LiteralContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterString_literal([NotNull] SwiftInterfaceParser.String_literalContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitString_literal([NotNull] SwiftInterfaceParser.String_literalContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRequirement([NotNull] SwiftInterfaceParser.RequirementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRequirement([NotNull] SwiftInterfaceParser.RequirementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOperator([NotNull] SwiftInterfaceParser.OperatorContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOperator([NotNull] SwiftInterfaceParser.OperatorContext context) { } - /// - /// Enter a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void EnterOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context) { } - /// - /// Exit a parse tree produced by . - /// The default implementation does nothing. - /// - /// The parse tree. - public virtual void ExitOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context) { } - - /// - /// The default implementation does nothing. - public virtual void EnterEveryRule([NotNull] ParserRuleContext context) { } - /// - /// The default implementation does nothing. - public virtual void ExitEveryRule([NotNull] ParserRuleContext context) { } - /// - /// The default implementation does nothing. - public virtual void VisitTerminal([NotNull] ITerminalNode node) { } - /// - /// The default implementation does nothing. - public virtual void VisitErrorNode([NotNull] IErrorNode node) { } -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs deleted file mode 100644 index 46601ea02f16..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceLexer.cs +++ /dev/null @@ -1,1395 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// ANTLR Version: 4.9.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// Generated from SwiftInterface.g4 by ANTLR 4.9.1 - -// Unreachable code detected -#pragma warning disable 0162 -// The variable '...' is assigned but its value is never used -#pragma warning disable 0219 -// Missing XML comment for publicly visible type or member '...' -#pragma warning disable 1591 -// Ambiguous reference in cref attribute -#pragma warning disable 419 - -using System; -using System.IO; -using System.Text; -using Antlr4.Runtime; -using Antlr4.Runtime.Atn; -using Antlr4.Runtime.Misc; -using DFA = Antlr4.Runtime.Dfa.DFA; - -[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] -// [System.CLSCompliant(false)] -public partial class SwiftInterfaceLexer : Lexer { - protected static DFA[] decisionToDFA; - protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); - public const int - T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, - T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, - T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24, - T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31, - T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, T__37=38, - T__38=39, T__39=40, T__40=41, T__41=42, T__42=43, T__43=44, T__44=45, - T__45=46, T__46=47, T__47=48, T__48=49, T__49=50, T__50=51, T__51=52, - T__52=53, T__53=54, T__54=55, T__55=56, T__56=57, T__57=58, T__58=59, - T__59=60, T__60=61, T__61=62, T__62=63, T__63=64, T__64=65, T__65=66, - T__66=67, T__67=68, T__68=69, T__69=70, T__70=71, T__71=72, T__72=73, - T__73=74, T__74=75, T__75=76, T__76=77, T__77=78, T__78=79, T__79=80, - T__80=81, T__81=82, T__82=83, T__83=84, T__84=85, T__85=86, T__86=87, - T__87=88, T__88=89, T__89=90, T__90=91, T__91=92, T__92=93, T__93=94, - T__94=95, T__95=96, T__96=97, T__97=98, T__98=99, T__99=100, T__100=101, - T__101=102, T__102=103, T__103=104, T__104=105, T__105=106, T__106=107, - T__107=108, T__108=109, T__109=110, T__110=111, T__111=112, Binary_literal=113, - Octal_literal=114, Decimal_literal=115, Pure_decimal_digits=116, Hexadecimal_literal=117, - Static_string_literal=118, Identifier=119, Implicit_parameter_name=120, - WS=121, OpPlus=122, OpMinus=123, OpAssign=124, OpAmp=125, OpQuestion=126, - OpLess=127, OpBang=128, OpDot=129, OpComma=130, OpTilde=131, OpColon=132, - OpSemi=133, OpAt=134, OpPound=135, OpBackTick=136, OpUnder=137, OpLParen=138, - OpRParen=139, OpLBracket=140, OpRBracket=141, OpLBrace=142, OpRBrace=143, - Decimal_digits=144, Operator=145, DotOperatorHead=146, DotOperatorFollow=147, - OpEqEq=148, Comment_line=149; - public static string[] channelNames = { - "DEFAULT_TOKEN_CHANNEL", "HIDDEN" - }; - - public static string[] modeNames = { - "DEFAULT_MODE" - }; - - public static readonly string[] ruleNames = { - "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", - "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16", - "T__17", "T__18", "T__19", "T__20", "T__21", "T__22", "T__23", "T__24", - "T__25", "T__26", "T__27", "T__28", "T__29", "T__30", "T__31", "T__32", - "T__33", "T__34", "T__35", "T__36", "T__37", "T__38", "T__39", "T__40", - "T__41", "T__42", "T__43", "T__44", "T__45", "T__46", "T__47", "T__48", - "T__49", "T__50", "T__51", "T__52", "T__53", "T__54", "T__55", "T__56", - "T__57", "T__58", "T__59", "T__60", "T__61", "T__62", "T__63", "T__64", - "T__65", "T__66", "T__67", "T__68", "T__69", "T__70", "T__71", "T__72", - "T__73", "T__74", "T__75", "T__76", "T__77", "T__78", "T__79", "T__80", - "T__81", "T__82", "T__83", "T__84", "T__85", "T__86", "T__87", "T__88", - "T__89", "T__90", "T__91", "T__92", "T__93", "T__94", "T__95", "T__96", - "T__97", "T__98", "T__99", "T__100", "T__101", "T__102", "T__103", "T__104", - "T__105", "T__106", "T__107", "T__108", "T__109", "T__110", "T__111", - "Binary_literal", "Binary_digit", "Binary_literal_character", "Binary_literal_characters", - "Octal_literal", "Octal_digit", "Octal_literal_character", "Octal_literal_characters", - "Decimal_literal", "Pure_decimal_digits", "Hexadecimal_literal", "Hexadecimal_digit", - "Hexadecimal_literal_character", "Hexadecimal_literal_characters", "Static_string_literal", - "Quoted_text", "Quoted_text_item", "Escaped_character", "Identifier", - "Identifier_head", "Identifier_character", "Identifier_characters", "Implicit_parameter_name", - "WS", "OpPlus", "OpMinus", "OpAssign", "OpAmp", "OpQuestion", "OpLess", - "OpBang", "OpDot", "OpComma", "OpTilde", "OpColon", "OpSemi", "OpAt", - "OpPound", "OpBackTick", "OpUnder", "OpLParen", "OpRParen", "OpLBracket", - "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", "Operator", "OperatorHeadGreater", - "OperatorHead", "OperatorCharacters", "OperatorFollowNoGreater", "OperatorFollow", - "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line" - }; - - - public SwiftInterfaceLexer(ICharStream input) - : this(input, Console.Out, Console.Error) { } - - public SwiftInterfaceLexer(ICharStream input, TextWriter output, TextWriter errorOutput) - : base(input, output, errorOutput) - { - Interpreter = new LexerATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); - } - - private static readonly string[] _LiteralNames = { - null, "'import'", "'typealias'", "'struct'", "'class'", "'enum'", "'protocol'", - "'var'", "'func'", "'let'", "'get'", "'set'", "'indirect'", "'case'", - "'final'", "'prefix'", "'operator'", "'postfix'", "'infix'", "'precedencegroup'", - "'higherThan'", "'lowerThan'", "'assignment'", "'associativity'", "'left'", - "'right'", "'none'", "'extension'", "'subscript'", "'associatedtype'", - "'async'", "'throws'", "'rethrows'", "'init'", "'deinit'", "'convenience'", - "'dynamic'", "'lazy'", "'optional'", "'override'", "'required'", "'static'", - "'unowned'", "'safe'", "'unsafe'", "'weak'", "'private'", "'fileprivate'", - "'internal'", "'public'", "'open'", "'mutating'", "'nonmutating'", "'is'", - "'as'", "'Type'", "'Protocol'", "'Any'", "'Self'", "'any'", "'inout'", - "'nil'", "'true'", "'false'", "'where'", "'>'", "'->'", "'...'", "'alpha'", - "'arch'", "'arm'", "'arm64'", "'blue'", "'didSet'", "'file'", "'green'", - "'i386'", "'iOS'", "'iOSApplicationExtension'", "'line'", "'macOS'", "'macOSApplicationExtension'", - "'of'", "'os'", "'precedence'", "'red'", "'resourceName'", "'swift'", - "'tvOS'", "'type'", "'watchOS'", "'willSet'", "'x86_64'", "'break'", "'catch'", - "'continue'", "'default'", "'defer'", "'do'", "'else'", "'fallthrough'", - "'for'", "'guard'", "'if'", "'in'", "'repeat'", "'return'", "'self'", - "'super'", "'switch'", "'throw'", "'try'", "'while'", null, null, null, - null, null, null, null, null, null, "'+'", "'-'", "'='", "'&'", "'?'", - "'<'", "'!'", "'.'", "','", "'~'", "':'", "';'", "'@'", "'#'", "'`'", - "'_'", "'('", "')'", "'['", "']'", "'{'", "'}'", null, null, null, null, - "'=='" - }; - private static readonly string[] _SymbolicNames = { - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, "Binary_literal", "Octal_literal", "Decimal_literal", - "Pure_decimal_digits", "Hexadecimal_literal", "Static_string_literal", - "Identifier", "Implicit_parameter_name", "WS", "OpPlus", "OpMinus", "OpAssign", - "OpAmp", "OpQuestion", "OpLess", "OpBang", "OpDot", "OpComma", "OpTilde", - "OpColon", "OpSemi", "OpAt", "OpPound", "OpBackTick", "OpUnder", "OpLParen", - "OpRParen", "OpLBracket", "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", - "Operator", "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line" - }; - public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); - - [NotNull] - public override IVocabulary Vocabulary - { - get - { - return DefaultVocabulary; - } - } - - public override string GrammarFileName { get { return "SwiftInterface.g4"; } } - - public override string[] RuleNames { get { return ruleNames; } } - - public override string[] ChannelNames { get { return channelNames; } } - - public override string[] ModeNames { get { return modeNames; } } - - public override string SerializedAtn { get { return new string(_serializedATN); } } - - static SwiftInterfaceLexer() { - decisionToDFA = new DFA[_ATN.NumberOfDecisions]; - for (int i = 0; i < _ATN.NumberOfDecisions; i++) { - decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); - } - } - private static char[] _serializedATN = { - '\x3', '\x608B', '\xA72A', '\x8133', '\xB9ED', '\x417C', '\x3BE7', '\x7786', - '\x5964', '\x2', '\x97', '\x565', '\b', '\x1', '\x4', '\x2', '\t', '\x2', - '\x4', '\x3', '\t', '\x3', '\x4', '\x4', '\t', '\x4', '\x4', '\x5', '\t', - '\x5', '\x4', '\x6', '\t', '\x6', '\x4', '\a', '\t', '\a', '\x4', '\b', - '\t', '\b', '\x4', '\t', '\t', '\t', '\x4', '\n', '\t', '\n', '\x4', '\v', - '\t', '\v', '\x4', '\f', '\t', '\f', '\x4', '\r', '\t', '\r', '\x4', '\xE', - '\t', '\xE', '\x4', '\xF', '\t', '\xF', '\x4', '\x10', '\t', '\x10', '\x4', - '\x11', '\t', '\x11', '\x4', '\x12', '\t', '\x12', '\x4', '\x13', '\t', - '\x13', '\x4', '\x14', '\t', '\x14', '\x4', '\x15', '\t', '\x15', '\x4', - '\x16', '\t', '\x16', '\x4', '\x17', '\t', '\x17', '\x4', '\x18', '\t', - '\x18', '\x4', '\x19', '\t', '\x19', '\x4', '\x1A', '\t', '\x1A', '\x4', - '\x1B', '\t', '\x1B', '\x4', '\x1C', '\t', '\x1C', '\x4', '\x1D', '\t', - '\x1D', '\x4', '\x1E', '\t', '\x1E', '\x4', '\x1F', '\t', '\x1F', '\x4', - ' ', '\t', ' ', '\x4', '!', '\t', '!', '\x4', '\"', '\t', '\"', '\x4', - '#', '\t', '#', '\x4', '$', '\t', '$', '\x4', '%', '\t', '%', '\x4', '&', - '\t', '&', '\x4', '\'', '\t', '\'', '\x4', '(', '\t', '(', '\x4', ')', - '\t', ')', '\x4', '*', '\t', '*', '\x4', '+', '\t', '+', '\x4', ',', '\t', - ',', '\x4', '-', '\t', '-', '\x4', '.', '\t', '.', '\x4', '/', '\t', '/', - '\x4', '\x30', '\t', '\x30', '\x4', '\x31', '\t', '\x31', '\x4', '\x32', - '\t', '\x32', '\x4', '\x33', '\t', '\x33', '\x4', '\x34', '\t', '\x34', - '\x4', '\x35', '\t', '\x35', '\x4', '\x36', '\t', '\x36', '\x4', '\x37', - '\t', '\x37', '\x4', '\x38', '\t', '\x38', '\x4', '\x39', '\t', '\x39', - '\x4', ':', '\t', ':', '\x4', ';', '\t', ';', '\x4', '<', '\t', '<', '\x4', - '=', '\t', '=', '\x4', '>', '\t', '>', '\x4', '?', '\t', '?', '\x4', '@', - '\t', '@', '\x4', '\x41', '\t', '\x41', '\x4', '\x42', '\t', '\x42', '\x4', - '\x43', '\t', '\x43', '\x4', '\x44', '\t', '\x44', '\x4', '\x45', '\t', - '\x45', '\x4', '\x46', '\t', '\x46', '\x4', 'G', '\t', 'G', '\x4', 'H', - '\t', 'H', '\x4', 'I', '\t', 'I', '\x4', 'J', '\t', 'J', '\x4', 'K', '\t', - 'K', '\x4', 'L', '\t', 'L', '\x4', 'M', '\t', 'M', '\x4', 'N', '\t', 'N', - '\x4', 'O', '\t', 'O', '\x4', 'P', '\t', 'P', '\x4', 'Q', '\t', 'Q', '\x4', - 'R', '\t', 'R', '\x4', 'S', '\t', 'S', '\x4', 'T', '\t', 'T', '\x4', 'U', - '\t', 'U', '\x4', 'V', '\t', 'V', '\x4', 'W', '\t', 'W', '\x4', 'X', '\t', - 'X', '\x4', 'Y', '\t', 'Y', '\x4', 'Z', '\t', 'Z', '\x4', '[', '\t', '[', - '\x4', '\\', '\t', '\\', '\x4', ']', '\t', ']', '\x4', '^', '\t', '^', - '\x4', '_', '\t', '_', '\x4', '`', '\t', '`', '\x4', '\x61', '\t', '\x61', - '\x4', '\x62', '\t', '\x62', '\x4', '\x63', '\t', '\x63', '\x4', '\x64', - '\t', '\x64', '\x4', '\x65', '\t', '\x65', '\x4', '\x66', '\t', '\x66', - '\x4', 'g', '\t', 'g', '\x4', 'h', '\t', 'h', '\x4', 'i', '\t', 'i', '\x4', - 'j', '\t', 'j', '\x4', 'k', '\t', 'k', '\x4', 'l', '\t', 'l', '\x4', 'm', - '\t', 'm', '\x4', 'n', '\t', 'n', '\x4', 'o', '\t', 'o', '\x4', 'p', '\t', - 'p', '\x4', 'q', '\t', 'q', '\x4', 'r', '\t', 'r', '\x4', 's', '\t', 's', - '\x4', 't', '\t', 't', '\x4', 'u', '\t', 'u', '\x4', 'v', '\t', 'v', '\x4', - 'w', '\t', 'w', '\x4', 'x', '\t', 'x', '\x4', 'y', '\t', 'y', '\x4', 'z', - '\t', 'z', '\x4', '{', '\t', '{', '\x4', '|', '\t', '|', '\x4', '}', '\t', - '}', '\x4', '~', '\t', '~', '\x4', '\x7F', '\t', '\x7F', '\x4', '\x80', - '\t', '\x80', '\x4', '\x81', '\t', '\x81', '\x4', '\x82', '\t', '\x82', - '\x4', '\x83', '\t', '\x83', '\x4', '\x84', '\t', '\x84', '\x4', '\x85', - '\t', '\x85', '\x4', '\x86', '\t', '\x86', '\x4', '\x87', '\t', '\x87', - '\x4', '\x88', '\t', '\x88', '\x4', '\x89', '\t', '\x89', '\x4', '\x8A', - '\t', '\x8A', '\x4', '\x8B', '\t', '\x8B', '\x4', '\x8C', '\t', '\x8C', - '\x4', '\x8D', '\t', '\x8D', '\x4', '\x8E', '\t', '\x8E', '\x4', '\x8F', - '\t', '\x8F', '\x4', '\x90', '\t', '\x90', '\x4', '\x91', '\t', '\x91', - '\x4', '\x92', '\t', '\x92', '\x4', '\x93', '\t', '\x93', '\x4', '\x94', - '\t', '\x94', '\x4', '\x95', '\t', '\x95', '\x4', '\x96', '\t', '\x96', - '\x4', '\x97', '\t', '\x97', '\x4', '\x98', '\t', '\x98', '\x4', '\x99', - '\t', '\x99', '\x4', '\x9A', '\t', '\x9A', '\x4', '\x9B', '\t', '\x9B', - '\x4', '\x9C', '\t', '\x9C', '\x4', '\x9D', '\t', '\x9D', '\x4', '\x9E', - '\t', '\x9E', '\x4', '\x9F', '\t', '\x9F', '\x4', '\xA0', '\t', '\xA0', - '\x4', '\xA1', '\t', '\xA1', '\x4', '\xA2', '\t', '\xA2', '\x4', '\xA3', - '\t', '\xA3', '\x4', '\xA4', '\t', '\xA4', '\x4', '\xA5', '\t', '\xA5', - '\x4', '\xA6', '\t', '\xA6', '\x4', '\xA7', '\t', '\xA7', '\x4', '\xA8', - '\t', '\xA8', '\x4', '\xA9', '\t', '\xA9', '\x4', '\xAA', '\t', '\xAA', - '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', - '\x3', '\x2', '\x3', '\x2', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', - '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', - '\x3', '\x3', '\x3', '\x3', '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', - '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', '\x3', '\x4', '\x3', '\x5', - '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', - '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', - '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', - '\a', '\x3', '\a', '\x3', '\a', '\x3', '\a', '\x3', '\b', '\x3', '\b', - '\x3', '\b', '\x3', '\b', '\x3', '\t', '\x3', '\t', '\x3', '\t', '\x3', - '\t', '\x3', '\t', '\x3', '\n', '\x3', '\n', '\x3', '\n', '\x3', '\n', - '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', '\f', '\x3', - '\f', '\x3', '\f', '\x3', '\f', '\x3', '\r', '\x3', '\r', '\x3', '\r', - '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', '\r', '\x3', - '\r', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', '\x3', '\xE', - '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', '\x3', '\xF', - '\x3', '\xF', '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', - '\x3', '\x10', '\x3', '\x10', '\x3', '\x10', '\x3', '\x11', '\x3', '\x11', - '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', - '\x3', '\x11', '\x3', '\x11', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', - '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', '\x3', '\x12', - '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', - '\x3', '\x13', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', - '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', - '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', '\x3', '\x14', - '\x3', '\x14', '\x3', '\x14', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', - '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', - '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x16', '\x3', '\x16', - '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', - '\x3', '\x16', '\x3', '\x16', '\x3', '\x16', '\x3', '\x17', '\x3', '\x17', - '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', - '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x18', - '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', - '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', - '\x3', '\x18', '\x3', '\x18', '\x3', '\x18', '\x3', '\x19', '\x3', '\x19', - '\x3', '\x19', '\x3', '\x19', '\x3', '\x19', '\x3', '\x1A', '\x3', '\x1A', - '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1A', '\x3', '\x1B', - '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1B', '\x3', '\x1C', - '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', - '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1D', - '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', - '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1E', - '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', - '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', - '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1E', '\x3', '\x1F', - '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', '\x3', '\x1F', - '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', '\x3', ' ', - '\x3', ' ', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', - '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '!', '\x3', '\"', '\x3', '\"', - '\x3', '\"', '\x3', '\"', '\x3', '\"', '\x3', '#', '\x3', '#', '\x3', - '#', '\x3', '#', '\x3', '#', '\x3', '#', '\x3', '#', '\x3', '$', '\x3', - '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', - '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', '%', '\x3', - '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', - '%', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', '&', '\x3', - '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '\'', - '\x3', '\'', '\x3', '\'', '\x3', '\'', '\x3', '(', '\x3', '(', '\x3', - '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', '(', '\x3', - '(', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', - ')', '\x3', ')', '\x3', ')', '\x3', ')', '\x3', '*', '\x3', '*', '\x3', - '*', '\x3', '*', '\x3', '*', '\x3', '*', '\x3', '*', '\x3', '+', '\x3', - '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', '+', '\x3', - '+', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', ',', '\x3', - '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x3', - '-', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', '.', '\x3', - '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', '/', '\x3', - '/', '\x3', '/', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', - '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', - '\x3', '\x30', '\x3', '\x30', '\x3', '\x30', '\x3', '\x31', '\x3', '\x31', - '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', '\x3', '\x31', - '\x3', '\x31', '\x3', '\x31', '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', - '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x33', - '\x3', '\x33', '\x3', '\x33', '\x3', '\x33', '\x3', '\x33', '\x3', '\x34', - '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', - '\x3', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', '\x35', '\x3', '\x35', - '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', - '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', '\x3', '\x35', - '\x3', '\x36', '\x3', '\x36', '\x3', '\x36', '\x3', '\x37', '\x3', '\x37', - '\x3', '\x37', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', - '\x3', '\x38', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', - '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', - '\x3', ':', '\x3', ':', '\x3', ':', '\x3', ':', '\x3', ';', '\x3', ';', - '\x3', ';', '\x3', ';', '\x3', ';', '\x3', '<', '\x3', '<', '\x3', '<', - '\x3', '<', '\x3', '=', '\x3', '=', '\x3', '=', '\x3', '=', '\x3', '=', - '\x3', '=', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '?', - '\x3', '?', '\x3', '?', '\x3', '?', '\x3', '?', '\x3', '@', '\x3', '@', - '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '\x41', '\x3', - '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', '\x41', '\x3', - '\x42', '\x3', '\x42', '\x3', '\x43', '\x3', '\x43', '\x3', '\x43', '\x3', - '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x45', '\x3', - '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', '\x45', '\x3', - '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', '\x46', '\x3', - 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'H', '\x3', 'H', '\x3', - 'H', '\x3', 'H', '\x3', 'H', '\x3', 'H', '\x3', 'I', '\x3', 'I', '\x3', - 'I', '\x3', 'I', '\x3', 'I', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x3', - 'J', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x3', 'K', '\x3', 'K', '\x3', - 'K', '\x3', 'K', '\x3', 'K', '\x3', 'L', '\x3', 'L', '\x3', 'L', '\x3', - 'L', '\x3', 'L', '\x3', 'L', '\x3', 'M', '\x3', 'M', '\x3', 'M', '\x3', - 'M', '\x3', 'M', '\x3', 'N', '\x3', 'N', '\x3', 'N', '\x3', 'N', '\x3', - 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', - 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', - 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', - 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', 'O', '\x3', - 'P', '\x3', 'P', '\x3', 'P', '\x3', 'P', '\x3', 'P', '\x3', 'Q', '\x3', - 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'Q', '\x3', 'R', '\x3', - 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', - 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', - 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', - 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', 'R', '\x3', - 'R', '\x3', 'S', '\x3', 'S', '\x3', 'S', '\x3', 'T', '\x3', 'T', '\x3', - 'T', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', - 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', 'U', '\x3', - 'V', '\x3', 'V', '\x3', 'V', '\x3', 'V', '\x3', 'W', '\x3', 'W', '\x3', - 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', - 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'X', '\x3', - 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'Y', '\x3', - 'Y', '\x3', 'Y', '\x3', 'Y', '\x3', 'Y', '\x3', 'Z', '\x3', 'Z', '\x3', - 'Z', '\x3', 'Z', '\x3', 'Z', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', - '[', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', '[', '\x3', '\\', '\x3', - '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', '\x3', '\\', - '\x3', '\\', '\x3', ']', '\x3', ']', '\x3', ']', '\x3', ']', '\x3', ']', - '\x3', ']', '\x3', ']', '\x3', '^', '\x3', '^', '\x3', '^', '\x3', '^', - '\x3', '^', '\x3', '^', '\x3', '_', '\x3', '_', '\x3', '_', '\x3', '_', - '\x3', '_', '\x3', '_', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', - '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '\x61', - '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', '\x3', '\x61', - '\x3', '\x61', '\x3', '\x61', '\x3', '\x62', '\x3', '\x62', '\x3', '\x62', - '\x3', '\x62', '\x3', '\x62', '\x3', '\x62', '\x3', '\x63', '\x3', '\x63', - '\x3', '\x63', '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', - '\x3', '\x64', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', - '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', - '\x3', '\x65', '\x3', '\x65', '\x3', '\x65', '\x3', '\x66', '\x3', '\x66', - '\x3', '\x66', '\x3', '\x66', '\x3', 'g', '\x3', 'g', '\x3', 'g', '\x3', - 'g', '\x3', 'g', '\x3', 'g', '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', - 'i', '\x3', 'i', '\x3', 'i', '\x3', 'j', '\x3', 'j', '\x3', 'j', '\x3', - 'j', '\x3', 'j', '\x3', 'j', '\x3', 'j', '\x3', 'k', '\x3', 'k', '\x3', - 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'l', '\x3', - 'l', '\x3', 'l', '\x3', 'l', '\x3', 'l', '\x3', 'm', '\x3', 'm', '\x3', - 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'n', '\x3', 'n', '\x3', - 'n', '\x3', 'n', '\x3', 'n', '\x3', 'n', '\x3', 'n', '\x3', 'o', '\x3', - 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'p', '\x3', - 'p', '\x3', 'p', '\x3', 'p', '\x3', 'q', '\x3', 'q', '\x3', 'q', '\x3', - 'q', '\x3', 'q', '\x3', 'q', '\x3', 'r', '\x3', 'r', '\x3', 'r', '\x3', - 'r', '\x3', 'r', '\x5', 'r', '\x46A', '\n', 'r', '\x3', 's', '\x3', 's', - '\x3', 't', '\x3', 't', '\x5', 't', '\x470', '\n', 't', '\x3', 'u', '\x6', - 'u', '\x473', '\n', 'u', '\r', 'u', '\xE', 'u', '\x474', '\x3', 'v', '\x3', - 'v', '\x3', 'v', '\x3', 'v', '\x3', 'v', '\x5', 'v', '\x47C', '\n', 'v', - '\x3', 'w', '\x3', 'w', '\x3', 'x', '\x3', 'x', '\x5', 'x', '\x482', '\n', - 'x', '\x3', 'y', '\x6', 'y', '\x485', '\n', 'y', '\r', 'y', '\xE', 'y', - '\x486', '\x3', 'z', '\x3', 'z', '\a', 'z', '\x48B', '\n', 'z', '\f', - 'z', '\xE', 'z', '\x48E', '\v', 'z', '\x3', '{', '\x6', '{', '\x491', - '\n', '{', '\r', '{', '\xE', '{', '\x492', '\x3', '|', '\x3', '|', '\x3', - '|', '\x3', '|', '\x3', '|', '\x5', '|', '\x49A', '\n', '|', '\x3', '}', - '\x3', '}', '\x3', '~', '\x3', '~', '\x5', '~', '\x4A0', '\n', '~', '\x3', - '\x7F', '\x6', '\x7F', '\x4A3', '\n', '\x7F', '\r', '\x7F', '\xE', '\x7F', - '\x4A4', '\x3', '\x80', '\x3', '\x80', '\x5', '\x80', '\x4A9', '\n', '\x80', - '\x3', '\x80', '\x3', '\x80', '\x3', '\x81', '\x6', '\x81', '\x4AE', '\n', - '\x81', '\r', '\x81', '\xE', '\x81', '\x4AF', '\x3', '\x82', '\x3', '\x82', - '\x5', '\x82', '\x4B4', '\n', '\x82', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', - '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', '\x5', - '\x83', '\x4D6', '\n', '\x83', '\x3', '\x84', '\x3', '\x84', '\x5', '\x84', - '\x4DA', '\n', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', '\x5', - '\x84', '\x4DF', '\n', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', - '\x5', '\x84', '\x4E4', '\n', '\x84', '\x3', '\x85', '\x5', '\x85', '\x4E7', - '\n', '\x85', '\x3', '\x86', '\x3', '\x86', '\x5', '\x86', '\x4EB', '\n', - '\x86', '\x3', '\x87', '\x6', '\x87', '\x4EE', '\n', '\x87', '\r', '\x87', - '\xE', '\x87', '\x4EF', '\x3', '\x88', '\x3', '\x88', '\x3', '\x88', '\x3', - '\x89', '\x6', '\x89', '\x4F6', '\n', '\x89', '\r', '\x89', '\xE', '\x89', - '\x4F7', '\x3', '\x89', '\x3', '\x89', '\x3', '\x8A', '\x3', '\x8A', '\x3', - '\x8B', '\x3', '\x8B', '\x3', '\x8C', '\x3', '\x8C', '\x3', '\x8D', '\x3', - '\x8D', '\x3', '\x8E', '\x3', '\x8E', '\x3', '\x8F', '\x3', '\x8F', '\x3', - '\x90', '\x3', '\x90', '\x3', '\x91', '\x3', '\x91', '\x3', '\x92', '\x3', - '\x92', '\x3', '\x93', '\x3', '\x93', '\x3', '\x94', '\x3', '\x94', '\x3', - '\x95', '\x3', '\x95', '\x3', '\x96', '\x3', '\x96', '\x3', '\x97', '\x3', - '\x97', '\x3', '\x98', '\x3', '\x98', '\x3', '\x99', '\x3', '\x99', '\x3', - '\x9A', '\x3', '\x9A', '\x3', '\x9B', '\x3', '\x9B', '\x3', '\x9C', '\x3', - '\x9C', '\x3', '\x9D', '\x3', '\x9D', '\x3', '\x9E', '\x3', '\x9E', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\xA0', '\x6', '\xA0', '\x529', '\n', '\xA0', - '\r', '\xA0', '\xE', '\xA0', '\x52A', '\x3', '\xA1', '\x3', '\xA1', '\x5', - '\xA1', '\x52F', '\n', '\xA1', '\x3', '\xA1', '\x3', '\xA1', '\x3', '\xA1', - '\x3', '\xA1', '\x3', '\xA1', '\x3', '\xA1', '\x6', '\xA1', '\x537', '\n', - '\xA1', '\r', '\xA1', '\xE', '\xA1', '\x538', '\x3', '\xA1', '\x3', '\xA1', - '\x6', '\xA1', '\x53D', '\n', '\xA1', '\r', '\xA1', '\xE', '\xA1', '\x53E', - '\x5', '\xA1', '\x541', '\n', '\xA1', '\x3', '\xA2', '\x5', '\xA2', '\x544', - '\n', '\xA2', '\x3', '\xA3', '\x5', '\xA3', '\x547', '\n', '\xA3', '\x3', - '\xA4', '\x6', '\xA4', '\x54A', '\n', '\xA4', '\r', '\xA4', '\xE', '\xA4', - '\x54B', '\x3', '\xA5', '\x5', '\xA5', '\x54F', '\n', '\xA5', '\x3', '\xA6', - '\x5', '\xA6', '\x552', '\n', '\xA6', '\x3', '\xA7', '\x3', '\xA7', '\x3', - '\xA8', '\x3', '\xA8', '\x5', '\xA8', '\x558', '\n', '\xA8', '\x3', '\xA9', - '\x3', '\xA9', '\x3', '\xA9', '\x3', '\xAA', '\x3', '\xAA', '\x3', '\xAA', - '\x3', '\xAA', '\a', '\xAA', '\x561', '\n', '\xAA', '\f', '\xAA', '\xE', - '\xAA', '\x564', '\v', '\xAA', '\x2', '\x2', '\xAB', '\x3', '\x3', '\x5', - '\x4', '\a', '\x5', '\t', '\x6', '\v', '\a', '\r', '\b', '\xF', '\t', - '\x11', '\n', '\x13', '\v', '\x15', '\f', '\x17', '\r', '\x19', '\xE', - '\x1B', '\xF', '\x1D', '\x10', '\x1F', '\x11', '!', '\x12', '#', '\x13', - '%', '\x14', '\'', '\x15', ')', '\x16', '+', '\x17', '-', '\x18', '/', - '\x19', '\x31', '\x1A', '\x33', '\x1B', '\x35', '\x1C', '\x37', '\x1D', - '\x39', '\x1E', ';', '\x1F', '=', ' ', '?', '!', '\x41', '\"', '\x43', - '#', '\x45', '$', 'G', '%', 'I', '&', 'K', '\'', 'M', '(', 'O', ')', 'Q', - '*', 'S', '+', 'U', ',', 'W', '-', 'Y', '.', '[', '/', ']', '\x30', '_', - '\x31', '\x61', '\x32', '\x63', '\x33', '\x65', '\x34', 'g', '\x35', 'i', - '\x36', 'k', '\x37', 'm', '\x38', 'o', '\x39', 'q', ':', 's', ';', 'u', - '<', 'w', '=', 'y', '>', '{', '?', '}', '@', '\x7F', '\x41', '\x81', '\x42', - '\x83', '\x43', '\x85', '\x44', '\x87', '\x45', '\x89', '\x46', '\x8B', - 'G', '\x8D', 'H', '\x8F', 'I', '\x91', 'J', '\x93', 'K', '\x95', 'L', - '\x97', 'M', '\x99', 'N', '\x9B', 'O', '\x9D', 'P', '\x9F', 'Q', '\xA1', - 'R', '\xA3', 'S', '\xA5', 'T', '\xA7', 'U', '\xA9', 'V', '\xAB', 'W', - '\xAD', 'X', '\xAF', 'Y', '\xB1', 'Z', '\xB3', '[', '\xB5', '\\', '\xB7', - ']', '\xB9', '^', '\xBB', '_', '\xBD', '`', '\xBF', '\x61', '\xC1', '\x62', - '\xC3', '\x63', '\xC5', '\x64', '\xC7', '\x65', '\xC9', '\x66', '\xCB', - 'g', '\xCD', 'h', '\xCF', 'i', '\xD1', 'j', '\xD3', 'k', '\xD5', 'l', - '\xD7', 'm', '\xD9', 'n', '\xDB', 'o', '\xDD', 'p', '\xDF', 'q', '\xE1', - 'r', '\xE3', 's', '\xE5', '\x2', '\xE7', '\x2', '\xE9', '\x2', '\xEB', - 't', '\xED', '\x2', '\xEF', '\x2', '\xF1', '\x2', '\xF3', 'u', '\xF5', - 'v', '\xF7', 'w', '\xF9', '\x2', '\xFB', '\x2', '\xFD', '\x2', '\xFF', - 'x', '\x101', '\x2', '\x103', '\x2', '\x105', '\x2', '\x107', 'y', '\x109', - '\x2', '\x10B', '\x2', '\x10D', '\x2', '\x10F', 'z', '\x111', '{', '\x113', - '|', '\x115', '}', '\x117', '~', '\x119', '\x7F', '\x11B', '\x80', '\x11D', - '\x81', '\x11F', '\x82', '\x121', '\x83', '\x123', '\x84', '\x125', '\x85', - '\x127', '\x86', '\x129', '\x87', '\x12B', '\x88', '\x12D', '\x89', '\x12F', - '\x8A', '\x131', '\x8B', '\x133', '\x8C', '\x135', '\x8D', '\x137', '\x8E', - '\x139', '\x8F', '\x13B', '\x90', '\x13D', '\x91', '\x13F', '\x92', '\x141', - '\x93', '\x143', '\x2', '\x145', '\x2', '\x147', '\x2', '\x149', '\x2', - '\x14B', '\x2', '\x14D', '\x94', '\x14F', '\x95', '\x151', '\x96', '\x153', - '\x97', '\x3', '\x2', '\r', '\x3', '\x2', '\x32', '\x33', '\x3', '\x2', - '\x32', '\x39', '\x3', '\x2', '\x32', ';', '\x4', '\x2', '\x32', ';', - '\x61', '\x61', '\x6', '\x2', '\f', '\f', '\xF', '\xF', '$', '$', '^', - '^', '\t', '\x2', '$', '$', ')', ')', '\x32', '\x32', '^', '^', 'p', 'p', - 't', 't', 'v', 'v', '\a', '\x2', '\x32', ';', '\x302', '\x371', '\x1DC2', - '\x1E01', '\x20D2', '\x2101', '\xFE22', '\xFE31', '\x5', '\x2', '\x2', - '\x2', '\v', '\xF', '\"', '\"', '!', '\x2', '#', '#', '\'', '(', ',', - '-', '/', '/', '\x31', '\x31', '>', '\x41', '`', '`', '~', '~', '\x80', - '\x80', '\xA3', '\xA9', '\xAB', '\xAB', '\xAD', '\xAE', '\xB0', '\xB0', - '\xB2', '\xB3', '\xB8', '\xB8', '\xBD', '\xBD', '\xC1', '\xC1', '\xD9', - '\xD9', '\xF9', '\xF9', '\x2018', '\x2019', '\x2022', '\x2029', '\x2032', - '\x2040', '\x2043', '\x2055', '\x2057', '\x2060', '\x2192', '\x2401', - '\x2502', '\x2777', '\x2796', '\x2C01', '\x2E02', '\x2E81', '\x3003', - '\x3005', '\x300A', '\x3022', '\x3032', '\x3032', '\"', '\x2', '#', '#', - '\'', '(', ',', '-', '/', '/', '\x31', '\x31', '>', '?', '\x41', '\x41', - '`', '`', '~', '~', '\x80', '\x80', '\xA3', '\xA9', '\xAB', '\xAB', '\xAD', - '\xAE', '\xB0', '\xB0', '\xB2', '\xB3', '\xB8', '\xB8', '\xBD', '\xBD', - '\xC1', '\xC1', '\xD9', '\xD9', '\xF9', '\xF9', '\x2018', '\x2019', '\x2022', - '\x2029', '\x2032', '\x2040', '\x2043', '\x2055', '\x2057', '\x2060', - '\x2192', '\x2401', '\x2502', '\x2777', '\x2796', '\x2C01', '\x2E02', - '\x2E81', '\x3003', '\x3005', '\x300A', '\x3022', '\x3032', '\x3032', - '\x4', '\x2', '\f', '\f', '\xF', '\xF', '\x5', '\x33', '\x2', '\x43', - '\x2', '\\', '\x2', '\x61', '\x2', '\x61', '\x2', '\x63', '\x2', '|', - '\x2', '\xAA', '\x2', '\xAA', '\x2', '\xAC', '\x2', '\xAC', '\x2', '\xAF', - '\x2', '\xAF', '\x2', '\xB1', '\x2', '\xB1', '\x2', '\xB4', '\x2', '\xB7', - '\x2', '\xB9', '\x2', '\xBC', '\x2', '\xBE', '\x2', '\xC0', '\x2', '\xC2', - '\x2', '\xD8', '\x2', '\xDA', '\x2', '\xF8', '\x2', '\xFA', '\x2', '\x301', - '\x2', '\x372', '\x2', '\x1681', '\x2', '\x1683', '\x2', '\x180F', '\x2', - '\x1811', '\x2', '\x1DC1', '\x2', '\x1E02', '\x2', '\x2001', '\x2', '\x200D', - '\x2', '\x200F', '\x2', '\x202C', '\x2', '\x2030', '\x2', '\x2041', '\x2', - '\x2042', '\x2', '\x2056', '\x2', '\x2056', '\x2', '\x2062', '\x2', '\x20D1', - '\x2', '\x2102', '\x2', '\x2191', '\x2', '\x2462', '\x2', '\x2501', '\x2', - '\x2778', '\x2', '\x2795', '\x2', '\x2C02', '\x2', '\x2E01', '\x2', '\x2E82', - '\x2', '\x3001', '\x2', '\x3006', '\x2', '\x3009', '\x2', '\x3023', '\x2', - '\x3031', '\x2', '\x3033', '\x2', '\xD801', '\x2', '\xF902', '\x2', '\xFD3F', - '\x2', '\xFD42', '\x2', '\xFDD1', '\x2', '\xFDF2', '\x2', '\xFE21', '\x2', - '\xFE32', '\x2', '\xFE46', '\x2', '\xFE49', '\x2', '\xFFFF', '\x2', '\x2', - '\x3', '\xFFFF', '\x3', '\x2', '\x4', '\xFFFF', '\x4', '\x2', '\x5', '\xFFFF', - '\x5', '\x2', '\x6', '\xFFFF', '\x6', '\x2', '\a', '\xFFFF', '\a', '\x2', - '\b', '\xFFFF', '\b', '\x2', '\t', '\xFFFF', '\t', '\x2', '\n', '\xFFFF', - '\n', '\x2', '\v', '\xFFFF', '\v', '\x2', '\f', '\xFFFF', '\f', '\x2', - '\r', '\xFFFF', '\r', '\x2', '\xE', '\xFFFF', '\xE', '\x2', '\xF', '\xFFFF', - '\xF', '\x2', '\x10', '\xFFFF', '\x10', '*', '\x2', '#', '\x2', '#', '\x2', - '\'', '\x2', '(', '\x2', ',', '\x2', '-', '\x2', '/', '\x2', '/', '\x2', - '\x31', '\x2', '\x31', '\x2', '>', '\x2', '?', '\x2', '\x41', '\x2', '\x41', - '\x2', '`', '\x2', '`', '\x2', '~', '\x2', '~', '\x2', '\x80', '\x2', - '\x80', '\x2', '\xA3', '\x2', '\xA9', '\x2', '\xAB', '\x2', '\xAB', '\x2', - '\xAD', '\x2', '\xAE', '\x2', '\xB0', '\x2', '\xB0', '\x2', '\xB2', '\x2', - '\xB3', '\x2', '\xB8', '\x2', '\xB8', '\x2', '\xBD', '\x2', '\xBD', '\x2', - '\xC1', '\x2', '\xC1', '\x2', '\xD9', '\x2', '\xD9', '\x2', '\xF9', '\x2', - '\xF9', '\x2', '\x302', '\x2', '\x302', '\x2', '\x371', '\x2', '\x371', - '\x2', '\x1DC2', '\x2', '\x1E01', '\x2', '\x2015', '\x2', '\x2015', '\x2', - '\x2018', '\x2', '\x2019', '\x2', '\x2022', '\x2', '\x2029', '\x2', '\x2032', - '\x2', '\x2040', '\x2', '\x2043', '\x2', '\x2055', '\x2', '\x2057', '\x2', - '\x2060', '\x2', '\x20D2', '\x2', '\x2101', '\x2', '\x2192', '\x2', '\x2401', - '\x2', '\x2502', '\x2', '\x2777', '\x2', '\x2796', '\x2', '\x2C01', '\x2', - '\x2E02', '\x2', '\x2E81', '\x2', '\x3003', '\x2', '\x3005', '\x2', '\x300A', - '\x2', '\x3022', '\x2', '\x3032', '\x2', '\x3032', '\x2', '\xFE02', '\x2', - '\xFE11', '\x2', '\xFE22', '\x2', '\xFE31', '\x2', '\x102', '\x10', '\x1F1', - '\x10', ')', '\x2', '#', '\x2', '#', '\x2', '\'', '\x2', '(', '\x2', ',', - '\x2', '-', '\x2', '/', '\x2', '/', '\x2', '\x31', '\x2', '\x31', '\x2', - '>', '\x2', '\x41', '\x2', '`', '\x2', '`', '\x2', '~', '\x2', '~', '\x2', - '\x80', '\x2', '\x80', '\x2', '\xA3', '\x2', '\xA9', '\x2', '\xAB', '\x2', - '\xAB', '\x2', '\xAD', '\x2', '\xAE', '\x2', '\xB0', '\x2', '\xB0', '\x2', - '\xB2', '\x2', '\xB3', '\x2', '\xB8', '\x2', '\xB8', '\x2', '\xBD', '\x2', - '\xBD', '\x2', '\xC1', '\x2', '\xC1', '\x2', '\xD9', '\x2', '\xD9', '\x2', - '\xF9', '\x2', '\xF9', '\x2', '\x302', '\x2', '\x302', '\x2', '\x371', - '\x2', '\x371', '\x2', '\x1DC2', '\x2', '\x1E01', '\x2', '\x2015', '\x2', - '\x2015', '\x2', '\x2018', '\x2', '\x2019', '\x2', '\x2022', '\x2', '\x2029', - '\x2', '\x2032', '\x2', '\x2040', '\x2', '\x2043', '\x2', '\x2055', '\x2', - '\x2057', '\x2', '\x2060', '\x2', '\x20D2', '\x2', '\x2101', '\x2', '\x2192', - '\x2', '\x2401', '\x2', '\x2502', '\x2', '\x2777', '\x2', '\x2796', '\x2', - '\x2C01', '\x2', '\x2E02', '\x2', '\x2E81', '\x2', '\x3003', '\x2', '\x3005', - '\x2', '\x300A', '\x2', '\x3022', '\x2', '\x3032', '\x2', '\x3032', '\x2', - '\xFE02', '\x2', '\xFE11', '\x2', '\xFE22', '\x2', '\xFE31', '\x2', '\x102', - '\x10', '\x1F1', '\x10', '\x572', '\x2', '\x3', '\x3', '\x2', '\x2', '\x2', - '\x2', '\x5', '\x3', '\x2', '\x2', '\x2', '\x2', '\a', '\x3', '\x2', '\x2', - '\x2', '\x2', '\t', '\x3', '\x2', '\x2', '\x2', '\x2', '\v', '\x3', '\x2', - '\x2', '\x2', '\x2', '\r', '\x3', '\x2', '\x2', '\x2', '\x2', '\xF', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x11', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x13', '\x3', '\x2', '\x2', '\x2', '\x2', '\x15', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x17', '\x3', '\x2', '\x2', '\x2', '\x2', '\x19', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x1B', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x1D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x1F', '\x3', '\x2', '\x2', - '\x2', '\x2', '!', '\x3', '\x2', '\x2', '\x2', '\x2', '#', '\x3', '\x2', - '\x2', '\x2', '\x2', '%', '\x3', '\x2', '\x2', '\x2', '\x2', '\'', '\x3', - '\x2', '\x2', '\x2', '\x2', ')', '\x3', '\x2', '\x2', '\x2', '\x2', '+', - '\x3', '\x2', '\x2', '\x2', '\x2', '-', '\x3', '\x2', '\x2', '\x2', '\x2', - '/', '\x3', '\x2', '\x2', '\x2', '\x2', '\x31', '\x3', '\x2', '\x2', '\x2', - '\x2', '\x33', '\x3', '\x2', '\x2', '\x2', '\x2', '\x35', '\x3', '\x2', - '\x2', '\x2', '\x2', '\x37', '\x3', '\x2', '\x2', '\x2', '\x2', '\x39', - '\x3', '\x2', '\x2', '\x2', '\x2', ';', '\x3', '\x2', '\x2', '\x2', '\x2', - '=', '\x3', '\x2', '\x2', '\x2', '\x2', '?', '\x3', '\x2', '\x2', '\x2', - '\x2', '\x41', '\x3', '\x2', '\x2', '\x2', '\x2', '\x43', '\x3', '\x2', - '\x2', '\x2', '\x2', '\x45', '\x3', '\x2', '\x2', '\x2', '\x2', 'G', '\x3', - '\x2', '\x2', '\x2', '\x2', 'I', '\x3', '\x2', '\x2', '\x2', '\x2', 'K', - '\x3', '\x2', '\x2', '\x2', '\x2', 'M', '\x3', '\x2', '\x2', '\x2', '\x2', - 'O', '\x3', '\x2', '\x2', '\x2', '\x2', 'Q', '\x3', '\x2', '\x2', '\x2', - '\x2', 'S', '\x3', '\x2', '\x2', '\x2', '\x2', 'U', '\x3', '\x2', '\x2', - '\x2', '\x2', 'W', '\x3', '\x2', '\x2', '\x2', '\x2', 'Y', '\x3', '\x2', - '\x2', '\x2', '\x2', '[', '\x3', '\x2', '\x2', '\x2', '\x2', ']', '\x3', - '\x2', '\x2', '\x2', '\x2', '_', '\x3', '\x2', '\x2', '\x2', '\x2', '\x61', - '\x3', '\x2', '\x2', '\x2', '\x2', '\x63', '\x3', '\x2', '\x2', '\x2', - '\x2', '\x65', '\x3', '\x2', '\x2', '\x2', '\x2', 'g', '\x3', '\x2', '\x2', - '\x2', '\x2', 'i', '\x3', '\x2', '\x2', '\x2', '\x2', 'k', '\x3', '\x2', - '\x2', '\x2', '\x2', 'm', '\x3', '\x2', '\x2', '\x2', '\x2', 'o', '\x3', - '\x2', '\x2', '\x2', '\x2', 'q', '\x3', '\x2', '\x2', '\x2', '\x2', 's', - '\x3', '\x2', '\x2', '\x2', '\x2', 'u', '\x3', '\x2', '\x2', '\x2', '\x2', - 'w', '\x3', '\x2', '\x2', '\x2', '\x2', 'y', '\x3', '\x2', '\x2', '\x2', - '\x2', '{', '\x3', '\x2', '\x2', '\x2', '\x2', '}', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x7F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x81', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x83', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x85', '\x3', '\x2', '\x2', '\x2', '\x2', '\x87', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x89', '\x3', '\x2', '\x2', '\x2', '\x2', '\x8B', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x8D', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x8F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x91', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x93', '\x3', '\x2', '\x2', '\x2', '\x2', '\x95', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x97', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x99', '\x3', '\x2', '\x2', '\x2', '\x2', '\x9B', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x9D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x9F', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xA1', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xA3', '\x3', '\x2', '\x2', '\x2', '\x2', '\xA5', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xA7', '\x3', '\x2', '\x2', '\x2', '\x2', '\xA9', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xAB', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xAD', '\x3', '\x2', '\x2', '\x2', '\x2', '\xAF', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xB1', '\x3', '\x2', '\x2', '\x2', '\x2', '\xB3', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xB5', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xB7', '\x3', '\x2', '\x2', '\x2', '\x2', '\xB9', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xBB', '\x3', '\x2', '\x2', '\x2', '\x2', '\xBD', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xBF', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xC1', '\x3', '\x2', '\x2', '\x2', '\x2', '\xC3', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xC5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xC7', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xC9', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xCB', '\x3', '\x2', '\x2', '\x2', '\x2', '\xCD', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xCF', '\x3', '\x2', '\x2', '\x2', '\x2', '\xD1', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xD3', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xD5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xD7', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xD9', '\x3', '\x2', '\x2', '\x2', '\x2', '\xDB', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xDD', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xDF', '\x3', '\x2', '\x2', '\x2', '\x2', '\xE1', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xE3', '\x3', '\x2', '\x2', '\x2', '\x2', '\xEB', '\x3', - '\x2', '\x2', '\x2', '\x2', '\xF3', '\x3', '\x2', '\x2', '\x2', '\x2', - '\xF5', '\x3', '\x2', '\x2', '\x2', '\x2', '\xF7', '\x3', '\x2', '\x2', - '\x2', '\x2', '\xFF', '\x3', '\x2', '\x2', '\x2', '\x2', '\x107', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x10F', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x111', '\x3', '\x2', '\x2', '\x2', '\x2', '\x113', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x115', '\x3', '\x2', '\x2', '\x2', '\x2', '\x117', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x119', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x11B', '\x3', '\x2', '\x2', '\x2', '\x2', '\x11D', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x11F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x121', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x123', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x125', '\x3', '\x2', '\x2', '\x2', '\x2', '\x127', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x129', '\x3', '\x2', '\x2', '\x2', '\x2', '\x12B', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x12D', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x12F', '\x3', '\x2', '\x2', '\x2', '\x2', '\x131', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x133', '\x3', '\x2', '\x2', '\x2', '\x2', '\x135', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x137', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x139', '\x3', '\x2', '\x2', '\x2', '\x2', '\x13B', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x13D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x13F', '\x3', - '\x2', '\x2', '\x2', '\x2', '\x141', '\x3', '\x2', '\x2', '\x2', '\x2', - '\x14D', '\x3', '\x2', '\x2', '\x2', '\x2', '\x14F', '\x3', '\x2', '\x2', - '\x2', '\x2', '\x151', '\x3', '\x2', '\x2', '\x2', '\x2', '\x153', '\x3', - '\x2', '\x2', '\x2', '\x3', '\x155', '\x3', '\x2', '\x2', '\x2', '\x5', - '\x15C', '\x3', '\x2', '\x2', '\x2', '\a', '\x166', '\x3', '\x2', '\x2', - '\x2', '\t', '\x16D', '\x3', '\x2', '\x2', '\x2', '\v', '\x173', '\x3', - '\x2', '\x2', '\x2', '\r', '\x178', '\x3', '\x2', '\x2', '\x2', '\xF', - '\x181', '\x3', '\x2', '\x2', '\x2', '\x11', '\x185', '\x3', '\x2', '\x2', - '\x2', '\x13', '\x18A', '\x3', '\x2', '\x2', '\x2', '\x15', '\x18E', '\x3', - '\x2', '\x2', '\x2', '\x17', '\x192', '\x3', '\x2', '\x2', '\x2', '\x19', - '\x196', '\x3', '\x2', '\x2', '\x2', '\x1B', '\x19F', '\x3', '\x2', '\x2', - '\x2', '\x1D', '\x1A4', '\x3', '\x2', '\x2', '\x2', '\x1F', '\x1AA', '\x3', - '\x2', '\x2', '\x2', '!', '\x1B1', '\x3', '\x2', '\x2', '\x2', '#', '\x1BA', - '\x3', '\x2', '\x2', '\x2', '%', '\x1C2', '\x3', '\x2', '\x2', '\x2', - '\'', '\x1C8', '\x3', '\x2', '\x2', '\x2', ')', '\x1D8', '\x3', '\x2', - '\x2', '\x2', '+', '\x1E3', '\x3', '\x2', '\x2', '\x2', '-', '\x1ED', - '\x3', '\x2', '\x2', '\x2', '/', '\x1F8', '\x3', '\x2', '\x2', '\x2', - '\x31', '\x206', '\x3', '\x2', '\x2', '\x2', '\x33', '\x20B', '\x3', '\x2', - '\x2', '\x2', '\x35', '\x211', '\x3', '\x2', '\x2', '\x2', '\x37', '\x216', - '\x3', '\x2', '\x2', '\x2', '\x39', '\x220', '\x3', '\x2', '\x2', '\x2', - ';', '\x22A', '\x3', '\x2', '\x2', '\x2', '=', '\x239', '\x3', '\x2', - '\x2', '\x2', '?', '\x23F', '\x3', '\x2', '\x2', '\x2', '\x41', '\x246', - '\x3', '\x2', '\x2', '\x2', '\x43', '\x24F', '\x3', '\x2', '\x2', '\x2', - '\x45', '\x254', '\x3', '\x2', '\x2', '\x2', 'G', '\x25B', '\x3', '\x2', - '\x2', '\x2', 'I', '\x267', '\x3', '\x2', '\x2', '\x2', 'K', '\x26F', - '\x3', '\x2', '\x2', '\x2', 'M', '\x274', '\x3', '\x2', '\x2', '\x2', - 'O', '\x27D', '\x3', '\x2', '\x2', '\x2', 'Q', '\x286', '\x3', '\x2', - '\x2', '\x2', 'S', '\x28F', '\x3', '\x2', '\x2', '\x2', 'U', '\x296', - '\x3', '\x2', '\x2', '\x2', 'W', '\x29E', '\x3', '\x2', '\x2', '\x2', - 'Y', '\x2A3', '\x3', '\x2', '\x2', '\x2', '[', '\x2AA', '\x3', '\x2', - '\x2', '\x2', ']', '\x2AF', '\x3', '\x2', '\x2', '\x2', '_', '\x2B7', - '\x3', '\x2', '\x2', '\x2', '\x61', '\x2C3', '\x3', '\x2', '\x2', '\x2', - '\x63', '\x2CC', '\x3', '\x2', '\x2', '\x2', '\x65', '\x2D3', '\x3', '\x2', - '\x2', '\x2', 'g', '\x2D8', '\x3', '\x2', '\x2', '\x2', 'i', '\x2E1', - '\x3', '\x2', '\x2', '\x2', 'k', '\x2ED', '\x3', '\x2', '\x2', '\x2', - 'm', '\x2F0', '\x3', '\x2', '\x2', '\x2', 'o', '\x2F3', '\x3', '\x2', - '\x2', '\x2', 'q', '\x2F8', '\x3', '\x2', '\x2', '\x2', 's', '\x301', - '\x3', '\x2', '\x2', '\x2', 'u', '\x305', '\x3', '\x2', '\x2', '\x2', - 'w', '\x30A', '\x3', '\x2', '\x2', '\x2', 'y', '\x30E', '\x3', '\x2', - '\x2', '\x2', '{', '\x314', '\x3', '\x2', '\x2', '\x2', '}', '\x318', - '\x3', '\x2', '\x2', '\x2', '\x7F', '\x31D', '\x3', '\x2', '\x2', '\x2', - '\x81', '\x323', '\x3', '\x2', '\x2', '\x2', '\x83', '\x329', '\x3', '\x2', - '\x2', '\x2', '\x85', '\x32B', '\x3', '\x2', '\x2', '\x2', '\x87', '\x32E', - '\x3', '\x2', '\x2', '\x2', '\x89', '\x332', '\x3', '\x2', '\x2', '\x2', - '\x8B', '\x338', '\x3', '\x2', '\x2', '\x2', '\x8D', '\x33D', '\x3', '\x2', - '\x2', '\x2', '\x8F', '\x341', '\x3', '\x2', '\x2', '\x2', '\x91', '\x347', - '\x3', '\x2', '\x2', '\x2', '\x93', '\x34C', '\x3', '\x2', '\x2', '\x2', - '\x95', '\x353', '\x3', '\x2', '\x2', '\x2', '\x97', '\x358', '\x3', '\x2', - '\x2', '\x2', '\x99', '\x35E', '\x3', '\x2', '\x2', '\x2', '\x9B', '\x363', - '\x3', '\x2', '\x2', '\x2', '\x9D', '\x367', '\x3', '\x2', '\x2', '\x2', - '\x9F', '\x37F', '\x3', '\x2', '\x2', '\x2', '\xA1', '\x384', '\x3', '\x2', - '\x2', '\x2', '\xA3', '\x38A', '\x3', '\x2', '\x2', '\x2', '\xA5', '\x3A4', - '\x3', '\x2', '\x2', '\x2', '\xA7', '\x3A7', '\x3', '\x2', '\x2', '\x2', - '\xA9', '\x3AA', '\x3', '\x2', '\x2', '\x2', '\xAB', '\x3B5', '\x3', '\x2', - '\x2', '\x2', '\xAD', '\x3B9', '\x3', '\x2', '\x2', '\x2', '\xAF', '\x3C6', - '\x3', '\x2', '\x2', '\x2', '\xB1', '\x3CC', '\x3', '\x2', '\x2', '\x2', - '\xB3', '\x3D1', '\x3', '\x2', '\x2', '\x2', '\xB5', '\x3D6', '\x3', '\x2', - '\x2', '\x2', '\xB7', '\x3DE', '\x3', '\x2', '\x2', '\x2', '\xB9', '\x3E6', - '\x3', '\x2', '\x2', '\x2', '\xBB', '\x3ED', '\x3', '\x2', '\x2', '\x2', - '\xBD', '\x3F3', '\x3', '\x2', '\x2', '\x2', '\xBF', '\x3F9', '\x3', '\x2', - '\x2', '\x2', '\xC1', '\x402', '\x3', '\x2', '\x2', '\x2', '\xC3', '\x40A', - '\x3', '\x2', '\x2', '\x2', '\xC5', '\x410', '\x3', '\x2', '\x2', '\x2', - '\xC7', '\x413', '\x3', '\x2', '\x2', '\x2', '\xC9', '\x418', '\x3', '\x2', - '\x2', '\x2', '\xCB', '\x424', '\x3', '\x2', '\x2', '\x2', '\xCD', '\x428', - '\x3', '\x2', '\x2', '\x2', '\xCF', '\x42E', '\x3', '\x2', '\x2', '\x2', - '\xD1', '\x431', '\x3', '\x2', '\x2', '\x2', '\xD3', '\x434', '\x3', '\x2', - '\x2', '\x2', '\xD5', '\x43B', '\x3', '\x2', '\x2', '\x2', '\xD7', '\x442', - '\x3', '\x2', '\x2', '\x2', '\xD9', '\x447', '\x3', '\x2', '\x2', '\x2', - '\xDB', '\x44D', '\x3', '\x2', '\x2', '\x2', '\xDD', '\x454', '\x3', '\x2', - '\x2', '\x2', '\xDF', '\x45A', '\x3', '\x2', '\x2', '\x2', '\xE1', '\x45E', - '\x3', '\x2', '\x2', '\x2', '\xE3', '\x464', '\x3', '\x2', '\x2', '\x2', - '\xE5', '\x46B', '\x3', '\x2', '\x2', '\x2', '\xE7', '\x46F', '\x3', '\x2', - '\x2', '\x2', '\xE9', '\x472', '\x3', '\x2', '\x2', '\x2', '\xEB', '\x476', - '\x3', '\x2', '\x2', '\x2', '\xED', '\x47D', '\x3', '\x2', '\x2', '\x2', - '\xEF', '\x481', '\x3', '\x2', '\x2', '\x2', '\xF1', '\x484', '\x3', '\x2', - '\x2', '\x2', '\xF3', '\x488', '\x3', '\x2', '\x2', '\x2', '\xF5', '\x490', - '\x3', '\x2', '\x2', '\x2', '\xF7', '\x494', '\x3', '\x2', '\x2', '\x2', - '\xF9', '\x49B', '\x3', '\x2', '\x2', '\x2', '\xFB', '\x49F', '\x3', '\x2', - '\x2', '\x2', '\xFD', '\x4A2', '\x3', '\x2', '\x2', '\x2', '\xFF', '\x4A6', - '\x3', '\x2', '\x2', '\x2', '\x101', '\x4AD', '\x3', '\x2', '\x2', '\x2', - '\x103', '\x4B3', '\x3', '\x2', '\x2', '\x2', '\x105', '\x4D5', '\x3', - '\x2', '\x2', '\x2', '\x107', '\x4E3', '\x3', '\x2', '\x2', '\x2', '\x109', - '\x4E6', '\x3', '\x2', '\x2', '\x2', '\x10B', '\x4EA', '\x3', '\x2', '\x2', - '\x2', '\x10D', '\x4ED', '\x3', '\x2', '\x2', '\x2', '\x10F', '\x4F1', - '\x3', '\x2', '\x2', '\x2', '\x111', '\x4F5', '\x3', '\x2', '\x2', '\x2', - '\x113', '\x4FB', '\x3', '\x2', '\x2', '\x2', '\x115', '\x4FD', '\x3', - '\x2', '\x2', '\x2', '\x117', '\x4FF', '\x3', '\x2', '\x2', '\x2', '\x119', - '\x501', '\x3', '\x2', '\x2', '\x2', '\x11B', '\x503', '\x3', '\x2', '\x2', - '\x2', '\x11D', '\x505', '\x3', '\x2', '\x2', '\x2', '\x11F', '\x507', - '\x3', '\x2', '\x2', '\x2', '\x121', '\x509', '\x3', '\x2', '\x2', '\x2', - '\x123', '\x50B', '\x3', '\x2', '\x2', '\x2', '\x125', '\x50D', '\x3', - '\x2', '\x2', '\x2', '\x127', '\x50F', '\x3', '\x2', '\x2', '\x2', '\x129', - '\x511', '\x3', '\x2', '\x2', '\x2', '\x12B', '\x513', '\x3', '\x2', '\x2', - '\x2', '\x12D', '\x515', '\x3', '\x2', '\x2', '\x2', '\x12F', '\x517', - '\x3', '\x2', '\x2', '\x2', '\x131', '\x519', '\x3', '\x2', '\x2', '\x2', - '\x133', '\x51B', '\x3', '\x2', '\x2', '\x2', '\x135', '\x51D', '\x3', - '\x2', '\x2', '\x2', '\x137', '\x51F', '\x3', '\x2', '\x2', '\x2', '\x139', - '\x521', '\x3', '\x2', '\x2', '\x2', '\x13B', '\x523', '\x3', '\x2', '\x2', - '\x2', '\x13D', '\x525', '\x3', '\x2', '\x2', '\x2', '\x13F', '\x528', - '\x3', '\x2', '\x2', '\x2', '\x141', '\x540', '\x3', '\x2', '\x2', '\x2', - '\x143', '\x543', '\x3', '\x2', '\x2', '\x2', '\x145', '\x546', '\x3', - '\x2', '\x2', '\x2', '\x147', '\x549', '\x3', '\x2', '\x2', '\x2', '\x149', - '\x54E', '\x3', '\x2', '\x2', '\x2', '\x14B', '\x551', '\x3', '\x2', '\x2', - '\x2', '\x14D', '\x553', '\x3', '\x2', '\x2', '\x2', '\x14F', '\x557', - '\x3', '\x2', '\x2', '\x2', '\x151', '\x559', '\x3', '\x2', '\x2', '\x2', - '\x153', '\x55C', '\x3', '\x2', '\x2', '\x2', '\x155', '\x156', '\a', - 'k', '\x2', '\x2', '\x156', '\x157', '\a', 'o', '\x2', '\x2', '\x157', - '\x158', '\a', 'r', '\x2', '\x2', '\x158', '\x159', '\a', 'q', '\x2', - '\x2', '\x159', '\x15A', '\a', 't', '\x2', '\x2', '\x15A', '\x15B', '\a', - 'v', '\x2', '\x2', '\x15B', '\x4', '\x3', '\x2', '\x2', '\x2', '\x15C', - '\x15D', '\a', 'v', '\x2', '\x2', '\x15D', '\x15E', '\a', '{', '\x2', - '\x2', '\x15E', '\x15F', '\a', 'r', '\x2', '\x2', '\x15F', '\x160', '\a', - 'g', '\x2', '\x2', '\x160', '\x161', '\a', '\x63', '\x2', '\x2', '\x161', - '\x162', '\a', 'n', '\x2', '\x2', '\x162', '\x163', '\a', 'k', '\x2', - '\x2', '\x163', '\x164', '\a', '\x63', '\x2', '\x2', '\x164', '\x165', - '\a', 'u', '\x2', '\x2', '\x165', '\x6', '\x3', '\x2', '\x2', '\x2', '\x166', - '\x167', '\a', 'u', '\x2', '\x2', '\x167', '\x168', '\a', 'v', '\x2', - '\x2', '\x168', '\x169', '\a', 't', '\x2', '\x2', '\x169', '\x16A', '\a', - 'w', '\x2', '\x2', '\x16A', '\x16B', '\a', '\x65', '\x2', '\x2', '\x16B', - '\x16C', '\a', 'v', '\x2', '\x2', '\x16C', '\b', '\x3', '\x2', '\x2', - '\x2', '\x16D', '\x16E', '\a', '\x65', '\x2', '\x2', '\x16E', '\x16F', - '\a', 'n', '\x2', '\x2', '\x16F', '\x170', '\a', '\x63', '\x2', '\x2', - '\x170', '\x171', '\a', 'u', '\x2', '\x2', '\x171', '\x172', '\a', 'u', - '\x2', '\x2', '\x172', '\n', '\x3', '\x2', '\x2', '\x2', '\x173', '\x174', - '\a', 'g', '\x2', '\x2', '\x174', '\x175', '\a', 'p', '\x2', '\x2', '\x175', - '\x176', '\a', 'w', '\x2', '\x2', '\x176', '\x177', '\a', 'o', '\x2', - '\x2', '\x177', '\f', '\x3', '\x2', '\x2', '\x2', '\x178', '\x179', '\a', - 'r', '\x2', '\x2', '\x179', '\x17A', '\a', 't', '\x2', '\x2', '\x17A', - '\x17B', '\a', 'q', '\x2', '\x2', '\x17B', '\x17C', '\a', 'v', '\x2', - '\x2', '\x17C', '\x17D', '\a', 'q', '\x2', '\x2', '\x17D', '\x17E', '\a', - '\x65', '\x2', '\x2', '\x17E', '\x17F', '\a', 'q', '\x2', '\x2', '\x17F', - '\x180', '\a', 'n', '\x2', '\x2', '\x180', '\xE', '\x3', '\x2', '\x2', - '\x2', '\x181', '\x182', '\a', 'x', '\x2', '\x2', '\x182', '\x183', '\a', - '\x63', '\x2', '\x2', '\x183', '\x184', '\a', 't', '\x2', '\x2', '\x184', - '\x10', '\x3', '\x2', '\x2', '\x2', '\x185', '\x186', '\a', 'h', '\x2', - '\x2', '\x186', '\x187', '\a', 'w', '\x2', '\x2', '\x187', '\x188', '\a', - 'p', '\x2', '\x2', '\x188', '\x189', '\a', '\x65', '\x2', '\x2', '\x189', - '\x12', '\x3', '\x2', '\x2', '\x2', '\x18A', '\x18B', '\a', 'n', '\x2', - '\x2', '\x18B', '\x18C', '\a', 'g', '\x2', '\x2', '\x18C', '\x18D', '\a', - 'v', '\x2', '\x2', '\x18D', '\x14', '\x3', '\x2', '\x2', '\x2', '\x18E', - '\x18F', '\a', 'i', '\x2', '\x2', '\x18F', '\x190', '\a', 'g', '\x2', - '\x2', '\x190', '\x191', '\a', 'v', '\x2', '\x2', '\x191', '\x16', '\x3', - '\x2', '\x2', '\x2', '\x192', '\x193', '\a', 'u', '\x2', '\x2', '\x193', - '\x194', '\a', 'g', '\x2', '\x2', '\x194', '\x195', '\a', 'v', '\x2', - '\x2', '\x195', '\x18', '\x3', '\x2', '\x2', '\x2', '\x196', '\x197', - '\a', 'k', '\x2', '\x2', '\x197', '\x198', '\a', 'p', '\x2', '\x2', '\x198', - '\x199', '\a', '\x66', '\x2', '\x2', '\x199', '\x19A', '\a', 'k', '\x2', - '\x2', '\x19A', '\x19B', '\a', 't', '\x2', '\x2', '\x19B', '\x19C', '\a', - 'g', '\x2', '\x2', '\x19C', '\x19D', '\a', '\x65', '\x2', '\x2', '\x19D', - '\x19E', '\a', 'v', '\x2', '\x2', '\x19E', '\x1A', '\x3', '\x2', '\x2', - '\x2', '\x19F', '\x1A0', '\a', '\x65', '\x2', '\x2', '\x1A0', '\x1A1', - '\a', '\x63', '\x2', '\x2', '\x1A1', '\x1A2', '\a', 'u', '\x2', '\x2', - '\x1A2', '\x1A3', '\a', 'g', '\x2', '\x2', '\x1A3', '\x1C', '\x3', '\x2', - '\x2', '\x2', '\x1A4', '\x1A5', '\a', 'h', '\x2', '\x2', '\x1A5', '\x1A6', - '\a', 'k', '\x2', '\x2', '\x1A6', '\x1A7', '\a', 'p', '\x2', '\x2', '\x1A7', - '\x1A8', '\a', '\x63', '\x2', '\x2', '\x1A8', '\x1A9', '\a', 'n', '\x2', - '\x2', '\x1A9', '\x1E', '\x3', '\x2', '\x2', '\x2', '\x1AA', '\x1AB', - '\a', 'r', '\x2', '\x2', '\x1AB', '\x1AC', '\a', 't', '\x2', '\x2', '\x1AC', - '\x1AD', '\a', 'g', '\x2', '\x2', '\x1AD', '\x1AE', '\a', 'h', '\x2', - '\x2', '\x1AE', '\x1AF', '\a', 'k', '\x2', '\x2', '\x1AF', '\x1B0', '\a', - 'z', '\x2', '\x2', '\x1B0', ' ', '\x3', '\x2', '\x2', '\x2', '\x1B1', - '\x1B2', '\a', 'q', '\x2', '\x2', '\x1B2', '\x1B3', '\a', 'r', '\x2', - '\x2', '\x1B3', '\x1B4', '\a', 'g', '\x2', '\x2', '\x1B4', '\x1B5', '\a', - 't', '\x2', '\x2', '\x1B5', '\x1B6', '\a', '\x63', '\x2', '\x2', '\x1B6', - '\x1B7', '\a', 'v', '\x2', '\x2', '\x1B7', '\x1B8', '\a', 'q', '\x2', - '\x2', '\x1B8', '\x1B9', '\a', 't', '\x2', '\x2', '\x1B9', '\"', '\x3', - '\x2', '\x2', '\x2', '\x1BA', '\x1BB', '\a', 'r', '\x2', '\x2', '\x1BB', - '\x1BC', '\a', 'q', '\x2', '\x2', '\x1BC', '\x1BD', '\a', 'u', '\x2', - '\x2', '\x1BD', '\x1BE', '\a', 'v', '\x2', '\x2', '\x1BE', '\x1BF', '\a', - 'h', '\x2', '\x2', '\x1BF', '\x1C0', '\a', 'k', '\x2', '\x2', '\x1C0', - '\x1C1', '\a', 'z', '\x2', '\x2', '\x1C1', '$', '\x3', '\x2', '\x2', '\x2', - '\x1C2', '\x1C3', '\a', 'k', '\x2', '\x2', '\x1C3', '\x1C4', '\a', 'p', - '\x2', '\x2', '\x1C4', '\x1C5', '\a', 'h', '\x2', '\x2', '\x1C5', '\x1C6', - '\a', 'k', '\x2', '\x2', '\x1C6', '\x1C7', '\a', 'z', '\x2', '\x2', '\x1C7', - '&', '\x3', '\x2', '\x2', '\x2', '\x1C8', '\x1C9', '\a', 'r', '\x2', '\x2', - '\x1C9', '\x1CA', '\a', 't', '\x2', '\x2', '\x1CA', '\x1CB', '\a', 'g', - '\x2', '\x2', '\x1CB', '\x1CC', '\a', '\x65', '\x2', '\x2', '\x1CC', '\x1CD', - '\a', 'g', '\x2', '\x2', '\x1CD', '\x1CE', '\a', '\x66', '\x2', '\x2', - '\x1CE', '\x1CF', '\a', 'g', '\x2', '\x2', '\x1CF', '\x1D0', '\a', 'p', - '\x2', '\x2', '\x1D0', '\x1D1', '\a', '\x65', '\x2', '\x2', '\x1D1', '\x1D2', - '\a', 'g', '\x2', '\x2', '\x1D2', '\x1D3', '\a', 'i', '\x2', '\x2', '\x1D3', - '\x1D4', '\a', 't', '\x2', '\x2', '\x1D4', '\x1D5', '\a', 'q', '\x2', - '\x2', '\x1D5', '\x1D6', '\a', 'w', '\x2', '\x2', '\x1D6', '\x1D7', '\a', - 'r', '\x2', '\x2', '\x1D7', '(', '\x3', '\x2', '\x2', '\x2', '\x1D8', - '\x1D9', '\a', 'j', '\x2', '\x2', '\x1D9', '\x1DA', '\a', 'k', '\x2', - '\x2', '\x1DA', '\x1DB', '\a', 'i', '\x2', '\x2', '\x1DB', '\x1DC', '\a', - 'j', '\x2', '\x2', '\x1DC', '\x1DD', '\a', 'g', '\x2', '\x2', '\x1DD', - '\x1DE', '\a', 't', '\x2', '\x2', '\x1DE', '\x1DF', '\a', 'V', '\x2', - '\x2', '\x1DF', '\x1E0', '\a', 'j', '\x2', '\x2', '\x1E0', '\x1E1', '\a', - '\x63', '\x2', '\x2', '\x1E1', '\x1E2', '\a', 'p', '\x2', '\x2', '\x1E2', - '*', '\x3', '\x2', '\x2', '\x2', '\x1E3', '\x1E4', '\a', 'n', '\x2', '\x2', - '\x1E4', '\x1E5', '\a', 'q', '\x2', '\x2', '\x1E5', '\x1E6', '\a', 'y', - '\x2', '\x2', '\x1E6', '\x1E7', '\a', 'g', '\x2', '\x2', '\x1E7', '\x1E8', - '\a', 't', '\x2', '\x2', '\x1E8', '\x1E9', '\a', 'V', '\x2', '\x2', '\x1E9', - '\x1EA', '\a', 'j', '\x2', '\x2', '\x1EA', '\x1EB', '\a', '\x63', '\x2', - '\x2', '\x1EB', '\x1EC', '\a', 'p', '\x2', '\x2', '\x1EC', ',', '\x3', - '\x2', '\x2', '\x2', '\x1ED', '\x1EE', '\a', '\x63', '\x2', '\x2', '\x1EE', - '\x1EF', '\a', 'u', '\x2', '\x2', '\x1EF', '\x1F0', '\a', 'u', '\x2', - '\x2', '\x1F0', '\x1F1', '\a', 'k', '\x2', '\x2', '\x1F1', '\x1F2', '\a', - 'i', '\x2', '\x2', '\x1F2', '\x1F3', '\a', 'p', '\x2', '\x2', '\x1F3', - '\x1F4', '\a', 'o', '\x2', '\x2', '\x1F4', '\x1F5', '\a', 'g', '\x2', - '\x2', '\x1F5', '\x1F6', '\a', 'p', '\x2', '\x2', '\x1F6', '\x1F7', '\a', - 'v', '\x2', '\x2', '\x1F7', '.', '\x3', '\x2', '\x2', '\x2', '\x1F8', - '\x1F9', '\a', '\x63', '\x2', '\x2', '\x1F9', '\x1FA', '\a', 'u', '\x2', - '\x2', '\x1FA', '\x1FB', '\a', 'u', '\x2', '\x2', '\x1FB', '\x1FC', '\a', - 'q', '\x2', '\x2', '\x1FC', '\x1FD', '\a', '\x65', '\x2', '\x2', '\x1FD', - '\x1FE', '\a', 'k', '\x2', '\x2', '\x1FE', '\x1FF', '\a', '\x63', '\x2', - '\x2', '\x1FF', '\x200', '\a', 'v', '\x2', '\x2', '\x200', '\x201', '\a', - 'k', '\x2', '\x2', '\x201', '\x202', '\a', 'x', '\x2', '\x2', '\x202', - '\x203', '\a', 'k', '\x2', '\x2', '\x203', '\x204', '\a', 'v', '\x2', - '\x2', '\x204', '\x205', '\a', '{', '\x2', '\x2', '\x205', '\x30', '\x3', - '\x2', '\x2', '\x2', '\x206', '\x207', '\a', 'n', '\x2', '\x2', '\x207', - '\x208', '\a', 'g', '\x2', '\x2', '\x208', '\x209', '\a', 'h', '\x2', - '\x2', '\x209', '\x20A', '\a', 'v', '\x2', '\x2', '\x20A', '\x32', '\x3', - '\x2', '\x2', '\x2', '\x20B', '\x20C', '\a', 't', '\x2', '\x2', '\x20C', - '\x20D', '\a', 'k', '\x2', '\x2', '\x20D', '\x20E', '\a', 'i', '\x2', - '\x2', '\x20E', '\x20F', '\a', 'j', '\x2', '\x2', '\x20F', '\x210', '\a', - 'v', '\x2', '\x2', '\x210', '\x34', '\x3', '\x2', '\x2', '\x2', '\x211', - '\x212', '\a', 'p', '\x2', '\x2', '\x212', '\x213', '\a', 'q', '\x2', - '\x2', '\x213', '\x214', '\a', 'p', '\x2', '\x2', '\x214', '\x215', '\a', - 'g', '\x2', '\x2', '\x215', '\x36', '\x3', '\x2', '\x2', '\x2', '\x216', - '\x217', '\a', 'g', '\x2', '\x2', '\x217', '\x218', '\a', 'z', '\x2', - '\x2', '\x218', '\x219', '\a', 'v', '\x2', '\x2', '\x219', '\x21A', '\a', - 'g', '\x2', '\x2', '\x21A', '\x21B', '\a', 'p', '\x2', '\x2', '\x21B', - '\x21C', '\a', 'u', '\x2', '\x2', '\x21C', '\x21D', '\a', 'k', '\x2', - '\x2', '\x21D', '\x21E', '\a', 'q', '\x2', '\x2', '\x21E', '\x21F', '\a', - 'p', '\x2', '\x2', '\x21F', '\x38', '\x3', '\x2', '\x2', '\x2', '\x220', - '\x221', '\a', 'u', '\x2', '\x2', '\x221', '\x222', '\a', 'w', '\x2', - '\x2', '\x222', '\x223', '\a', '\x64', '\x2', '\x2', '\x223', '\x224', - '\a', 'u', '\x2', '\x2', '\x224', '\x225', '\a', '\x65', '\x2', '\x2', - '\x225', '\x226', '\a', 't', '\x2', '\x2', '\x226', '\x227', '\a', 'k', - '\x2', '\x2', '\x227', '\x228', '\a', 'r', '\x2', '\x2', '\x228', '\x229', - '\a', 'v', '\x2', '\x2', '\x229', ':', '\x3', '\x2', '\x2', '\x2', '\x22A', - '\x22B', '\a', '\x63', '\x2', '\x2', '\x22B', '\x22C', '\a', 'u', '\x2', - '\x2', '\x22C', '\x22D', '\a', 'u', '\x2', '\x2', '\x22D', '\x22E', '\a', - 'q', '\x2', '\x2', '\x22E', '\x22F', '\a', '\x65', '\x2', '\x2', '\x22F', - '\x230', '\a', 'k', '\x2', '\x2', '\x230', '\x231', '\a', '\x63', '\x2', - '\x2', '\x231', '\x232', '\a', 'v', '\x2', '\x2', '\x232', '\x233', '\a', - 'g', '\x2', '\x2', '\x233', '\x234', '\a', '\x66', '\x2', '\x2', '\x234', - '\x235', '\a', 'v', '\x2', '\x2', '\x235', '\x236', '\a', '{', '\x2', - '\x2', '\x236', '\x237', '\a', 'r', '\x2', '\x2', '\x237', '\x238', '\a', - 'g', '\x2', '\x2', '\x238', '<', '\x3', '\x2', '\x2', '\x2', '\x239', - '\x23A', '\a', '\x63', '\x2', '\x2', '\x23A', '\x23B', '\a', 'u', '\x2', - '\x2', '\x23B', '\x23C', '\a', '{', '\x2', '\x2', '\x23C', '\x23D', '\a', - 'p', '\x2', '\x2', '\x23D', '\x23E', '\a', '\x65', '\x2', '\x2', '\x23E', - '>', '\x3', '\x2', '\x2', '\x2', '\x23F', '\x240', '\a', 'v', '\x2', '\x2', - '\x240', '\x241', '\a', 'j', '\x2', '\x2', '\x241', '\x242', '\a', 't', - '\x2', '\x2', '\x242', '\x243', '\a', 'q', '\x2', '\x2', '\x243', '\x244', - '\a', 'y', '\x2', '\x2', '\x244', '\x245', '\a', 'u', '\x2', '\x2', '\x245', - '@', '\x3', '\x2', '\x2', '\x2', '\x246', '\x247', '\a', 't', '\x2', '\x2', - '\x247', '\x248', '\a', 'g', '\x2', '\x2', '\x248', '\x249', '\a', 'v', - '\x2', '\x2', '\x249', '\x24A', '\a', 'j', '\x2', '\x2', '\x24A', '\x24B', - '\a', 't', '\x2', '\x2', '\x24B', '\x24C', '\a', 'q', '\x2', '\x2', '\x24C', - '\x24D', '\a', 'y', '\x2', '\x2', '\x24D', '\x24E', '\a', 'u', '\x2', - '\x2', '\x24E', '\x42', '\x3', '\x2', '\x2', '\x2', '\x24F', '\x250', - '\a', 'k', '\x2', '\x2', '\x250', '\x251', '\a', 'p', '\x2', '\x2', '\x251', - '\x252', '\a', 'k', '\x2', '\x2', '\x252', '\x253', '\a', 'v', '\x2', - '\x2', '\x253', '\x44', '\x3', '\x2', '\x2', '\x2', '\x254', '\x255', - '\a', '\x66', '\x2', '\x2', '\x255', '\x256', '\a', 'g', '\x2', '\x2', - '\x256', '\x257', '\a', 'k', '\x2', '\x2', '\x257', '\x258', '\a', 'p', - '\x2', '\x2', '\x258', '\x259', '\a', 'k', '\x2', '\x2', '\x259', '\x25A', - '\a', 'v', '\x2', '\x2', '\x25A', '\x46', '\x3', '\x2', '\x2', '\x2', - '\x25B', '\x25C', '\a', '\x65', '\x2', '\x2', '\x25C', '\x25D', '\a', - 'q', '\x2', '\x2', '\x25D', '\x25E', '\a', 'p', '\x2', '\x2', '\x25E', - '\x25F', '\a', 'x', '\x2', '\x2', '\x25F', '\x260', '\a', 'g', '\x2', - '\x2', '\x260', '\x261', '\a', 'p', '\x2', '\x2', '\x261', '\x262', '\a', - 'k', '\x2', '\x2', '\x262', '\x263', '\a', 'g', '\x2', '\x2', '\x263', - '\x264', '\a', 'p', '\x2', '\x2', '\x264', '\x265', '\a', '\x65', '\x2', - '\x2', '\x265', '\x266', '\a', 'g', '\x2', '\x2', '\x266', 'H', '\x3', - '\x2', '\x2', '\x2', '\x267', '\x268', '\a', '\x66', '\x2', '\x2', '\x268', - '\x269', '\a', '{', '\x2', '\x2', '\x269', '\x26A', '\a', 'p', '\x2', - '\x2', '\x26A', '\x26B', '\a', '\x63', '\x2', '\x2', '\x26B', '\x26C', - '\a', 'o', '\x2', '\x2', '\x26C', '\x26D', '\a', 'k', '\x2', '\x2', '\x26D', - '\x26E', '\a', '\x65', '\x2', '\x2', '\x26E', 'J', '\x3', '\x2', '\x2', - '\x2', '\x26F', '\x270', '\a', 'n', '\x2', '\x2', '\x270', '\x271', '\a', - '\x63', '\x2', '\x2', '\x271', '\x272', '\a', '|', '\x2', '\x2', '\x272', - '\x273', '\a', '{', '\x2', '\x2', '\x273', 'L', '\x3', '\x2', '\x2', '\x2', - '\x274', '\x275', '\a', 'q', '\x2', '\x2', '\x275', '\x276', '\a', 'r', - '\x2', '\x2', '\x276', '\x277', '\a', 'v', '\x2', '\x2', '\x277', '\x278', - '\a', 'k', '\x2', '\x2', '\x278', '\x279', '\a', 'q', '\x2', '\x2', '\x279', - '\x27A', '\a', 'p', '\x2', '\x2', '\x27A', '\x27B', '\a', '\x63', '\x2', - '\x2', '\x27B', '\x27C', '\a', 'n', '\x2', '\x2', '\x27C', 'N', '\x3', - '\x2', '\x2', '\x2', '\x27D', '\x27E', '\a', 'q', '\x2', '\x2', '\x27E', - '\x27F', '\a', 'x', '\x2', '\x2', '\x27F', '\x280', '\a', 'g', '\x2', - '\x2', '\x280', '\x281', '\a', 't', '\x2', '\x2', '\x281', '\x282', '\a', - 't', '\x2', '\x2', '\x282', '\x283', '\a', 'k', '\x2', '\x2', '\x283', - '\x284', '\a', '\x66', '\x2', '\x2', '\x284', '\x285', '\a', 'g', '\x2', - '\x2', '\x285', 'P', '\x3', '\x2', '\x2', '\x2', '\x286', '\x287', '\a', - 't', '\x2', '\x2', '\x287', '\x288', '\a', 'g', '\x2', '\x2', '\x288', - '\x289', '\a', 's', '\x2', '\x2', '\x289', '\x28A', '\a', 'w', '\x2', - '\x2', '\x28A', '\x28B', '\a', 'k', '\x2', '\x2', '\x28B', '\x28C', '\a', - 't', '\x2', '\x2', '\x28C', '\x28D', '\a', 'g', '\x2', '\x2', '\x28D', - '\x28E', '\a', '\x66', '\x2', '\x2', '\x28E', 'R', '\x3', '\x2', '\x2', - '\x2', '\x28F', '\x290', '\a', 'u', '\x2', '\x2', '\x290', '\x291', '\a', - 'v', '\x2', '\x2', '\x291', '\x292', '\a', '\x63', '\x2', '\x2', '\x292', - '\x293', '\a', 'v', '\x2', '\x2', '\x293', '\x294', '\a', 'k', '\x2', - '\x2', '\x294', '\x295', '\a', '\x65', '\x2', '\x2', '\x295', 'T', '\x3', - '\x2', '\x2', '\x2', '\x296', '\x297', '\a', 'w', '\x2', '\x2', '\x297', - '\x298', '\a', 'p', '\x2', '\x2', '\x298', '\x299', '\a', 'q', '\x2', - '\x2', '\x299', '\x29A', '\a', 'y', '\x2', '\x2', '\x29A', '\x29B', '\a', - 'p', '\x2', '\x2', '\x29B', '\x29C', '\a', 'g', '\x2', '\x2', '\x29C', - '\x29D', '\a', '\x66', '\x2', '\x2', '\x29D', 'V', '\x3', '\x2', '\x2', - '\x2', '\x29E', '\x29F', '\a', 'u', '\x2', '\x2', '\x29F', '\x2A0', '\a', - '\x63', '\x2', '\x2', '\x2A0', '\x2A1', '\a', 'h', '\x2', '\x2', '\x2A1', - '\x2A2', '\a', 'g', '\x2', '\x2', '\x2A2', 'X', '\x3', '\x2', '\x2', '\x2', - '\x2A3', '\x2A4', '\a', 'w', '\x2', '\x2', '\x2A4', '\x2A5', '\a', 'p', - '\x2', '\x2', '\x2A5', '\x2A6', '\a', 'u', '\x2', '\x2', '\x2A6', '\x2A7', - '\a', '\x63', '\x2', '\x2', '\x2A7', '\x2A8', '\a', 'h', '\x2', '\x2', - '\x2A8', '\x2A9', '\a', 'g', '\x2', '\x2', '\x2A9', 'Z', '\x3', '\x2', - '\x2', '\x2', '\x2AA', '\x2AB', '\a', 'y', '\x2', '\x2', '\x2AB', '\x2AC', - '\a', 'g', '\x2', '\x2', '\x2AC', '\x2AD', '\a', '\x63', '\x2', '\x2', - '\x2AD', '\x2AE', '\a', 'm', '\x2', '\x2', '\x2AE', '\\', '\x3', '\x2', - '\x2', '\x2', '\x2AF', '\x2B0', '\a', 'r', '\x2', '\x2', '\x2B0', '\x2B1', - '\a', 't', '\x2', '\x2', '\x2B1', '\x2B2', '\a', 'k', '\x2', '\x2', '\x2B2', - '\x2B3', '\a', 'x', '\x2', '\x2', '\x2B3', '\x2B4', '\a', '\x63', '\x2', - '\x2', '\x2B4', '\x2B5', '\a', 'v', '\x2', '\x2', '\x2B5', '\x2B6', '\a', - 'g', '\x2', '\x2', '\x2B6', '^', '\x3', '\x2', '\x2', '\x2', '\x2B7', - '\x2B8', '\a', 'h', '\x2', '\x2', '\x2B8', '\x2B9', '\a', 'k', '\x2', - '\x2', '\x2B9', '\x2BA', '\a', 'n', '\x2', '\x2', '\x2BA', '\x2BB', '\a', - 'g', '\x2', '\x2', '\x2BB', '\x2BC', '\a', 'r', '\x2', '\x2', '\x2BC', - '\x2BD', '\a', 't', '\x2', '\x2', '\x2BD', '\x2BE', '\a', 'k', '\x2', - '\x2', '\x2BE', '\x2BF', '\a', 'x', '\x2', '\x2', '\x2BF', '\x2C0', '\a', - '\x63', '\x2', '\x2', '\x2C0', '\x2C1', '\a', 'v', '\x2', '\x2', '\x2C1', - '\x2C2', '\a', 'g', '\x2', '\x2', '\x2C2', '`', '\x3', '\x2', '\x2', '\x2', - '\x2C3', '\x2C4', '\a', 'k', '\x2', '\x2', '\x2C4', '\x2C5', '\a', 'p', - '\x2', '\x2', '\x2C5', '\x2C6', '\a', 'v', '\x2', '\x2', '\x2C6', '\x2C7', - '\a', 'g', '\x2', '\x2', '\x2C7', '\x2C8', '\a', 't', '\x2', '\x2', '\x2C8', - '\x2C9', '\a', 'p', '\x2', '\x2', '\x2C9', '\x2CA', '\a', '\x63', '\x2', - '\x2', '\x2CA', '\x2CB', '\a', 'n', '\x2', '\x2', '\x2CB', '\x62', '\x3', - '\x2', '\x2', '\x2', '\x2CC', '\x2CD', '\a', 'r', '\x2', '\x2', '\x2CD', - '\x2CE', '\a', 'w', '\x2', '\x2', '\x2CE', '\x2CF', '\a', '\x64', '\x2', - '\x2', '\x2CF', '\x2D0', '\a', 'n', '\x2', '\x2', '\x2D0', '\x2D1', '\a', - 'k', '\x2', '\x2', '\x2D1', '\x2D2', '\a', '\x65', '\x2', '\x2', '\x2D2', - '\x64', '\x3', '\x2', '\x2', '\x2', '\x2D3', '\x2D4', '\a', 'q', '\x2', - '\x2', '\x2D4', '\x2D5', '\a', 'r', '\x2', '\x2', '\x2D5', '\x2D6', '\a', - 'g', '\x2', '\x2', '\x2D6', '\x2D7', '\a', 'p', '\x2', '\x2', '\x2D7', - '\x66', '\x3', '\x2', '\x2', '\x2', '\x2D8', '\x2D9', '\a', 'o', '\x2', - '\x2', '\x2D9', '\x2DA', '\a', 'w', '\x2', '\x2', '\x2DA', '\x2DB', '\a', - 'v', '\x2', '\x2', '\x2DB', '\x2DC', '\a', '\x63', '\x2', '\x2', '\x2DC', - '\x2DD', '\a', 'v', '\x2', '\x2', '\x2DD', '\x2DE', '\a', 'k', '\x2', - '\x2', '\x2DE', '\x2DF', '\a', 'p', '\x2', '\x2', '\x2DF', '\x2E0', '\a', - 'i', '\x2', '\x2', '\x2E0', 'h', '\x3', '\x2', '\x2', '\x2', '\x2E1', - '\x2E2', '\a', 'p', '\x2', '\x2', '\x2E2', '\x2E3', '\a', 'q', '\x2', - '\x2', '\x2E3', '\x2E4', '\a', 'p', '\x2', '\x2', '\x2E4', '\x2E5', '\a', - 'o', '\x2', '\x2', '\x2E5', '\x2E6', '\a', 'w', '\x2', '\x2', '\x2E6', - '\x2E7', '\a', 'v', '\x2', '\x2', '\x2E7', '\x2E8', '\a', '\x63', '\x2', - '\x2', '\x2E8', '\x2E9', '\a', 'v', '\x2', '\x2', '\x2E9', '\x2EA', '\a', - 'k', '\x2', '\x2', '\x2EA', '\x2EB', '\a', 'p', '\x2', '\x2', '\x2EB', - '\x2EC', '\a', 'i', '\x2', '\x2', '\x2EC', 'j', '\x3', '\x2', '\x2', '\x2', - '\x2ED', '\x2EE', '\a', 'k', '\x2', '\x2', '\x2EE', '\x2EF', '\a', 'u', - '\x2', '\x2', '\x2EF', 'l', '\x3', '\x2', '\x2', '\x2', '\x2F0', '\x2F1', - '\a', '\x63', '\x2', '\x2', '\x2F1', '\x2F2', '\a', 'u', '\x2', '\x2', - '\x2F2', 'n', '\x3', '\x2', '\x2', '\x2', '\x2F3', '\x2F4', '\a', 'V', - '\x2', '\x2', '\x2F4', '\x2F5', '\a', '{', '\x2', '\x2', '\x2F5', '\x2F6', - '\a', 'r', '\x2', '\x2', '\x2F6', '\x2F7', '\a', 'g', '\x2', '\x2', '\x2F7', - 'p', '\x3', '\x2', '\x2', '\x2', '\x2F8', '\x2F9', '\a', 'R', '\x2', '\x2', - '\x2F9', '\x2FA', '\a', 't', '\x2', '\x2', '\x2FA', '\x2FB', '\a', 'q', - '\x2', '\x2', '\x2FB', '\x2FC', '\a', 'v', '\x2', '\x2', '\x2FC', '\x2FD', - '\a', 'q', '\x2', '\x2', '\x2FD', '\x2FE', '\a', '\x65', '\x2', '\x2', - '\x2FE', '\x2FF', '\a', 'q', '\x2', '\x2', '\x2FF', '\x300', '\a', 'n', - '\x2', '\x2', '\x300', 'r', '\x3', '\x2', '\x2', '\x2', '\x301', '\x302', - '\a', '\x43', '\x2', '\x2', '\x302', '\x303', '\a', 'p', '\x2', '\x2', - '\x303', '\x304', '\a', '{', '\x2', '\x2', '\x304', 't', '\x3', '\x2', - '\x2', '\x2', '\x305', '\x306', '\a', 'U', '\x2', '\x2', '\x306', '\x307', - '\a', 'g', '\x2', '\x2', '\x307', '\x308', '\a', 'n', '\x2', '\x2', '\x308', - '\x309', '\a', 'h', '\x2', '\x2', '\x309', 'v', '\x3', '\x2', '\x2', '\x2', - '\x30A', '\x30B', '\a', '\x63', '\x2', '\x2', '\x30B', '\x30C', '\a', - 'p', '\x2', '\x2', '\x30C', '\x30D', '\a', '{', '\x2', '\x2', '\x30D', - 'x', '\x3', '\x2', '\x2', '\x2', '\x30E', '\x30F', '\a', 'k', '\x2', '\x2', - '\x30F', '\x310', '\a', 'p', '\x2', '\x2', '\x310', '\x311', '\a', 'q', - '\x2', '\x2', '\x311', '\x312', '\a', 'w', '\x2', '\x2', '\x312', '\x313', - '\a', 'v', '\x2', '\x2', '\x313', 'z', '\x3', '\x2', '\x2', '\x2', '\x314', - '\x315', '\a', 'p', '\x2', '\x2', '\x315', '\x316', '\a', 'k', '\x2', - '\x2', '\x316', '\x317', '\a', 'n', '\x2', '\x2', '\x317', '|', '\x3', - '\x2', '\x2', '\x2', '\x318', '\x319', '\a', 'v', '\x2', '\x2', '\x319', - '\x31A', '\a', 't', '\x2', '\x2', '\x31A', '\x31B', '\a', 'w', '\x2', - '\x2', '\x31B', '\x31C', '\a', 'g', '\x2', '\x2', '\x31C', '~', '\x3', - '\x2', '\x2', '\x2', '\x31D', '\x31E', '\a', 'h', '\x2', '\x2', '\x31E', - '\x31F', '\a', '\x63', '\x2', '\x2', '\x31F', '\x320', '\a', 'n', '\x2', - '\x2', '\x320', '\x321', '\a', 'u', '\x2', '\x2', '\x321', '\x322', '\a', - 'g', '\x2', '\x2', '\x322', '\x80', '\x3', '\x2', '\x2', '\x2', '\x323', - '\x324', '\a', 'y', '\x2', '\x2', '\x324', '\x325', '\a', 'j', '\x2', - '\x2', '\x325', '\x326', '\a', 'g', '\x2', '\x2', '\x326', '\x327', '\a', - 't', '\x2', '\x2', '\x327', '\x328', '\a', 'g', '\x2', '\x2', '\x328', - '\x82', '\x3', '\x2', '\x2', '\x2', '\x329', '\x32A', '\a', '@', '\x2', - '\x2', '\x32A', '\x84', '\x3', '\x2', '\x2', '\x2', '\x32B', '\x32C', - '\a', '/', '\x2', '\x2', '\x32C', '\x32D', '\a', '@', '\x2', '\x2', '\x32D', - '\x86', '\x3', '\x2', '\x2', '\x2', '\x32E', '\x32F', '\a', '\x30', '\x2', - '\x2', '\x32F', '\x330', '\a', '\x30', '\x2', '\x2', '\x330', '\x331', - '\a', '\x30', '\x2', '\x2', '\x331', '\x88', '\x3', '\x2', '\x2', '\x2', - '\x332', '\x333', '\a', '\x63', '\x2', '\x2', '\x333', '\x334', '\a', - 'n', '\x2', '\x2', '\x334', '\x335', '\a', 'r', '\x2', '\x2', '\x335', - '\x336', '\a', 'j', '\x2', '\x2', '\x336', '\x337', '\a', '\x63', '\x2', - '\x2', '\x337', '\x8A', '\x3', '\x2', '\x2', '\x2', '\x338', '\x339', - '\a', '\x63', '\x2', '\x2', '\x339', '\x33A', '\a', 't', '\x2', '\x2', - '\x33A', '\x33B', '\a', '\x65', '\x2', '\x2', '\x33B', '\x33C', '\a', - 'j', '\x2', '\x2', '\x33C', '\x8C', '\x3', '\x2', '\x2', '\x2', '\x33D', - '\x33E', '\a', '\x63', '\x2', '\x2', '\x33E', '\x33F', '\a', 't', '\x2', - '\x2', '\x33F', '\x340', '\a', 'o', '\x2', '\x2', '\x340', '\x8E', '\x3', - '\x2', '\x2', '\x2', '\x341', '\x342', '\a', '\x63', '\x2', '\x2', '\x342', - '\x343', '\a', 't', '\x2', '\x2', '\x343', '\x344', '\a', 'o', '\x2', - '\x2', '\x344', '\x345', '\a', '\x38', '\x2', '\x2', '\x345', '\x346', - '\a', '\x36', '\x2', '\x2', '\x346', '\x90', '\x3', '\x2', '\x2', '\x2', - '\x347', '\x348', '\a', '\x64', '\x2', '\x2', '\x348', '\x349', '\a', - 'n', '\x2', '\x2', '\x349', '\x34A', '\a', 'w', '\x2', '\x2', '\x34A', - '\x34B', '\a', 'g', '\x2', '\x2', '\x34B', '\x92', '\x3', '\x2', '\x2', - '\x2', '\x34C', '\x34D', '\a', '\x66', '\x2', '\x2', '\x34D', '\x34E', - '\a', 'k', '\x2', '\x2', '\x34E', '\x34F', '\a', '\x66', '\x2', '\x2', - '\x34F', '\x350', '\a', 'U', '\x2', '\x2', '\x350', '\x351', '\a', 'g', - '\x2', '\x2', '\x351', '\x352', '\a', 'v', '\x2', '\x2', '\x352', '\x94', - '\x3', '\x2', '\x2', '\x2', '\x353', '\x354', '\a', 'h', '\x2', '\x2', - '\x354', '\x355', '\a', 'k', '\x2', '\x2', '\x355', '\x356', '\a', 'n', - '\x2', '\x2', '\x356', '\x357', '\a', 'g', '\x2', '\x2', '\x357', '\x96', - '\x3', '\x2', '\x2', '\x2', '\x358', '\x359', '\a', 'i', '\x2', '\x2', - '\x359', '\x35A', '\a', 't', '\x2', '\x2', '\x35A', '\x35B', '\a', 'g', - '\x2', '\x2', '\x35B', '\x35C', '\a', 'g', '\x2', '\x2', '\x35C', '\x35D', - '\a', 'p', '\x2', '\x2', '\x35D', '\x98', '\x3', '\x2', '\x2', '\x2', - '\x35E', '\x35F', '\a', 'k', '\x2', '\x2', '\x35F', '\x360', '\a', '\x35', - '\x2', '\x2', '\x360', '\x361', '\a', ':', '\x2', '\x2', '\x361', '\x362', - '\a', '\x38', '\x2', '\x2', '\x362', '\x9A', '\x3', '\x2', '\x2', '\x2', - '\x363', '\x364', '\a', 'k', '\x2', '\x2', '\x364', '\x365', '\a', 'Q', - '\x2', '\x2', '\x365', '\x366', '\a', 'U', '\x2', '\x2', '\x366', '\x9C', - '\x3', '\x2', '\x2', '\x2', '\x367', '\x368', '\a', 'k', '\x2', '\x2', - '\x368', '\x369', '\a', 'Q', '\x2', '\x2', '\x369', '\x36A', '\a', 'U', - '\x2', '\x2', '\x36A', '\x36B', '\a', '\x43', '\x2', '\x2', '\x36B', '\x36C', - '\a', 'r', '\x2', '\x2', '\x36C', '\x36D', '\a', 'r', '\x2', '\x2', '\x36D', - '\x36E', '\a', 'n', '\x2', '\x2', '\x36E', '\x36F', '\a', 'k', '\x2', - '\x2', '\x36F', '\x370', '\a', '\x65', '\x2', '\x2', '\x370', '\x371', - '\a', '\x63', '\x2', '\x2', '\x371', '\x372', '\a', 'v', '\x2', '\x2', - '\x372', '\x373', '\a', 'k', '\x2', '\x2', '\x373', '\x374', '\a', 'q', - '\x2', '\x2', '\x374', '\x375', '\a', 'p', '\x2', '\x2', '\x375', '\x376', - '\a', 'G', '\x2', '\x2', '\x376', '\x377', '\a', 'z', '\x2', '\x2', '\x377', - '\x378', '\a', 'v', '\x2', '\x2', '\x378', '\x379', '\a', 'g', '\x2', - '\x2', '\x379', '\x37A', '\a', 'p', '\x2', '\x2', '\x37A', '\x37B', '\a', - 'u', '\x2', '\x2', '\x37B', '\x37C', '\a', 'k', '\x2', '\x2', '\x37C', - '\x37D', '\a', 'q', '\x2', '\x2', '\x37D', '\x37E', '\a', 'p', '\x2', - '\x2', '\x37E', '\x9E', '\x3', '\x2', '\x2', '\x2', '\x37F', '\x380', - '\a', 'n', '\x2', '\x2', '\x380', '\x381', '\a', 'k', '\x2', '\x2', '\x381', - '\x382', '\a', 'p', '\x2', '\x2', '\x382', '\x383', '\a', 'g', '\x2', - '\x2', '\x383', '\xA0', '\x3', '\x2', '\x2', '\x2', '\x384', '\x385', - '\a', 'o', '\x2', '\x2', '\x385', '\x386', '\a', '\x63', '\x2', '\x2', - '\x386', '\x387', '\a', '\x65', '\x2', '\x2', '\x387', '\x388', '\a', - 'Q', '\x2', '\x2', '\x388', '\x389', '\a', 'U', '\x2', '\x2', '\x389', - '\xA2', '\x3', '\x2', '\x2', '\x2', '\x38A', '\x38B', '\a', 'o', '\x2', - '\x2', '\x38B', '\x38C', '\a', '\x63', '\x2', '\x2', '\x38C', '\x38D', - '\a', '\x65', '\x2', '\x2', '\x38D', '\x38E', '\a', 'Q', '\x2', '\x2', - '\x38E', '\x38F', '\a', 'U', '\x2', '\x2', '\x38F', '\x390', '\a', '\x43', - '\x2', '\x2', '\x390', '\x391', '\a', 'r', '\x2', '\x2', '\x391', '\x392', - '\a', 'r', '\x2', '\x2', '\x392', '\x393', '\a', 'n', '\x2', '\x2', '\x393', - '\x394', '\a', 'k', '\x2', '\x2', '\x394', '\x395', '\a', '\x65', '\x2', - '\x2', '\x395', '\x396', '\a', '\x63', '\x2', '\x2', '\x396', '\x397', - '\a', 'v', '\x2', '\x2', '\x397', '\x398', '\a', 'k', '\x2', '\x2', '\x398', - '\x399', '\a', 'q', '\x2', '\x2', '\x399', '\x39A', '\a', 'p', '\x2', - '\x2', '\x39A', '\x39B', '\a', 'G', '\x2', '\x2', '\x39B', '\x39C', '\a', - 'z', '\x2', '\x2', '\x39C', '\x39D', '\a', 'v', '\x2', '\x2', '\x39D', - '\x39E', '\a', 'g', '\x2', '\x2', '\x39E', '\x39F', '\a', 'p', '\x2', - '\x2', '\x39F', '\x3A0', '\a', 'u', '\x2', '\x2', '\x3A0', '\x3A1', '\a', - 'k', '\x2', '\x2', '\x3A1', '\x3A2', '\a', 'q', '\x2', '\x2', '\x3A2', - '\x3A3', '\a', 'p', '\x2', '\x2', '\x3A3', '\xA4', '\x3', '\x2', '\x2', - '\x2', '\x3A4', '\x3A5', '\a', 'q', '\x2', '\x2', '\x3A5', '\x3A6', '\a', - 'h', '\x2', '\x2', '\x3A6', '\xA6', '\x3', '\x2', '\x2', '\x2', '\x3A7', - '\x3A8', '\a', 'q', '\x2', '\x2', '\x3A8', '\x3A9', '\a', 'u', '\x2', - '\x2', '\x3A9', '\xA8', '\x3', '\x2', '\x2', '\x2', '\x3AA', '\x3AB', - '\a', 'r', '\x2', '\x2', '\x3AB', '\x3AC', '\a', 't', '\x2', '\x2', '\x3AC', - '\x3AD', '\a', 'g', '\x2', '\x2', '\x3AD', '\x3AE', '\a', '\x65', '\x2', - '\x2', '\x3AE', '\x3AF', '\a', 'g', '\x2', '\x2', '\x3AF', '\x3B0', '\a', - '\x66', '\x2', '\x2', '\x3B0', '\x3B1', '\a', 'g', '\x2', '\x2', '\x3B1', - '\x3B2', '\a', 'p', '\x2', '\x2', '\x3B2', '\x3B3', '\a', '\x65', '\x2', - '\x2', '\x3B3', '\x3B4', '\a', 'g', '\x2', '\x2', '\x3B4', '\xAA', '\x3', - '\x2', '\x2', '\x2', '\x3B5', '\x3B6', '\a', 't', '\x2', '\x2', '\x3B6', - '\x3B7', '\a', 'g', '\x2', '\x2', '\x3B7', '\x3B8', '\a', '\x66', '\x2', - '\x2', '\x3B8', '\xAC', '\x3', '\x2', '\x2', '\x2', '\x3B9', '\x3BA', - '\a', 't', '\x2', '\x2', '\x3BA', '\x3BB', '\a', 'g', '\x2', '\x2', '\x3BB', - '\x3BC', '\a', 'u', '\x2', '\x2', '\x3BC', '\x3BD', '\a', 'q', '\x2', - '\x2', '\x3BD', '\x3BE', '\a', 'w', '\x2', '\x2', '\x3BE', '\x3BF', '\a', - 't', '\x2', '\x2', '\x3BF', '\x3C0', '\a', '\x65', '\x2', '\x2', '\x3C0', - '\x3C1', '\a', 'g', '\x2', '\x2', '\x3C1', '\x3C2', '\a', 'P', '\x2', - '\x2', '\x3C2', '\x3C3', '\a', '\x63', '\x2', '\x2', '\x3C3', '\x3C4', - '\a', 'o', '\x2', '\x2', '\x3C4', '\x3C5', '\a', 'g', '\x2', '\x2', '\x3C5', - '\xAE', '\x3', '\x2', '\x2', '\x2', '\x3C6', '\x3C7', '\a', 'u', '\x2', - '\x2', '\x3C7', '\x3C8', '\a', 'y', '\x2', '\x2', '\x3C8', '\x3C9', '\a', - 'k', '\x2', '\x2', '\x3C9', '\x3CA', '\a', 'h', '\x2', '\x2', '\x3CA', - '\x3CB', '\a', 'v', '\x2', '\x2', '\x3CB', '\xB0', '\x3', '\x2', '\x2', - '\x2', '\x3CC', '\x3CD', '\a', 'v', '\x2', '\x2', '\x3CD', '\x3CE', '\a', - 'x', '\x2', '\x2', '\x3CE', '\x3CF', '\a', 'Q', '\x2', '\x2', '\x3CF', - '\x3D0', '\a', 'U', '\x2', '\x2', '\x3D0', '\xB2', '\x3', '\x2', '\x2', - '\x2', '\x3D1', '\x3D2', '\a', 'v', '\x2', '\x2', '\x3D2', '\x3D3', '\a', - '{', '\x2', '\x2', '\x3D3', '\x3D4', '\a', 'r', '\x2', '\x2', '\x3D4', - '\x3D5', '\a', 'g', '\x2', '\x2', '\x3D5', '\xB4', '\x3', '\x2', '\x2', - '\x2', '\x3D6', '\x3D7', '\a', 'y', '\x2', '\x2', '\x3D7', '\x3D8', '\a', - '\x63', '\x2', '\x2', '\x3D8', '\x3D9', '\a', 'v', '\x2', '\x2', '\x3D9', - '\x3DA', '\a', '\x65', '\x2', '\x2', '\x3DA', '\x3DB', '\a', 'j', '\x2', - '\x2', '\x3DB', '\x3DC', '\a', 'Q', '\x2', '\x2', '\x3DC', '\x3DD', '\a', - 'U', '\x2', '\x2', '\x3DD', '\xB6', '\x3', '\x2', '\x2', '\x2', '\x3DE', - '\x3DF', '\a', 'y', '\x2', '\x2', '\x3DF', '\x3E0', '\a', 'k', '\x2', - '\x2', '\x3E0', '\x3E1', '\a', 'n', '\x2', '\x2', '\x3E1', '\x3E2', '\a', - 'n', '\x2', '\x2', '\x3E2', '\x3E3', '\a', 'U', '\x2', '\x2', '\x3E3', - '\x3E4', '\a', 'g', '\x2', '\x2', '\x3E4', '\x3E5', '\a', 'v', '\x2', - '\x2', '\x3E5', '\xB8', '\x3', '\x2', '\x2', '\x2', '\x3E6', '\x3E7', - '\a', 'z', '\x2', '\x2', '\x3E7', '\x3E8', '\a', ':', '\x2', '\x2', '\x3E8', - '\x3E9', '\a', '\x38', '\x2', '\x2', '\x3E9', '\x3EA', '\a', '\x61', '\x2', - '\x2', '\x3EA', '\x3EB', '\a', '\x38', '\x2', '\x2', '\x3EB', '\x3EC', - '\a', '\x36', '\x2', '\x2', '\x3EC', '\xBA', '\x3', '\x2', '\x2', '\x2', - '\x3ED', '\x3EE', '\a', '\x64', '\x2', '\x2', '\x3EE', '\x3EF', '\a', - 't', '\x2', '\x2', '\x3EF', '\x3F0', '\a', 'g', '\x2', '\x2', '\x3F0', - '\x3F1', '\a', '\x63', '\x2', '\x2', '\x3F1', '\x3F2', '\a', 'm', '\x2', - '\x2', '\x3F2', '\xBC', '\x3', '\x2', '\x2', '\x2', '\x3F3', '\x3F4', - '\a', '\x65', '\x2', '\x2', '\x3F4', '\x3F5', '\a', '\x63', '\x2', '\x2', - '\x3F5', '\x3F6', '\a', 'v', '\x2', '\x2', '\x3F6', '\x3F7', '\a', '\x65', - '\x2', '\x2', '\x3F7', '\x3F8', '\a', 'j', '\x2', '\x2', '\x3F8', '\xBE', - '\x3', '\x2', '\x2', '\x2', '\x3F9', '\x3FA', '\a', '\x65', '\x2', '\x2', - '\x3FA', '\x3FB', '\a', 'q', '\x2', '\x2', '\x3FB', '\x3FC', '\a', 'p', - '\x2', '\x2', '\x3FC', '\x3FD', '\a', 'v', '\x2', '\x2', '\x3FD', '\x3FE', - '\a', 'k', '\x2', '\x2', '\x3FE', '\x3FF', '\a', 'p', '\x2', '\x2', '\x3FF', - '\x400', '\a', 'w', '\x2', '\x2', '\x400', '\x401', '\a', 'g', '\x2', - '\x2', '\x401', '\xC0', '\x3', '\x2', '\x2', '\x2', '\x402', '\x403', - '\a', '\x66', '\x2', '\x2', '\x403', '\x404', '\a', 'g', '\x2', '\x2', - '\x404', '\x405', '\a', 'h', '\x2', '\x2', '\x405', '\x406', '\a', '\x63', - '\x2', '\x2', '\x406', '\x407', '\a', 'w', '\x2', '\x2', '\x407', '\x408', - '\a', 'n', '\x2', '\x2', '\x408', '\x409', '\a', 'v', '\x2', '\x2', '\x409', - '\xC2', '\x3', '\x2', '\x2', '\x2', '\x40A', '\x40B', '\a', '\x66', '\x2', - '\x2', '\x40B', '\x40C', '\a', 'g', '\x2', '\x2', '\x40C', '\x40D', '\a', - 'h', '\x2', '\x2', '\x40D', '\x40E', '\a', 'g', '\x2', '\x2', '\x40E', - '\x40F', '\a', 't', '\x2', '\x2', '\x40F', '\xC4', '\x3', '\x2', '\x2', - '\x2', '\x410', '\x411', '\a', '\x66', '\x2', '\x2', '\x411', '\x412', - '\a', 'q', '\x2', '\x2', '\x412', '\xC6', '\x3', '\x2', '\x2', '\x2', - '\x413', '\x414', '\a', 'g', '\x2', '\x2', '\x414', '\x415', '\a', 'n', - '\x2', '\x2', '\x415', '\x416', '\a', 'u', '\x2', '\x2', '\x416', '\x417', - '\a', 'g', '\x2', '\x2', '\x417', '\xC8', '\x3', '\x2', '\x2', '\x2', - '\x418', '\x419', '\a', 'h', '\x2', '\x2', '\x419', '\x41A', '\a', '\x63', - '\x2', '\x2', '\x41A', '\x41B', '\a', 'n', '\x2', '\x2', '\x41B', '\x41C', - '\a', 'n', '\x2', '\x2', '\x41C', '\x41D', '\a', 'v', '\x2', '\x2', '\x41D', - '\x41E', '\a', 'j', '\x2', '\x2', '\x41E', '\x41F', '\a', 't', '\x2', - '\x2', '\x41F', '\x420', '\a', 'q', '\x2', '\x2', '\x420', '\x421', '\a', - 'w', '\x2', '\x2', '\x421', '\x422', '\a', 'i', '\x2', '\x2', '\x422', - '\x423', '\a', 'j', '\x2', '\x2', '\x423', '\xCA', '\x3', '\x2', '\x2', - '\x2', '\x424', '\x425', '\a', 'h', '\x2', '\x2', '\x425', '\x426', '\a', - 'q', '\x2', '\x2', '\x426', '\x427', '\a', 't', '\x2', '\x2', '\x427', - '\xCC', '\x3', '\x2', '\x2', '\x2', '\x428', '\x429', '\a', 'i', '\x2', - '\x2', '\x429', '\x42A', '\a', 'w', '\x2', '\x2', '\x42A', '\x42B', '\a', - '\x63', '\x2', '\x2', '\x42B', '\x42C', '\a', 't', '\x2', '\x2', '\x42C', - '\x42D', '\a', '\x66', '\x2', '\x2', '\x42D', '\xCE', '\x3', '\x2', '\x2', - '\x2', '\x42E', '\x42F', '\a', 'k', '\x2', '\x2', '\x42F', '\x430', '\a', - 'h', '\x2', '\x2', '\x430', '\xD0', '\x3', '\x2', '\x2', '\x2', '\x431', - '\x432', '\a', 'k', '\x2', '\x2', '\x432', '\x433', '\a', 'p', '\x2', - '\x2', '\x433', '\xD2', '\x3', '\x2', '\x2', '\x2', '\x434', '\x435', - '\a', 't', '\x2', '\x2', '\x435', '\x436', '\a', 'g', '\x2', '\x2', '\x436', - '\x437', '\a', 'r', '\x2', '\x2', '\x437', '\x438', '\a', 'g', '\x2', - '\x2', '\x438', '\x439', '\a', '\x63', '\x2', '\x2', '\x439', '\x43A', - '\a', 'v', '\x2', '\x2', '\x43A', '\xD4', '\x3', '\x2', '\x2', '\x2', - '\x43B', '\x43C', '\a', 't', '\x2', '\x2', '\x43C', '\x43D', '\a', 'g', - '\x2', '\x2', '\x43D', '\x43E', '\a', 'v', '\x2', '\x2', '\x43E', '\x43F', - '\a', 'w', '\x2', '\x2', '\x43F', '\x440', '\a', 't', '\x2', '\x2', '\x440', - '\x441', '\a', 'p', '\x2', '\x2', '\x441', '\xD6', '\x3', '\x2', '\x2', - '\x2', '\x442', '\x443', '\a', 'u', '\x2', '\x2', '\x443', '\x444', '\a', - 'g', '\x2', '\x2', '\x444', '\x445', '\a', 'n', '\x2', '\x2', '\x445', - '\x446', '\a', 'h', '\x2', '\x2', '\x446', '\xD8', '\x3', '\x2', '\x2', - '\x2', '\x447', '\x448', '\a', 'u', '\x2', '\x2', '\x448', '\x449', '\a', - 'w', '\x2', '\x2', '\x449', '\x44A', '\a', 'r', '\x2', '\x2', '\x44A', - '\x44B', '\a', 'g', '\x2', '\x2', '\x44B', '\x44C', '\a', 't', '\x2', - '\x2', '\x44C', '\xDA', '\x3', '\x2', '\x2', '\x2', '\x44D', '\x44E', - '\a', 'u', '\x2', '\x2', '\x44E', '\x44F', '\a', 'y', '\x2', '\x2', '\x44F', - '\x450', '\a', 'k', '\x2', '\x2', '\x450', '\x451', '\a', 'v', '\x2', - '\x2', '\x451', '\x452', '\a', '\x65', '\x2', '\x2', '\x452', '\x453', - '\a', 'j', '\x2', '\x2', '\x453', '\xDC', '\x3', '\x2', '\x2', '\x2', - '\x454', '\x455', '\a', 'v', '\x2', '\x2', '\x455', '\x456', '\a', 'j', - '\x2', '\x2', '\x456', '\x457', '\a', 't', '\x2', '\x2', '\x457', '\x458', - '\a', 'q', '\x2', '\x2', '\x458', '\x459', '\a', 'y', '\x2', '\x2', '\x459', - '\xDE', '\x3', '\x2', '\x2', '\x2', '\x45A', '\x45B', '\a', 'v', '\x2', - '\x2', '\x45B', '\x45C', '\a', 't', '\x2', '\x2', '\x45C', '\x45D', '\a', - '{', '\x2', '\x2', '\x45D', '\xE0', '\x3', '\x2', '\x2', '\x2', '\x45E', - '\x45F', '\a', 'y', '\x2', '\x2', '\x45F', '\x460', '\a', 'j', '\x2', - '\x2', '\x460', '\x461', '\a', 'k', '\x2', '\x2', '\x461', '\x462', '\a', - 'n', '\x2', '\x2', '\x462', '\x463', '\a', 'g', '\x2', '\x2', '\x463', - '\xE2', '\x3', '\x2', '\x2', '\x2', '\x464', '\x465', '\a', '\x32', '\x2', - '\x2', '\x465', '\x466', '\a', '\x64', '\x2', '\x2', '\x466', '\x467', - '\x3', '\x2', '\x2', '\x2', '\x467', '\x469', '\x5', '\xE5', 's', '\x2', - '\x468', '\x46A', '\x5', '\xE9', 'u', '\x2', '\x469', '\x468', '\x3', - '\x2', '\x2', '\x2', '\x469', '\x46A', '\x3', '\x2', '\x2', '\x2', '\x46A', - '\xE4', '\x3', '\x2', '\x2', '\x2', '\x46B', '\x46C', '\t', '\x2', '\x2', - '\x2', '\x46C', '\xE6', '\x3', '\x2', '\x2', '\x2', '\x46D', '\x470', - '\x5', '\xE5', 's', '\x2', '\x46E', '\x470', '\x5', '\x131', '\x99', '\x2', - '\x46F', '\x46D', '\x3', '\x2', '\x2', '\x2', '\x46F', '\x46E', '\x3', - '\x2', '\x2', '\x2', '\x470', '\xE8', '\x3', '\x2', '\x2', '\x2', '\x471', - '\x473', '\x5', '\xE7', 't', '\x2', '\x472', '\x471', '\x3', '\x2', '\x2', - '\x2', '\x473', '\x474', '\x3', '\x2', '\x2', '\x2', '\x474', '\x472', - '\x3', '\x2', '\x2', '\x2', '\x474', '\x475', '\x3', '\x2', '\x2', '\x2', - '\x475', '\xEA', '\x3', '\x2', '\x2', '\x2', '\x476', '\x477', '\a', '\x32', - '\x2', '\x2', '\x477', '\x478', '\a', 'q', '\x2', '\x2', '\x478', '\x479', - '\x3', '\x2', '\x2', '\x2', '\x479', '\x47B', '\x5', '\xED', 'w', '\x2', - '\x47A', '\x47C', '\x5', '\xF1', 'y', '\x2', '\x47B', '\x47A', '\x3', - '\x2', '\x2', '\x2', '\x47B', '\x47C', '\x3', '\x2', '\x2', '\x2', '\x47C', - '\xEC', '\x3', '\x2', '\x2', '\x2', '\x47D', '\x47E', '\t', '\x3', '\x2', - '\x2', '\x47E', '\xEE', '\x3', '\x2', '\x2', '\x2', '\x47F', '\x482', - '\x5', '\xED', 'w', '\x2', '\x480', '\x482', '\x5', '\x131', '\x99', '\x2', - '\x481', '\x47F', '\x3', '\x2', '\x2', '\x2', '\x481', '\x480', '\x3', - '\x2', '\x2', '\x2', '\x482', '\xF0', '\x3', '\x2', '\x2', '\x2', '\x483', - '\x485', '\x5', '\xEF', 'x', '\x2', '\x484', '\x483', '\x3', '\x2', '\x2', - '\x2', '\x485', '\x486', '\x3', '\x2', '\x2', '\x2', '\x486', '\x484', - '\x3', '\x2', '\x2', '\x2', '\x486', '\x487', '\x3', '\x2', '\x2', '\x2', - '\x487', '\xF2', '\x3', '\x2', '\x2', '\x2', '\x488', '\x48C', '\t', '\x4', - '\x2', '\x2', '\x489', '\x48B', '\t', '\x5', '\x2', '\x2', '\x48A', '\x489', - '\x3', '\x2', '\x2', '\x2', '\x48B', '\x48E', '\x3', '\x2', '\x2', '\x2', - '\x48C', '\x48A', '\x3', '\x2', '\x2', '\x2', '\x48C', '\x48D', '\x3', - '\x2', '\x2', '\x2', '\x48D', '\xF4', '\x3', '\x2', '\x2', '\x2', '\x48E', - '\x48C', '\x3', '\x2', '\x2', '\x2', '\x48F', '\x491', '\t', '\x4', '\x2', - '\x2', '\x490', '\x48F', '\x3', '\x2', '\x2', '\x2', '\x491', '\x492', - '\x3', '\x2', '\x2', '\x2', '\x492', '\x490', '\x3', '\x2', '\x2', '\x2', - '\x492', '\x493', '\x3', '\x2', '\x2', '\x2', '\x493', '\xF6', '\x3', - '\x2', '\x2', '\x2', '\x494', '\x495', '\a', '\x32', '\x2', '\x2', '\x495', - '\x496', '\a', 'z', '\x2', '\x2', '\x496', '\x497', '\x3', '\x2', '\x2', - '\x2', '\x497', '\x499', '\x5', '\xF9', '}', '\x2', '\x498', '\x49A', - '\x5', '\xFD', '\x7F', '\x2', '\x499', '\x498', '\x3', '\x2', '\x2', '\x2', - '\x499', '\x49A', '\x3', '\x2', '\x2', '\x2', '\x49A', '\xF8', '\x3', - '\x2', '\x2', '\x2', '\x49B', '\x49C', '\t', '\x3', '\x2', '\x2', '\x49C', - '\xFA', '\x3', '\x2', '\x2', '\x2', '\x49D', '\x4A0', '\x5', '\xF9', '}', - '\x2', '\x49E', '\x4A0', '\x5', '\x131', '\x99', '\x2', '\x49F', '\x49D', - '\x3', '\x2', '\x2', '\x2', '\x49F', '\x49E', '\x3', '\x2', '\x2', '\x2', - '\x4A0', '\xFC', '\x3', '\x2', '\x2', '\x2', '\x4A1', '\x4A3', '\x5', - '\xFB', '~', '\x2', '\x4A2', '\x4A1', '\x3', '\x2', '\x2', '\x2', '\x4A3', - '\x4A4', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A2', '\x3', '\x2', '\x2', - '\x2', '\x4A4', '\x4A5', '\x3', '\x2', '\x2', '\x2', '\x4A5', '\xFE', - '\x3', '\x2', '\x2', '\x2', '\x4A6', '\x4A8', '\a', '$', '\x2', '\x2', - '\x4A7', '\x4A9', '\x5', '\x101', '\x81', '\x2', '\x4A8', '\x4A7', '\x3', - '\x2', '\x2', '\x2', '\x4A8', '\x4A9', '\x3', '\x2', '\x2', '\x2', '\x4A9', - '\x4AA', '\x3', '\x2', '\x2', '\x2', '\x4AA', '\x4AB', '\a', '$', '\x2', - '\x2', '\x4AB', '\x100', '\x3', '\x2', '\x2', '\x2', '\x4AC', '\x4AE', - '\x5', '\x103', '\x82', '\x2', '\x4AD', '\x4AC', '\x3', '\x2', '\x2', - '\x2', '\x4AE', '\x4AF', '\x3', '\x2', '\x2', '\x2', '\x4AF', '\x4AD', - '\x3', '\x2', '\x2', '\x2', '\x4AF', '\x4B0', '\x3', '\x2', '\x2', '\x2', - '\x4B0', '\x102', '\x3', '\x2', '\x2', '\x2', '\x4B1', '\x4B4', '\x5', - '\x105', '\x83', '\x2', '\x4B2', '\x4B4', '\n', '\x6', '\x2', '\x2', '\x4B3', - '\x4B1', '\x3', '\x2', '\x2', '\x2', '\x4B3', '\x4B2', '\x3', '\x2', '\x2', - '\x2', '\x4B4', '\x104', '\x3', '\x2', '\x2', '\x2', '\x4B5', '\x4B6', - '\a', '^', '\x2', '\x2', '\x4B6', '\x4D6', '\t', '\a', '\x2', '\x2', '\x4B7', - '\x4B8', '\a', '^', '\x2', '\x2', '\x4B8', '\x4B9', '\a', 'z', '\x2', - '\x2', '\x4B9', '\x4BA', '\x3', '\x2', '\x2', '\x2', '\x4BA', '\x4BB', - '\x5', '\xF9', '}', '\x2', '\x4BB', '\x4BC', '\x5', '\xF9', '}', '\x2', - '\x4BC', '\x4D6', '\x3', '\x2', '\x2', '\x2', '\x4BD', '\x4BE', '\a', - '^', '\x2', '\x2', '\x4BE', '\x4BF', '\a', 'w', '\x2', '\x2', '\x4BF', - '\x4C0', '\x3', '\x2', '\x2', '\x2', '\x4C0', '\x4C1', '\x5', '\x13B', - '\x9E', '\x2', '\x4C1', '\x4C2', '\x5', '\xF9', '}', '\x2', '\x4C2', '\x4C3', - '\x5', '\xF9', '}', '\x2', '\x4C3', '\x4C4', '\x5', '\xF9', '}', '\x2', - '\x4C4', '\x4C5', '\x5', '\xF9', '}', '\x2', '\x4C5', '\x4C6', '\x5', - '\x13D', '\x9F', '\x2', '\x4C6', '\x4D6', '\x3', '\x2', '\x2', '\x2', - '\x4C7', '\x4C8', '\a', '^', '\x2', '\x2', '\x4C8', '\x4C9', '\a', 'w', - '\x2', '\x2', '\x4C9', '\x4CA', '\x3', '\x2', '\x2', '\x2', '\x4CA', '\x4CB', - '\x5', '\x13B', '\x9E', '\x2', '\x4CB', '\x4CC', '\x5', '\xF9', '}', '\x2', - '\x4CC', '\x4CD', '\x5', '\xF9', '}', '\x2', '\x4CD', '\x4CE', '\x5', - '\xF9', '}', '\x2', '\x4CE', '\x4CF', '\x5', '\xF9', '}', '\x2', '\x4CF', - '\x4D0', '\x5', '\xF9', '}', '\x2', '\x4D0', '\x4D1', '\x5', '\xF9', '}', - '\x2', '\x4D1', '\x4D2', '\x5', '\xF9', '}', '\x2', '\x4D2', '\x4D3', - '\x5', '\xF9', '}', '\x2', '\x4D3', '\x4D4', '\x5', '\x13D', '\x9F', '\x2', - '\x4D4', '\x4D6', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4B5', '\x3', - '\x2', '\x2', '\x2', '\x4D5', '\x4B7', '\x3', '\x2', '\x2', '\x2', '\x4D5', - '\x4BD', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4C7', '\x3', '\x2', '\x2', - '\x2', '\x4D6', '\x106', '\x3', '\x2', '\x2', '\x2', '\x4D7', '\x4D9', - '\x5', '\x109', '\x85', '\x2', '\x4D8', '\x4DA', '\x5', '\x10D', '\x87', - '\x2', '\x4D9', '\x4D8', '\x3', '\x2', '\x2', '\x2', '\x4D9', '\x4DA', - '\x3', '\x2', '\x2', '\x2', '\x4DA', '\x4E4', '\x3', '\x2', '\x2', '\x2', - '\x4DB', '\x4DC', '\x5', '\x12F', '\x98', '\x2', '\x4DC', '\x4DE', '\x5', - '\x109', '\x85', '\x2', '\x4DD', '\x4DF', '\x5', '\x10D', '\x87', '\x2', - '\x4DE', '\x4DD', '\x3', '\x2', '\x2', '\x2', '\x4DE', '\x4DF', '\x3', - '\x2', '\x2', '\x2', '\x4DF', '\x4E0', '\x3', '\x2', '\x2', '\x2', '\x4E0', - '\x4E1', '\x5', '\x12F', '\x98', '\x2', '\x4E1', '\x4E4', '\x3', '\x2', - '\x2', '\x2', '\x4E2', '\x4E4', '\x5', '\x10F', '\x88', '\x2', '\x4E3', - '\x4D7', '\x3', '\x2', '\x2', '\x2', '\x4E3', '\x4DB', '\x3', '\x2', '\x2', - '\x2', '\x4E3', '\x4E2', '\x3', '\x2', '\x2', '\x2', '\x4E4', '\x108', - '\x3', '\x2', '\x2', '\x2', '\x4E5', '\x4E7', '\t', '\r', '\x2', '\x2', - '\x4E6', '\x4E5', '\x3', '\x2', '\x2', '\x2', '\x4E7', '\x10A', '\x3', - '\x2', '\x2', '\x2', '\x4E8', '\x4EB', '\t', '\b', '\x2', '\x2', '\x4E9', - '\x4EB', '\x5', '\x109', '\x85', '\x2', '\x4EA', '\x4E8', '\x3', '\x2', - '\x2', '\x2', '\x4EA', '\x4E9', '\x3', '\x2', '\x2', '\x2', '\x4EB', '\x10C', - '\x3', '\x2', '\x2', '\x2', '\x4EC', '\x4EE', '\x5', '\x10B', '\x86', - '\x2', '\x4ED', '\x4EC', '\x3', '\x2', '\x2', '\x2', '\x4EE', '\x4EF', - '\x3', '\x2', '\x2', '\x2', '\x4EF', '\x4ED', '\x3', '\x2', '\x2', '\x2', - '\x4EF', '\x4F0', '\x3', '\x2', '\x2', '\x2', '\x4F0', '\x10E', '\x3', - '\x2', '\x2', '\x2', '\x4F1', '\x4F2', '\a', '&', '\x2', '\x2', '\x4F2', - '\x4F3', '\x5', '\x13F', '\xA0', '\x2', '\x4F3', '\x110', '\x3', '\x2', - '\x2', '\x2', '\x4F4', '\x4F6', '\t', '\t', '\x2', '\x2', '\x4F5', '\x4F4', - '\x3', '\x2', '\x2', '\x2', '\x4F6', '\x4F7', '\x3', '\x2', '\x2', '\x2', - '\x4F7', '\x4F5', '\x3', '\x2', '\x2', '\x2', '\x4F7', '\x4F8', '\x3', - '\x2', '\x2', '\x2', '\x4F8', '\x4F9', '\x3', '\x2', '\x2', '\x2', '\x4F9', - '\x4FA', '\b', '\x89', '\x2', '\x2', '\x4FA', '\x112', '\x3', '\x2', '\x2', - '\x2', '\x4FB', '\x4FC', '\a', '-', '\x2', '\x2', '\x4FC', '\x114', '\x3', - '\x2', '\x2', '\x2', '\x4FD', '\x4FE', '\a', '/', '\x2', '\x2', '\x4FE', - '\x116', '\x3', '\x2', '\x2', '\x2', '\x4FF', '\x500', '\a', '?', '\x2', - '\x2', '\x500', '\x118', '\x3', '\x2', '\x2', '\x2', '\x501', '\x502', - '\a', '(', '\x2', '\x2', '\x502', '\x11A', '\x3', '\x2', '\x2', '\x2', - '\x503', '\x504', '\a', '\x41', '\x2', '\x2', '\x504', '\x11C', '\x3', - '\x2', '\x2', '\x2', '\x505', '\x506', '\a', '>', '\x2', '\x2', '\x506', - '\x11E', '\x3', '\x2', '\x2', '\x2', '\x507', '\x508', '\a', '#', '\x2', - '\x2', '\x508', '\x120', '\x3', '\x2', '\x2', '\x2', '\x509', '\x50A', - '\a', '\x30', '\x2', '\x2', '\x50A', '\x122', '\x3', '\x2', '\x2', '\x2', - '\x50B', '\x50C', '\a', '.', '\x2', '\x2', '\x50C', '\x124', '\x3', '\x2', - '\x2', '\x2', '\x50D', '\x50E', '\a', '\x80', '\x2', '\x2', '\x50E', '\x126', - '\x3', '\x2', '\x2', '\x2', '\x50F', '\x510', '\a', '<', '\x2', '\x2', - '\x510', '\x128', '\x3', '\x2', '\x2', '\x2', '\x511', '\x512', '\a', - '=', '\x2', '\x2', '\x512', '\x12A', '\x3', '\x2', '\x2', '\x2', '\x513', - '\x514', '\a', '\x42', '\x2', '\x2', '\x514', '\x12C', '\x3', '\x2', '\x2', - '\x2', '\x515', '\x516', '\a', '%', '\x2', '\x2', '\x516', '\x12E', '\x3', - '\x2', '\x2', '\x2', '\x517', '\x518', '\a', '\x62', '\x2', '\x2', '\x518', - '\x130', '\x3', '\x2', '\x2', '\x2', '\x519', '\x51A', '\a', '\x61', '\x2', - '\x2', '\x51A', '\x132', '\x3', '\x2', '\x2', '\x2', '\x51B', '\x51C', - '\a', '*', '\x2', '\x2', '\x51C', '\x134', '\x3', '\x2', '\x2', '\x2', - '\x51D', '\x51E', '\a', '+', '\x2', '\x2', '\x51E', '\x136', '\x3', '\x2', - '\x2', '\x2', '\x51F', '\x520', '\a', ']', '\x2', '\x2', '\x520', '\x138', - '\x3', '\x2', '\x2', '\x2', '\x521', '\x522', '\a', '_', '\x2', '\x2', - '\x522', '\x13A', '\x3', '\x2', '\x2', '\x2', '\x523', '\x524', '\a', - '}', '\x2', '\x2', '\x524', '\x13C', '\x3', '\x2', '\x2', '\x2', '\x525', - '\x526', '\a', '\x7F', '\x2', '\x2', '\x526', '\x13E', '\x3', '\x2', '\x2', - '\x2', '\x527', '\x529', '\t', '\x4', '\x2', '\x2', '\x528', '\x527', - '\x3', '\x2', '\x2', '\x2', '\x529', '\x52A', '\x3', '\x2', '\x2', '\x2', - '\x52A', '\x528', '\x3', '\x2', '\x2', '\x2', '\x52A', '\x52B', '\x3', - '\x2', '\x2', '\x2', '\x52B', '\x140', '\x3', '\x2', '\x2', '\x2', '\x52C', - '\x52E', '\x5', '\x145', '\xA3', '\x2', '\x52D', '\x52F', '\x5', '\x147', - '\xA4', '\x2', '\x52E', '\x52D', '\x3', '\x2', '\x2', '\x2', '\x52E', - '\x52F', '\x3', '\x2', '\x2', '\x2', '\x52F', '\x541', '\x3', '\x2', '\x2', - '\x2', '\x530', '\x531', '\x5', '\x143', '\xA2', '\x2', '\x531', '\x532', - '\x5', '\x149', '\xA5', '\x2', '\x532', '\x541', '\x3', '\x2', '\x2', - '\x2', '\x533', '\x534', '\x5', '\x143', '\xA2', '\x2', '\x534', '\x536', - '\x5', '\x149', '\xA5', '\x2', '\x535', '\x537', '\x5', '\x14B', '\xA6', - '\x2', '\x536', '\x535', '\x3', '\x2', '\x2', '\x2', '\x537', '\x538', - '\x3', '\x2', '\x2', '\x2', '\x538', '\x536', '\x3', '\x2', '\x2', '\x2', - '\x538', '\x539', '\x3', '\x2', '\x2', '\x2', '\x539', '\x541', '\x3', - '\x2', '\x2', '\x2', '\x53A', '\x53C', '\x5', '\x14D', '\xA7', '\x2', - '\x53B', '\x53D', '\x5', '\x14F', '\xA8', '\x2', '\x53C', '\x53B', '\x3', - '\x2', '\x2', '\x2', '\x53D', '\x53E', '\x3', '\x2', '\x2', '\x2', '\x53E', - '\x53C', '\x3', '\x2', '\x2', '\x2', '\x53E', '\x53F', '\x3', '\x2', '\x2', - '\x2', '\x53F', '\x541', '\x3', '\x2', '\x2', '\x2', '\x540', '\x52C', - '\x3', '\x2', '\x2', '\x2', '\x540', '\x530', '\x3', '\x2', '\x2', '\x2', - '\x540', '\x533', '\x3', '\x2', '\x2', '\x2', '\x540', '\x53A', '\x3', - '\x2', '\x2', '\x2', '\x541', '\x142', '\x3', '\x2', '\x2', '\x2', '\x542', - '\x544', '\t', '\n', '\x2', '\x2', '\x543', '\x542', '\x3', '\x2', '\x2', - '\x2', '\x544', '\x144', '\x3', '\x2', '\x2', '\x2', '\x545', '\x547', - '\t', '\v', '\x2', '\x2', '\x546', '\x545', '\x3', '\x2', '\x2', '\x2', - '\x547', '\x146', '\x3', '\x2', '\x2', '\x2', '\x548', '\x54A', '\x5', - '\x14B', '\xA6', '\x2', '\x549', '\x548', '\x3', '\x2', '\x2', '\x2', - '\x54A', '\x54B', '\x3', '\x2', '\x2', '\x2', '\x54B', '\x549', '\x3', - '\x2', '\x2', '\x2', '\x54B', '\x54C', '\x3', '\x2', '\x2', '\x2', '\x54C', - '\x148', '\x3', '\x2', '\x2', '\x2', '\x54D', '\x54F', '\t', '\xE', '\x2', - '\x2', '\x54E', '\x54D', '\x3', '\x2', '\x2', '\x2', '\x54F', '\x14A', - '\x3', '\x2', '\x2', '\x2', '\x550', '\x552', '\t', '\xF', '\x2', '\x2', - '\x551', '\x550', '\x3', '\x2', '\x2', '\x2', '\x552', '\x14C', '\x3', - '\x2', '\x2', '\x2', '\x553', '\x554', '\x5', '\x121', '\x91', '\x2', - '\x554', '\x14E', '\x3', '\x2', '\x2', '\x2', '\x555', '\x558', '\x5', - '\x145', '\xA3', '\x2', '\x556', '\x558', '\x5', '\x14B', '\xA6', '\x2', - '\x557', '\x555', '\x3', '\x2', '\x2', '\x2', '\x557', '\x556', '\x3', - '\x2', '\x2', '\x2', '\x558', '\x150', '\x3', '\x2', '\x2', '\x2', '\x559', - '\x55A', '\a', '?', '\x2', '\x2', '\x55A', '\x55B', '\a', '?', '\x2', - '\x2', '\x55B', '\x152', '\x3', '\x2', '\x2', '\x2', '\x55C', '\x55D', - '\a', '\x31', '\x2', '\x2', '\x55D', '\x55E', '\a', '\x31', '\x2', '\x2', - '\x55E', '\x562', '\x3', '\x2', '\x2', '\x2', '\x55F', '\x561', '\n', - '\f', '\x2', '\x2', '\x560', '\x55F', '\x3', '\x2', '\x2', '\x2', '\x561', - '\x564', '\x3', '\x2', '\x2', '\x2', '\x562', '\x560', '\x3', '\x2', '\x2', - '\x2', '\x562', '\x563', '\x3', '\x2', '\x2', '\x2', '\x563', '\x154', - '\x3', '\x2', '\x2', '\x2', '\x564', '\x562', '\x3', '\x2', '\x2', '\x2', - '%', '\x2', '\x469', '\x46F', '\x474', '\x47B', '\x481', '\x486', '\x48C', - '\x492', '\x499', '\x49F', '\x4A4', '\x4A8', '\x4AF', '\x4B3', '\x4D5', - '\x4D9', '\x4DE', '\x4E3', '\x4E6', '\x4EA', '\x4EF', '\x4F7', '\x52A', - '\x52E', '\x538', '\x53E', '\x540', '\x543', '\x546', '\x54B', '\x54E', - '\x551', '\x557', '\x562', '\x3', '\x2', '\x3', '\x2', - }; - - public static readonly ATN _ATN = - new ATNDeserializer().Deserialize(_serializedATN); - - -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs deleted file mode 100644 index cc5a5524278f..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceListener.cs +++ /dev/null @@ -1,1771 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// ANTLR Version: 4.9.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// Generated from SwiftInterface.g4 by ANTLR 4.9.1 - -// Unreachable code detected -#pragma warning disable 0162 -// The variable '...' is assigned but its value is never used -#pragma warning disable 0219 -// Missing XML comment for publicly visible type or member '...' -#pragma warning disable 1591 -// Ambiguous reference in cref attribute -#pragma warning disable 419 - -using Antlr4.Runtime.Misc; -using IParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener; -using IToken = Antlr4.Runtime.IToken; - -/// -/// This interface defines a complete listener for a parse tree produced by -/// . -/// -[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] -// [System.CLSCompliant(false)] -public interface ISwiftInterfaceListener : IParseTreeListener { - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSwiftinterface([NotNull] SwiftInterfaceParser.SwiftinterfaceContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterStatement([NotNull] SwiftInterfaceParser.StatementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitStatement([NotNull] SwiftInterfaceParser.StatementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterComment([NotNull] SwiftInterfaceParser.CommentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitComment([NotNull] SwiftInterfaceParser.CommentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDeclaration([NotNull] SwiftInterfaceParser.DeclarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitNominal_declaration([NotNull] SwiftInterfaceParser.Nominal_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitImport_statement([NotNull] SwiftInterfaceParser.Import_statementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitImport_kind([NotNull] SwiftInterfaceParser.Import_kindContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitImport_path([NotNull] SwiftInterfaceParser.Import_pathContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitImport_path_identifier([NotNull] SwiftInterfaceParser.Import_path_identifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitVariable_declaration([NotNull] SwiftInterfaceParser.Variable_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitVariable_declaration_head([NotNull] SwiftInterfaceParser.Variable_declaration_headContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitVariable_declaration_tail([NotNull] SwiftInterfaceParser.Variable_declaration_tailContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitVariable_name([NotNull] SwiftInterfaceParser.Variable_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitVar_clause([NotNull] SwiftInterfaceParser.Var_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitLet_clause([NotNull] SwiftInterfaceParser.Let_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGetter_setter_keyword_block([NotNull] SwiftInterfaceParser.Getter_setter_keyword_blockContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGetter_keyword_clause([NotNull] SwiftInterfaceParser.Getter_keyword_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSetter_keyword_clause([NotNull] SwiftInterfaceParser.Setter_keyword_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitNew_value_name([NotNull] SwiftInterfaceParser.New_value_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTypealias_declaration([NotNull] SwiftInterfaceParser.Typealias_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTypealias_name([NotNull] SwiftInterfaceParser.Typealias_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTypealias_assignment([NotNull] SwiftInterfaceParser.Typealias_assignmentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitEnum_declaration([NotNull] SwiftInterfaceParser.Enum_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum([NotNull] SwiftInterfaceParser.Union_style_enumContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum_members([NotNull] SwiftInterfaceParser.Union_style_enum_membersContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum_member([NotNull] SwiftInterfaceParser.Union_style_enum_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum_case_clause([NotNull] SwiftInterfaceParser.Union_style_enum_case_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum_case_list([NotNull] SwiftInterfaceParser.Union_style_enum_case_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitUnion_style_enum_case([NotNull] SwiftInterfaceParser.Union_style_enum_caseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitEnum_name([NotNull] SwiftInterfaceParser.Enum_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitEnum_case_name([NotNull] SwiftInterfaceParser.Enum_case_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum([NotNull] SwiftInterfaceParser.Raw_value_style_enumContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum_members([NotNull] SwiftInterfaceParser.Raw_value_style_enum_membersContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum_member([NotNull] SwiftInterfaceParser.Raw_value_style_enum_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum_case_clause([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum_case_list([NotNull] SwiftInterfaceParser.Raw_value_style_enum_case_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_style_enum_case([NotNull] SwiftInterfaceParser.Raw_value_style_enum_caseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_assignment([NotNull] SwiftInterfaceParser.Raw_value_assignmentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRaw_value_literal([NotNull] SwiftInterfaceParser.Raw_value_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitStruct_declaration([NotNull] SwiftInterfaceParser.Struct_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitStruct_name([NotNull] SwiftInterfaceParser.Struct_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitStruct_body([NotNull] SwiftInterfaceParser.Struct_bodyContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitStruct_member([NotNull] SwiftInterfaceParser.Struct_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitClass_declaration([NotNull] SwiftInterfaceParser.Class_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitClass_name([NotNull] SwiftInterfaceParser.Class_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitClass_body([NotNull] SwiftInterfaceParser.Class_bodyContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitClass_member([NotNull] SwiftInterfaceParser.Class_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFinal_clause([NotNull] SwiftInterfaceParser.Final_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_declaration([NotNull] SwiftInterfaceParser.Protocol_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_name([NotNull] SwiftInterfaceParser.Protocol_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_body([NotNull] SwiftInterfaceParser.Protocol_bodyContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_member([NotNull] SwiftInterfaceParser.Protocol_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_member_declaration([NotNull] SwiftInterfaceParser.Protocol_member_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitOperator_declaration([NotNull] SwiftInterfaceParser.Operator_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrefix_operator_declaration([NotNull] SwiftInterfaceParser.Prefix_operator_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPostfix_operator_declaration([NotNull] SwiftInterfaceParser.Postfix_operator_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInfix_operator_declaration([NotNull] SwiftInterfaceParser.Infix_operator_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInfix_operator_group([NotNull] SwiftInterfaceParser.Infix_operator_groupContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_declaration([NotNull] SwiftInterfaceParser.Precedence_group_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_attribute([NotNull] SwiftInterfaceParser.Precedence_group_attributeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_relation([NotNull] SwiftInterfaceParser.Precedence_group_relationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_assignment([NotNull] SwiftInterfaceParser.Precedence_group_assignmentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_associativity([NotNull] SwiftInterfaceParser.Precedence_group_associativityContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAssociativity([NotNull] SwiftInterfaceParser.AssociativityContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_names([NotNull] SwiftInterfaceParser.Precedence_group_namesContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPrecedence_group_name([NotNull] SwiftInterfaceParser.Precedence_group_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitExtension_declaration([NotNull] SwiftInterfaceParser.Extension_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitExtension_body([NotNull] SwiftInterfaceParser.Extension_bodyContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitExtension_member([NotNull] SwiftInterfaceParser.Extension_memberContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSubscript_declaration([NotNull] SwiftInterfaceParser.Subscript_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSubscript_head([NotNull] SwiftInterfaceParser.Subscript_headContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSubscript_result([NotNull] SwiftInterfaceParser.Subscript_resultContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_associated_type_declaration([NotNull] SwiftInterfaceParser.Protocol_associated_type_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_declaration([NotNull] SwiftInterfaceParser.Function_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_head([NotNull] SwiftInterfaceParser.Function_headContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_name([NotNull] SwiftInterfaceParser.Function_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_body([NotNull] SwiftInterfaceParser.Function_bodyContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitOperator_name([NotNull] SwiftInterfaceParser.Operator_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_signature([NotNull] SwiftInterfaceParser.Function_signatureContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAsync_clause([NotNull] SwiftInterfaceParser.Async_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitThrows_clause([NotNull] SwiftInterfaceParser.Throws_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRethrows_clause([NotNull] SwiftInterfaceParser.Rethrows_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_result([NotNull] SwiftInterfaceParser.Function_resultContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInitializer_declaration([NotNull] SwiftInterfaceParser.Initializer_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInitializer_head([NotNull] SwiftInterfaceParser.Initializer_headContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDeinitializer_declaration([NotNull] SwiftInterfaceParser.Deinitializer_declarationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitParameter_clause([NotNull] SwiftInterfaceParser.Parameter_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitParameter_list([NotNull] SwiftInterfaceParser.Parameter_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterParameter([NotNull] SwiftInterfaceParser.ParameterContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitParameter([NotNull] SwiftInterfaceParser.ParameterContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitExternal_parameter_name([NotNull] SwiftInterfaceParser.External_parameter_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitLocal_parameter_name([NotNull] SwiftInterfaceParser.Local_parameter_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDefaultInitializer([NotNull] SwiftInterfaceParser.DefaultInitializerContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDyckExpression([NotNull] SwiftInterfaceParser.DyckExpressionContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDyckSubExpression([NotNull] SwiftInterfaceParser.DyckSubExpressionContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAny_other_things_for_dyck_expression([NotNull] SwiftInterfaceParser.Any_other_things_for_dyck_expressionContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDotSymbol([NotNull] SwiftInterfaceParser.DotSymbolContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDeclaration_identifier([NotNull] SwiftInterfaceParser.Declaration_identifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitType_inheritance_clause([NotNull] SwiftInterfaceParser.Type_inheritance_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitType_inheritance_list([NotNull] SwiftInterfaceParser.Type_inheritance_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitClass_requirement([NotNull] SwiftInterfaceParser.Class_requirementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAttribute([NotNull] SwiftInterfaceParser.AttributeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAttribute([NotNull] SwiftInterfaceParser.AttributeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAttribute_name([NotNull] SwiftInterfaceParser.Attribute_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAttribute_argument_clause([NotNull] SwiftInterfaceParser.Attribute_argument_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAttributes([NotNull] SwiftInterfaceParser.AttributesContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAttributes([NotNull] SwiftInterfaceParser.AttributesContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitBalanced_tokens([NotNull] SwiftInterfaceParser.Balanced_tokensContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitBalanced_token([NotNull] SwiftInterfaceParser.Balanced_tokenContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAny_punctuation_for_balanced_token([NotNull] SwiftInterfaceParser.Any_punctuation_for_balanced_tokenContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDeclaration_modifier([NotNull] SwiftInterfaceParser.Declaration_modifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDeclaration_modifiers([NotNull] SwiftInterfaceParser.Declaration_modifiersContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAccess_level_modifier([NotNull] SwiftInterfaceParser.Access_level_modifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitMutation_modifier([NotNull] SwiftInterfaceParser.Mutation_modifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterPattern([NotNull] SwiftInterfaceParser.PatternContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitPattern([NotNull] SwiftInterfaceParser.PatternContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitWildcard_pattern([NotNull] SwiftInterfaceParser.Wildcard_patternContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitIdentifier_pattern([NotNull] SwiftInterfaceParser.Identifier_patternContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_type([NotNull] SwiftInterfaceParser.Function_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_type_argument_clause([NotNull] SwiftInterfaceParser.Function_type_argument_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_type_argument_list([NotNull] SwiftInterfaceParser.Function_type_argument_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitFunction_type_argument([NotNull] SwiftInterfaceParser.Function_type_argumentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitArgument_label([NotNull] SwiftInterfaceParser.Argument_labelContext context); - /// - /// Enter a parse tree produced by the dict_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context); - /// - /// Exit a parse tree produced by the dict_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitDict_type([NotNull] SwiftInterfaceParser.Dict_typeContext context); - /// - /// Enter a parse tree produced by the any_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context); - /// - /// Exit a parse tree produced by the any_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitAny_type([NotNull] SwiftInterfaceParser.Any_typeContext context); - /// - /// Enter a parse tree produced by the identifier_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context); - /// - /// Exit a parse tree produced by the identifier_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitIdentifier_type([NotNull] SwiftInterfaceParser.Identifier_typeContext context); - /// - /// Enter a parse tree produced by the func_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context); - /// - /// Exit a parse tree produced by the func_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitFunc_type([NotNull] SwiftInterfaceParser.Func_typeContext context); - /// - /// Enter a parse tree produced by the arr_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context); - /// - /// Exit a parse tree produced by the arr_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitArr_type([NotNull] SwiftInterfaceParser.Arr_typeContext context); - /// - /// Enter a parse tree produced by the meta_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context); - /// - /// Exit a parse tree produced by the meta_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitMeta_type([NotNull] SwiftInterfaceParser.Meta_typeContext context); - /// - /// Enter a parse tree produced by the boxed_protocol_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context); - /// - /// Exit a parse tree produced by the boxed_protocol_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitBoxed_protocol_type([NotNull] SwiftInterfaceParser.Boxed_protocol_typeContext context); - /// - /// Enter a parse tree produced by the optional_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context); - /// - /// Exit a parse tree produced by the optional_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitOptional_type([NotNull] SwiftInterfaceParser.Optional_typeContext context); - /// - /// Enter a parse tree produced by the self_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context); - /// - /// Exit a parse tree produced by the self_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitSelf_type([NotNull] SwiftInterfaceParser.Self_typeContext context); - /// - /// Enter a parse tree produced by the unwrapped_optional_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context); - /// - /// Exit a parse tree produced by the unwrapped_optional_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitUnwrapped_optional_type([NotNull] SwiftInterfaceParser.Unwrapped_optional_typeContext context); - /// - /// Enter a parse tree produced by the proto_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context); - /// - /// Exit a parse tree produced by the proto_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitProto_type([NotNull] SwiftInterfaceParser.Proto_typeContext context); - /// - /// Enter a parse tree produced by the tup_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context); - /// - /// Exit a parse tree produced by the tup_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitTup_type([NotNull] SwiftInterfaceParser.Tup_typeContext context); - /// - /// Enter a parse tree produced by the self_long - /// labeled alternative in . - /// - /// The parse tree. - void EnterSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context); - /// - /// Exit a parse tree produced by the self_long - /// labeled alternative in . - /// - /// The parse tree. - void ExitSelf_long([NotNull] SwiftInterfaceParser.Self_longContext context); - /// - /// Enter a parse tree produced by the proto_comp_type - /// labeled alternative in . - /// - /// The parse tree. - void EnterProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context); - /// - /// Exit a parse tree produced by the proto_comp_type - /// labeled alternative in . - /// - /// The parse tree. - void ExitProto_comp_type([NotNull] SwiftInterfaceParser.Proto_comp_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitType_annotation([NotNull] SwiftInterfaceParser.Type_annotationContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitAny_clause([NotNull] SwiftInterfaceParser.Any_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInout_clause([NotNull] SwiftInterfaceParser.Inout_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitType_identifier([NotNull] SwiftInterfaceParser.Type_identifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterType_name([NotNull] SwiftInterfaceParser.Type_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitType_name([NotNull] SwiftInterfaceParser.Type_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTuple_type([NotNull] SwiftInterfaceParser.Tuple_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTuple_type_element_list([NotNull] SwiftInterfaceParser.Tuple_type_element_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitTuple_type_element([NotNull] SwiftInterfaceParser.Tuple_type_elementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitElement_name([NotNull] SwiftInterfaceParser.Element_nameContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitArray_type([NotNull] SwiftInterfaceParser.Array_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitDictionary_type([NotNull] SwiftInterfaceParser.Dictionary_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_composition_type([NotNull] SwiftInterfaceParser.Protocol_composition_typeContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitProtocol_identifier([NotNull] SwiftInterfaceParser.Protocol_identifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterLiteral([NotNull] SwiftInterfaceParser.LiteralContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitLiteral([NotNull] SwiftInterfaceParser.LiteralContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitNil_literal([NotNull] SwiftInterfaceParser.Nil_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitBoolean_literal([NotNull] SwiftInterfaceParser.Boolean_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitNumeric_literal([NotNull] SwiftInterfaceParser.Numeric_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitInteger_literal([NotNull] SwiftInterfaceParser.Integer_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterString_literal([NotNull] SwiftInterfaceParser.String_literalContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitString_literal([NotNull] SwiftInterfaceParser.String_literalContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitLabel_identifier([NotNull] SwiftInterfaceParser.Label_identifierContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_parameter_clause([NotNull] SwiftInterfaceParser.Generic_parameter_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_parameter_list([NotNull] SwiftInterfaceParser.Generic_parameter_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_parameter([NotNull] SwiftInterfaceParser.Generic_parameterContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_where_clause([NotNull] SwiftInterfaceParser.Generic_where_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRequirement_list([NotNull] SwiftInterfaceParser.Requirement_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRequirement([NotNull] SwiftInterfaceParser.RequirementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRequirement([NotNull] SwiftInterfaceParser.RequirementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitConformance_requirement([NotNull] SwiftInterfaceParser.Conformance_requirementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitSame_type_requirement([NotNull] SwiftInterfaceParser.Same_type_requirementContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_argument_clause([NotNull] SwiftInterfaceParser.Generic_argument_clauseContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_argument_list([NotNull] SwiftInterfaceParser.Generic_argument_listContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitGeneric_argument([NotNull] SwiftInterfaceParser.Generic_argumentContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitOpGreater([NotNull] SwiftInterfaceParser.OpGreaterContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitArrow_operator([NotNull] SwiftInterfaceParser.Arrow_operatorContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitRange_operator([NotNull] SwiftInterfaceParser.Range_operatorContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitKeyword_as_identifier_in_declarations([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_declarationsContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitKeyword_as_identifier_in_labels([NotNull] SwiftInterfaceParser.Keyword_as_identifier_in_labelsContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterOperator([NotNull] SwiftInterfaceParser.OperatorContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitOperator([NotNull] SwiftInterfaceParser.OperatorContext context); - /// - /// Enter a parse tree produced by . - /// - /// The parse tree. - void EnterOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context); - /// - /// Exit a parse tree produced by . - /// - /// The parse tree. - void ExitOperator_angles([NotNull] SwiftInterfaceParser.Operator_anglesContext context); -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs b/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs deleted file mode 100644 index 4b6a57425975..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/GeneratedParser/SwiftInterfaceParser.cs +++ /dev/null @@ -1,13120 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// ANTLR Version: 4.9.1 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// Generated from SwiftInterface.g4 by ANTLR 4.9.1 - -// Unreachable code detected -#pragma warning disable 0162 -// The variable '...' is assigned but its value is never used -#pragma warning disable 0219 -// Missing XML comment for publicly visible type or member '...' -#pragma warning disable 1591 -// Ambiguous reference in cref attribute -#pragma warning disable 419 - -using System; -using System.IO; -using System.Text; -using System.Diagnostics; -using System.Collections.Generic; -using Antlr4.Runtime; -using Antlr4.Runtime.Atn; -using Antlr4.Runtime.Misc; -using Antlr4.Runtime.Tree; -using DFA = Antlr4.Runtime.Dfa.DFA; - -[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.9.1")] -// [System.CLSCompliant(false)] -public partial class SwiftInterfaceParser : Parser { - protected static DFA[] decisionToDFA; - protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); - public const int - T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, - T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, - T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24, - T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31, - T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, T__37=38, - T__38=39, T__39=40, T__40=41, T__41=42, T__42=43, T__43=44, T__44=45, - T__45=46, T__46=47, T__47=48, T__48=49, T__49=50, T__50=51, T__51=52, - T__52=53, T__53=54, T__54=55, T__55=56, T__56=57, T__57=58, T__58=59, - T__59=60, T__60=61, T__61=62, T__62=63, T__63=64, T__64=65, T__65=66, - T__66=67, T__67=68, T__68=69, T__69=70, T__70=71, T__71=72, T__72=73, - T__73=74, T__74=75, T__75=76, T__76=77, T__77=78, T__78=79, T__79=80, - T__80=81, T__81=82, T__82=83, T__83=84, T__84=85, T__85=86, T__86=87, - T__87=88, T__88=89, T__89=90, T__90=91, T__91=92, T__92=93, T__93=94, - T__94=95, T__95=96, T__96=97, T__97=98, T__98=99, T__99=100, T__100=101, - T__101=102, T__102=103, T__103=104, T__104=105, T__105=106, T__106=107, - T__107=108, T__108=109, T__109=110, T__110=111, T__111=112, Binary_literal=113, - Octal_literal=114, Decimal_literal=115, Pure_decimal_digits=116, Hexadecimal_literal=117, - Static_string_literal=118, Identifier=119, Implicit_parameter_name=120, - WS=121, OpPlus=122, OpMinus=123, OpAssign=124, OpAmp=125, OpQuestion=126, - OpLess=127, OpBang=128, OpDot=129, OpComma=130, OpTilde=131, OpColon=132, - OpSemi=133, OpAt=134, OpPound=135, OpBackTick=136, OpUnder=137, OpLParen=138, - OpRParen=139, OpLBracket=140, OpRBracket=141, OpLBrace=142, OpRBrace=143, - Decimal_digits=144, Operator=145, DotOperatorHead=146, DotOperatorFollow=147, - OpEqEq=148, Comment_line=149, OpGreater=150; - public const int - RULE_swiftinterface = 0, RULE_statement = 1, RULE_comment = 2, RULE_declaration = 3, - RULE_nominal_declaration = 4, RULE_import_statement = 5, RULE_import_kind = 6, - RULE_import_path = 7, RULE_import_path_identifier = 8, RULE_variable_declaration = 9, - RULE_variable_declaration_head = 10, RULE_variable_declaration_tail = 11, - RULE_variable_name = 12, RULE_var_clause = 13, RULE_let_clause = 14, RULE_getter_setter_keyword_block = 15, - RULE_getter_keyword_clause = 16, RULE_setter_keyword_clause = 17, RULE_new_value_name = 18, - RULE_typealias_declaration = 19, RULE_typealias_name = 20, RULE_typealias_assignment = 21, - RULE_enum_declaration = 22, RULE_union_style_enum = 23, RULE_union_style_enum_members = 24, - RULE_union_style_enum_member = 25, RULE_union_style_enum_case_clause = 26, - RULE_union_style_enum_case_list = 27, RULE_union_style_enum_case = 28, - RULE_enum_name = 29, RULE_enum_case_name = 30, RULE_raw_value_style_enum = 31, - RULE_raw_value_style_enum_members = 32, RULE_raw_value_style_enum_member = 33, - RULE_raw_value_style_enum_case_clause = 34, RULE_raw_value_style_enum_case_list = 35, - RULE_raw_value_style_enum_case = 36, RULE_raw_value_assignment = 37, RULE_raw_value_literal = 38, - RULE_struct_declaration = 39, RULE_struct_name = 40, RULE_struct_body = 41, - RULE_struct_member = 42, RULE_class_declaration = 43, RULE_class_name = 44, - RULE_class_body = 45, RULE_class_member = 46, RULE_final_clause = 47, - RULE_protocol_declaration = 48, RULE_protocol_name = 49, RULE_protocol_body = 50, - RULE_protocol_member = 51, RULE_protocol_member_declaration = 52, RULE_operator_declaration = 53, - RULE_prefix_operator_declaration = 54, RULE_postfix_operator_declaration = 55, - RULE_infix_operator_declaration = 56, RULE_infix_operator_group = 57, - RULE_precedence_group_declaration = 58, RULE_precedence_group_attribute = 59, - RULE_precedence_group_relation = 60, RULE_precedence_group_assignment = 61, - RULE_precedence_group_associativity = 62, RULE_associativity = 63, RULE_precedence_group_names = 64, - RULE_precedence_group_name = 65, RULE_extension_declaration = 66, RULE_extension_body = 67, - RULE_extension_member = 68, RULE_subscript_declaration = 69, RULE_subscript_head = 70, - RULE_subscript_result = 71, RULE_protocol_associated_type_declaration = 72, - RULE_function_declaration = 73, RULE_function_head = 74, RULE_function_name = 75, - RULE_function_body = 76, RULE_operator_name = 77, RULE_function_signature = 78, - RULE_async_clause = 79, RULE_throws_clause = 80, RULE_rethrows_clause = 81, - RULE_function_result = 82, RULE_initializer_declaration = 83, RULE_initializer_head = 84, - RULE_deinitializer_declaration = 85, RULE_parameter_clause = 86, RULE_parameter_list = 87, - RULE_parameter = 88, RULE_external_parameter_name = 89, RULE_local_parameter_name = 90, - RULE_defaultInitializer = 91, RULE_dyckExpression = 92, RULE_dyckSubExpression = 93, - RULE_any_other_things_for_dyck_expression = 94, RULE_dotSymbol = 95, RULE_declaration_identifier = 96, - RULE_type_inheritance_clause = 97, RULE_type_inheritance_list = 98, RULE_class_requirement = 99, - RULE_attribute = 100, RULE_attribute_name = 101, RULE_attribute_argument_clause = 102, - RULE_attributes = 103, RULE_balanced_tokens = 104, RULE_balanced_token = 105, - RULE_any_punctuation_for_balanced_token = 106, RULE_declaration_modifier = 107, - RULE_declaration_modifiers = 108, RULE_access_level_modifier = 109, RULE_mutation_modifier = 110, - RULE_pattern = 111, RULE_wildcard_pattern = 112, RULE_identifier_pattern = 113, - RULE_function_type = 114, RULE_function_type_argument_clause = 115, RULE_function_type_argument_list = 116, - RULE_function_type_argument = 117, RULE_argument_label = 118, RULE_type = 119, - RULE_type_annotation = 120, RULE_any_clause = 121, RULE_inout_clause = 122, - RULE_type_identifier = 123, RULE_type_name = 124, RULE_tuple_type = 125, - RULE_tuple_type_element_list = 126, RULE_tuple_type_element = 127, RULE_element_name = 128, - RULE_array_type = 129, RULE_dictionary_type = 130, RULE_protocol_composition_type = 131, - RULE_protocol_identifier = 132, RULE_literal = 133, RULE_nil_literal = 134, - RULE_boolean_literal = 135, RULE_numeric_literal = 136, RULE_integer_literal = 137, - RULE_string_literal = 138, RULE_label_identifier = 139, RULE_generic_parameter_clause = 140, - RULE_generic_parameter_list = 141, RULE_generic_parameter = 142, RULE_generic_where_clause = 143, - RULE_requirement_list = 144, RULE_requirement = 145, RULE_conformance_requirement = 146, - RULE_same_type_requirement = 147, RULE_generic_argument_clause = 148, - RULE_generic_argument_list = 149, RULE_generic_argument = 150, RULE_opGreater = 151, - RULE_arrow_operator = 152, RULE_range_operator = 153, RULE_keyword_as_identifier_in_declarations = 154, - RULE_keyword_as_identifier_in_labels = 155, RULE_operator = 156, RULE_operator_angles = 157; - public static readonly string[] ruleNames = { - "swiftinterface", "statement", "comment", "declaration", "nominal_declaration", - "import_statement", "import_kind", "import_path", "import_path_identifier", - "variable_declaration", "variable_declaration_head", "variable_declaration_tail", - "variable_name", "var_clause", "let_clause", "getter_setter_keyword_block", - "getter_keyword_clause", "setter_keyword_clause", "new_value_name", "typealias_declaration", - "typealias_name", "typealias_assignment", "enum_declaration", "union_style_enum", - "union_style_enum_members", "union_style_enum_member", "union_style_enum_case_clause", - "union_style_enum_case_list", "union_style_enum_case", "enum_name", "enum_case_name", - "raw_value_style_enum", "raw_value_style_enum_members", "raw_value_style_enum_member", - "raw_value_style_enum_case_clause", "raw_value_style_enum_case_list", - "raw_value_style_enum_case", "raw_value_assignment", "raw_value_literal", - "struct_declaration", "struct_name", "struct_body", "struct_member", "class_declaration", - "class_name", "class_body", "class_member", "final_clause", "protocol_declaration", - "protocol_name", "protocol_body", "protocol_member", "protocol_member_declaration", - "operator_declaration", "prefix_operator_declaration", "postfix_operator_declaration", - "infix_operator_declaration", "infix_operator_group", "precedence_group_declaration", - "precedence_group_attribute", "precedence_group_relation", "precedence_group_assignment", - "precedence_group_associativity", "associativity", "precedence_group_names", - "precedence_group_name", "extension_declaration", "extension_body", "extension_member", - "subscript_declaration", "subscript_head", "subscript_result", "protocol_associated_type_declaration", - "function_declaration", "function_head", "function_name", "function_body", - "operator_name", "function_signature", "async_clause", "throws_clause", - "rethrows_clause", "function_result", "initializer_declaration", "initializer_head", - "deinitializer_declaration", "parameter_clause", "parameter_list", "parameter", - "external_parameter_name", "local_parameter_name", "defaultInitializer", - "dyckExpression", "dyckSubExpression", "any_other_things_for_dyck_expression", - "dotSymbol", "declaration_identifier", "type_inheritance_clause", "type_inheritance_list", - "class_requirement", "attribute", "attribute_name", "attribute_argument_clause", - "attributes", "balanced_tokens", "balanced_token", "any_punctuation_for_balanced_token", - "declaration_modifier", "declaration_modifiers", "access_level_modifier", - "mutation_modifier", "pattern", "wildcard_pattern", "identifier_pattern", - "function_type", "function_type_argument_clause", "function_type_argument_list", - "function_type_argument", "argument_label", "type", "type_annotation", - "any_clause", "inout_clause", "type_identifier", "type_name", "tuple_type", - "tuple_type_element_list", "tuple_type_element", "element_name", "array_type", - "dictionary_type", "protocol_composition_type", "protocol_identifier", - "literal", "nil_literal", "boolean_literal", "numeric_literal", "integer_literal", - "string_literal", "label_identifier", "generic_parameter_clause", "generic_parameter_list", - "generic_parameter", "generic_where_clause", "requirement_list", "requirement", - "conformance_requirement", "same_type_requirement", "generic_argument_clause", - "generic_argument_list", "generic_argument", "opGreater", "arrow_operator", - "range_operator", "keyword_as_identifier_in_declarations", "keyword_as_identifier_in_labels", - "operator", "operator_angles" - }; - - private static readonly string[] _LiteralNames = { - null, "'import'", "'typealias'", "'struct'", "'class'", "'enum'", "'protocol'", - "'var'", "'func'", "'let'", "'get'", "'set'", "'indirect'", "'case'", - "'final'", "'prefix'", "'operator'", "'postfix'", "'infix'", "'precedencegroup'", - "'higherThan'", "'lowerThan'", "'assignment'", "'associativity'", "'left'", - "'right'", "'none'", "'extension'", "'subscript'", "'associatedtype'", - "'async'", "'throws'", "'rethrows'", "'init'", "'deinit'", "'convenience'", - "'dynamic'", "'lazy'", "'optional'", "'override'", "'required'", "'static'", - "'unowned'", "'safe'", "'unsafe'", "'weak'", "'private'", "'fileprivate'", - "'internal'", "'public'", "'open'", "'mutating'", "'nonmutating'", "'is'", - "'as'", "'Type'", "'Protocol'", "'Any'", "'Self'", "'any'", "'inout'", - "'nil'", "'true'", "'false'", "'where'", "'>'", "'->'", "'...'", "'alpha'", - "'arch'", "'arm'", "'arm64'", "'blue'", "'didSet'", "'file'", "'green'", - "'i386'", "'iOS'", "'iOSApplicationExtension'", "'line'", "'macOS'", "'macOSApplicationExtension'", - "'of'", "'os'", "'precedence'", "'red'", "'resourceName'", "'swift'", - "'tvOS'", "'type'", "'watchOS'", "'willSet'", "'x86_64'", "'break'", "'catch'", - "'continue'", "'default'", "'defer'", "'do'", "'else'", "'fallthrough'", - "'for'", "'guard'", "'if'", "'in'", "'repeat'", "'return'", "'self'", - "'super'", "'switch'", "'throw'", "'try'", "'while'", null, null, null, - null, null, null, null, null, null, "'+'", "'-'", "'='", "'&'", "'?'", - "'<'", "'!'", "'.'", "','", "'~'", "':'", "';'", "'@'", "'#'", "'`'", - "'_'", "'('", "')'", "'['", "']'", "'{'", "'}'", null, null, null, null, - "'=='" - }; - private static readonly string[] _SymbolicNames = { - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, "Binary_literal", "Octal_literal", "Decimal_literal", - "Pure_decimal_digits", "Hexadecimal_literal", "Static_string_literal", - "Identifier", "Implicit_parameter_name", "WS", "OpPlus", "OpMinus", "OpAssign", - "OpAmp", "OpQuestion", "OpLess", "OpBang", "OpDot", "OpComma", "OpTilde", - "OpColon", "OpSemi", "OpAt", "OpPound", "OpBackTick", "OpUnder", "OpLParen", - "OpRParen", "OpLBracket", "OpRBracket", "OpLBrace", "OpRBrace", "Decimal_digits", - "Operator", "DotOperatorHead", "DotOperatorFollow", "OpEqEq", "Comment_line", - "OpGreater" - }; - public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); - - [NotNull] - public override IVocabulary Vocabulary - { - get - { - return DefaultVocabulary; - } - } - - public override string GrammarFileName { get { return "SwiftInterface.g4"; } } - - public override string[] RuleNames { get { return ruleNames; } } - - public override string SerializedAtn { get { return new string(_serializedATN); } } - - static SwiftInterfaceParser() { - decisionToDFA = new DFA[_ATN.NumberOfDecisions]; - for (int i = 0; i < _ATN.NumberOfDecisions; i++) { - decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); - } - } - - public SwiftInterfaceParser(ITokenStream input) : this(input, Console.Out, Console.Error) { } - - public SwiftInterfaceParser(ITokenStream input, TextWriter output, TextWriter errorOutput) - : base(input, output, errorOutput) - { - Interpreter = new ParserATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); - } - - public partial class SwiftinterfaceContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public StatementContext[] statement() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public StatementContext statement(int i) { - return GetRuleContext(i); - } - public SwiftinterfaceContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_swiftinterface; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSwiftinterface(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSwiftinterface(this); - } - } - - [RuleVersion(0)] - public SwiftinterfaceContext swiftinterface() { - SwiftinterfaceContext _localctx = new SwiftinterfaceContext(Context, State); - EnterRule(_localctx, 0, RULE_swiftinterface); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 319; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt || _la==Comment_line) { - { - { - State = 316; - statement(); - } - } - State = 321; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class StatementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Import_statementContext import_statement() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public DeclarationContext declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public CommentContext comment() { - return GetRuleContext(0); - } - public StatementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_statement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterStatement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitStatement(this); - } - } - - [RuleVersion(0)] - public StatementContext statement() { - StatementContext _localctx = new StatementContext(Context, State); - EnterRule(_localctx, 2, RULE_statement); - try { - State = 325; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,1,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 322; - import_statement(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 323; - declaration(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 324; - comment(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class CommentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Comment_line() { return GetToken(SwiftInterfaceParser.Comment_line, 0); } - public CommentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_comment; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterComment(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitComment(this); - } - } - - [RuleVersion(0)] - public CommentContext comment() { - CommentContext _localctx = new CommentContext(Context, State); - EnterRule(_localctx, 4, RULE_comment); - try { - EnterOuterAlt(_localctx, 1); - { - State = 327; - Match(Comment_line); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class DeclarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Enum_declarationContext enum_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Struct_declarationContext struct_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Class_declarationContext class_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_declarationContext protocol_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Extension_declarationContext extension_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Operator_declarationContext operator_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_declarationContext precedence_group_declaration() { - return GetRuleContext(0); - } - public DeclarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDeclaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDeclaration(this); - } - } - - [RuleVersion(0)] - public DeclarationContext declaration() { - DeclarationContext _localctx = new DeclarationContext(Context, State); - EnterRule(_localctx, 6, RULE_declaration); - try { - State = 340; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,2,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 329; - variable_declaration(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 330; - typealias_declaration(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 331; - function_declaration(); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 332; - enum_declaration(); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 333; - struct_declaration(); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 334; - class_declaration(); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 335; - protocol_declaration(); - } - break; - case 8: - EnterOuterAlt(_localctx, 8); - { - State = 336; - extension_declaration(); - } - break; - case 9: - EnterOuterAlt(_localctx, 9); - { - State = 337; - subscript_declaration(); - } - break; - case 10: - EnterOuterAlt(_localctx, 10); - { - State = 338; - operator_declaration(); - } - break; - case 11: - EnterOuterAlt(_localctx, 11); - { - State = 339; - precedence_group_declaration(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Nominal_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Enum_declarationContext enum_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Struct_declarationContext struct_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Class_declarationContext class_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_declarationContext protocol_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Initializer_declarationContext initializer_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Deinitializer_declarationContext deinitializer_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Extension_declarationContext extension_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Operator_declarationContext operator_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_declarationContext precedence_group_declaration() { - return GetRuleContext(0); - } - public Nominal_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_nominal_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterNominal_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitNominal_declaration(this); - } - } - - [RuleVersion(0)] - public Nominal_declarationContext nominal_declaration() { - Nominal_declarationContext _localctx = new Nominal_declarationContext(Context, State); - EnterRule(_localctx, 8, RULE_nominal_declaration); - try { - State = 355; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,3,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 342; - variable_declaration(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 343; - typealias_declaration(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 344; - function_declaration(); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 345; - enum_declaration(); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 346; - struct_declaration(); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 347; - class_declaration(); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 348; - protocol_declaration(); - } - break; - case 8: - EnterOuterAlt(_localctx, 8); - { - State = 349; - initializer_declaration(); - } - break; - case 9: - EnterOuterAlt(_localctx, 9); - { - State = 350; - deinitializer_declaration(); - } - break; - case 10: - EnterOuterAlt(_localctx, 10); - { - State = 351; - extension_declaration(); - } - break; - case 11: - EnterOuterAlt(_localctx, 11); - { - State = 352; - subscript_declaration(); - } - break; - case 12: - EnterOuterAlt(_localctx, 12); - { - State = 353; - operator_declaration(); - } - break; - case 13: - EnterOuterAlt(_localctx, 13); - { - State = 354; - precedence_group_declaration(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Import_statementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Import_pathContext import_path() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Import_kindContext import_kind() { - return GetRuleContext(0); - } - public Import_statementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_import_statement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterImport_statement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitImport_statement(this); - } - } - - [RuleVersion(0)] - public Import_statementContext import_statement() { - Import_statementContext _localctx = new Import_statementContext(Context, State); - EnterRule(_localctx, 10, RULE_import_statement); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 358; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 357; - attributes(); - } - } - - State = 360; - Match(T__0); - State = 362; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7))) != 0)) { - { - State = 361; - import_kind(); - } - } - - State = 364; - import_path(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Import_kindContext : ParserRuleContext { - public Import_kindContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_import_kind; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterImport_kind(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitImport_kind(this); - } - } - - [RuleVersion(0)] - public Import_kindContext import_kind() { - Import_kindContext _localctx = new Import_kindContext(Context, State); - EnterRule(_localctx, 12, RULE_import_kind); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 366; - _la = TokenStream.LA(1); - if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Import_pathContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Import_path_identifierContext[] import_path_identifier() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Import_path_identifierContext import_path_identifier(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpDot() { return GetTokens(SwiftInterfaceParser.OpDot); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot(int i) { - return GetToken(SwiftInterfaceParser.OpDot, i); - } - public Import_pathContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_import_path; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterImport_path(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitImport_path(this); - } - } - - [RuleVersion(0)] - public Import_pathContext import_path() { - Import_pathContext _localctx = new Import_pathContext(Context, State); - EnterRule(_localctx, 14, RULE_import_path); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 368; - import_path_identifier(); - State = 373; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpDot) { - { - { - State = 369; - Match(OpDot); - State = 370; - import_path_identifier(); - } - } - State = 375; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Import_path_identifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Import_path_identifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_import_path_identifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterImport_path_identifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitImport_path_identifier(this); - } - } - - [RuleVersion(0)] - public Import_path_identifierContext import_path_identifier() { - Import_path_identifierContext _localctx = new Import_path_identifierContext(Context, State); - EnterRule(_localctx, 16, RULE_import_path_identifier); - try { - EnterOuterAlt(_localctx, 1); - { - State = 376; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Variable_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_headContext variable_declaration_head() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_tailContext[] variable_declaration_tail() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Variable_declaration_tailContext variable_declaration_tail(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Variable_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_variable_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterVariable_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitVariable_declaration(this); - } - } - - [RuleVersion(0)] - public Variable_declarationContext variable_declaration() { - Variable_declarationContext _localctx = new Variable_declarationContext(Context, State); - EnterRule(_localctx, 18, RULE_variable_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 378; - variable_declaration_head(); - State = 379; - variable_declaration_tail(); - State = 384; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 380; - Match(OpComma); - State = 381; - variable_declaration_tail(); - } - } - State = 386; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Variable_declaration_headContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Var_clauseContext var_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Let_clauseContext let_clause() { - return GetRuleContext(0); - } - public Variable_declaration_headContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_variable_declaration_head; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterVariable_declaration_head(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitVariable_declaration_head(this); - } - } - - [RuleVersion(0)] - public Variable_declaration_headContext variable_declaration_head() { - Variable_declaration_headContext _localctx = new Variable_declaration_headContext(Context, State); - EnterRule(_localctx, 20, RULE_variable_declaration_head); - int _la; - try { - State = 401; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,12,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 388; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 387; - attributes(); - } - } - - State = 391; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 390; - declaration_modifiers(); - } - } - - State = 393; - var_clause(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 395; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 394; - attributes(); - } - } - - State = 398; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 397; - declaration_modifiers(); - } - } - - State = 400; - let_clause(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Variable_declaration_tailContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Variable_nameContext variable_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Getter_setter_keyword_blockContext getter_setter_keyword_block() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public DefaultInitializerContext defaultInitializer() { - return GetRuleContext(0); - } - public Variable_declaration_tailContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_variable_declaration_tail; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterVariable_declaration_tail(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitVariable_declaration_tail(this); - } - } - - [RuleVersion(0)] - public Variable_declaration_tailContext variable_declaration_tail() { - Variable_declaration_tailContext _localctx = new Variable_declaration_tailContext(Context, State); - EnterRule(_localctx, 22, RULE_variable_declaration_tail); - int _la; - try { - State = 413; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,15,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 403; - variable_name(); - State = 404; - type_annotation(); - State = 406; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLBrace) { - { - State = 405; - getter_setter_keyword_block(); - } - } - - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 408; - variable_name(); - State = 409; - type_annotation(); - State = 411; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAssign) { - { - State = 410; - defaultInitializer(); - } - } - - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Variable_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Variable_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_variable_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterVariable_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitVariable_name(this); - } - } - - [RuleVersion(0)] - public Variable_nameContext variable_name() { - Variable_nameContext _localctx = new Variable_nameContext(Context, State); - EnterRule(_localctx, 24, RULE_variable_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 415; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Var_clauseContext : ParserRuleContext { - public Var_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_var_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterVar_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitVar_clause(this); - } - } - - [RuleVersion(0)] - public Var_clauseContext var_clause() { - Var_clauseContext _localctx = new Var_clauseContext(Context, State); - EnterRule(_localctx, 26, RULE_var_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 417; - Match(T__6); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Let_clauseContext : ParserRuleContext { - public Let_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_let_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterLet_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitLet_clause(this); - } - } - - [RuleVersion(0)] - public Let_clauseContext let_clause() { - Let_clauseContext _localctx = new Let_clauseContext(Context, State); - EnterRule(_localctx, 28, RULE_let_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 419; - Match(T__8); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Getter_setter_keyword_blockContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Getter_keyword_clauseContext getter_keyword_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Setter_keyword_clauseContext setter_keyword_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - public Getter_setter_keyword_blockContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_getter_setter_keyword_block; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGetter_setter_keyword_block(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGetter_setter_keyword_block(this); - } - } - - [RuleVersion(0)] - public Getter_setter_keyword_blockContext getter_setter_keyword_block() { - Getter_setter_keyword_blockContext _localctx = new Getter_setter_keyword_blockContext(Context, State); - EnterRule(_localctx, 30, RULE_getter_setter_keyword_block); - try { - State = 435; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,16,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 421; - Match(OpLBrace); - State = 422; - getter_keyword_clause(); - State = 423; - setter_keyword_clause(); - State = 424; - Match(OpRBrace); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 426; - Match(OpLBrace); - State = 427; - setter_keyword_clause(); - State = 428; - getter_keyword_clause(); - State = 429; - Match(OpRBrace); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 431; - Match(OpLBrace); - State = 432; - getter_keyword_clause(); - State = 433; - Match(OpRBrace); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Getter_keyword_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Async_clauseContext async_clause() { - return GetRuleContext(0); - } - public Getter_keyword_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_getter_keyword_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGetter_keyword_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGetter_keyword_clause(this); - } - } - - [RuleVersion(0)] - public Getter_keyword_clauseContext getter_keyword_clause() { - Getter_keyword_clauseContext _localctx = new Getter_keyword_clauseContext(Context, State); - EnterRule(_localctx, 32, RULE_getter_keyword_clause); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 438; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 437; - attributes(); - } - } - - State = 441; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__50 || _la==T__51) { - { - State = 440; - mutation_modifier(); - } - } - - State = 443; - Match(T__9); - State = 445; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__29) { - { - State = 444; - async_clause(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Setter_keyword_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public New_value_nameContext new_value_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - public Setter_keyword_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_setter_keyword_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSetter_keyword_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSetter_keyword_clause(this); - } - } - - [RuleVersion(0)] - public Setter_keyword_clauseContext setter_keyword_clause() { - Setter_keyword_clauseContext _localctx = new Setter_keyword_clauseContext(Context, State); - EnterRule(_localctx, 34, RULE_setter_keyword_clause); - int _la; - try { - State = 465; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,24,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 448; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 447; - attributes(); - } - } - - State = 451; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__50 || _la==T__51) { - { - State = 450; - mutation_modifier(); - } - } - - State = 453; - Match(T__10); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 455; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 454; - attributes(); - } - } - - State = 458; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__50 || _la==T__51) { - { - State = 457; - mutation_modifier(); - } - } - - State = 460; - Match(T__10); - State = 461; - Match(OpLParen); - State = 462; - new_value_name(); - State = 463; - Match(OpRParen); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class New_value_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public New_value_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_new_value_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterNew_value_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitNew_value_name(this); - } - } - - [RuleVersion(0)] - public New_value_nameContext new_value_name() { - New_value_nameContext _localctx = new New_value_nameContext(Context, State); - EnterRule(_localctx, 36, RULE_new_value_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 467; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Typealias_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Typealias_nameContext typealias_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Typealias_assignmentContext typealias_assignment() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - public Typealias_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_typealias_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTypealias_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTypealias_declaration(this); - } - } - - [RuleVersion(0)] - public Typealias_declarationContext typealias_declaration() { - Typealias_declarationContext _localctx = new Typealias_declarationContext(Context, State); - EnterRule(_localctx, 38, RULE_typealias_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 470; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 469; - attributes(); - } - } - - State = 473; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 472; - access_level_modifier(); - } - } - - State = 475; - Match(T__1); - State = 476; - typealias_name(); - State = 478; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 477; - generic_parameter_clause(); - } - } - - State = 480; - typealias_assignment(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Typealias_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Typealias_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_typealias_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTypealias_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTypealias_name(this); - } - } - - [RuleVersion(0)] - public Typealias_nameContext typealias_name() { - Typealias_nameContext _localctx = new Typealias_nameContext(Context, State); - EnterRule(_localctx, 40, RULE_typealias_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 482; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Typealias_assignmentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - public Typealias_assignmentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_typealias_assignment; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTypealias_assignment(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTypealias_assignment(this); - } - } - - [RuleVersion(0)] - public Typealias_assignmentContext typealias_assignment() { - Typealias_assignmentContext _localctx = new Typealias_assignmentContext(Context, State); - EnterRule(_localctx, 42, RULE_typealias_assignment); - try { - EnterOuterAlt(_localctx, 1); - { - State = 484; - Match(OpAssign); - State = 485; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Enum_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enumContext union_style_enum() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enumContext raw_value_style_enum() { - return GetRuleContext(0); - } - public Enum_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_enum_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterEnum_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitEnum_declaration(this); - } - } - - [RuleVersion(0)] - public Enum_declarationContext enum_declaration() { - Enum_declarationContext _localctx = new Enum_declarationContext(Context, State); - EnterRule(_localctx, 44, RULE_enum_declaration); - int _la; - try { - State = 501; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,32,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 488; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 487; - attributes(); - } - } - - State = 491; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 490; - access_level_modifier(); - } - } - - State = 493; - union_style_enum(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 495; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 494; - attributes(); - } - } - - State = 498; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 497; - access_level_modifier(); - } - } - - State = 500; - raw_value_style_enum(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enumContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Enum_nameContext enum_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_membersContext union_style_enum_members() { - return GetRuleContext(0); - } - public Union_style_enumContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum(this); - } - } - - [RuleVersion(0)] - public Union_style_enumContext union_style_enum() { - Union_style_enumContext _localctx = new Union_style_enumContext(Context, State); - EnterRule(_localctx, 46, RULE_union_style_enum); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 504; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__11) { - { - State = 503; - Match(T__11); - } - } - - State = 506; - Match(T__4); - State = 507; - enum_name(); - State = 509; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 508; - generic_parameter_clause(); - } - } - - State = 512; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 511; - type_inheritance_clause(); - } - } - - State = 515; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 514; - generic_where_clause(); - } - } - - State = 517; - Match(OpLBrace); - State = 519; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - State = 518; - union_style_enum_members(); - } - } - - State = 521; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enum_membersContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_memberContext union_style_enum_member() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_membersContext union_style_enum_members() { - return GetRuleContext(0); - } - public Union_style_enum_membersContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum_members; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum_members(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum_members(this); - } - } - - [RuleVersion(0)] - public Union_style_enum_membersContext union_style_enum_members() { - Union_style_enum_membersContext _localctx = new Union_style_enum_membersContext(Context, State); - EnterRule(_localctx, 48, RULE_union_style_enum_members); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 523; - union_style_enum_member(); - State = 525; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - State = 524; - union_style_enum_members(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enum_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_clauseContext union_style_enum_case_clause() { - return GetRuleContext(0); - } - public Union_style_enum_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum_member(this); - } - } - - [RuleVersion(0)] - public Union_style_enum_memberContext union_style_enum_member() { - Union_style_enum_memberContext _localctx = new Union_style_enum_memberContext(Context, State); - EnterRule(_localctx, 50, RULE_union_style_enum_member); - try { - State = 529; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,39,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 527; - nominal_declaration(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 528; - union_style_enum_case_clause(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enum_case_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_listContext union_style_enum_case_list() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - public Union_style_enum_case_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum_case_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum_case_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum_case_clause(this); - } - } - - [RuleVersion(0)] - public Union_style_enum_case_clauseContext union_style_enum_case_clause() { - Union_style_enum_case_clauseContext _localctx = new Union_style_enum_case_clauseContext(Context, State); - EnterRule(_localctx, 52, RULE_union_style_enum_case_clause); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 532; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 531; - attributes(); - } - } - - State = 535; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__11) { - { - State = 534; - Match(T__11); - } - } - - State = 537; - Match(T__12); - State = 538; - union_style_enum_case_list(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enum_case_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_caseContext union_style_enum_case() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Union_style_enum_case_listContext union_style_enum_case_list() { - return GetRuleContext(0); - } - public Union_style_enum_case_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum_case_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum_case_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum_case_list(this); - } - } - - [RuleVersion(0)] - public Union_style_enum_case_listContext union_style_enum_case_list() { - Union_style_enum_case_listContext _localctx = new Union_style_enum_case_listContext(Context, State); - EnterRule(_localctx, 54, RULE_union_style_enum_case_list); - try { - State = 545; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,42,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 540; - union_style_enum_case(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 541; - union_style_enum_case(); - State = 542; - Match(OpComma); - State = 543; - union_style_enum_case_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Union_style_enum_caseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Enum_case_nameContext enum_case_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Tuple_typeContext tuple_type() { - return GetRuleContext(0); - } - public Union_style_enum_caseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_union_style_enum_case; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnion_style_enum_case(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnion_style_enum_case(this); - } - } - - [RuleVersion(0)] - public Union_style_enum_caseContext union_style_enum_case() { - Union_style_enum_caseContext _localctx = new Union_style_enum_caseContext(Context, State); - EnterRule(_localctx, 56, RULE_union_style_enum_case); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 547; - enum_case_name(); - State = 549; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLParen) { - { - State = 548; - tuple_type(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Enum_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Enum_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_enum_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterEnum_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitEnum_name(this); - } - } - - [RuleVersion(0)] - public Enum_nameContext enum_name() { - Enum_nameContext _localctx = new Enum_nameContext(Context, State); - EnterRule(_localctx, 58, RULE_enum_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 551; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Enum_case_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Enum_case_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_enum_case_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterEnum_case_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitEnum_case_name(this); - } - } - - [RuleVersion(0)] - public Enum_case_nameContext enum_case_name() { - Enum_case_nameContext _localctx = new Enum_case_nameContext(Context, State); - EnterRule(_localctx, 60, RULE_enum_case_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 553; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enumContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Enum_nameContext enum_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_membersContext raw_value_style_enum_members() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - public Raw_value_style_enumContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enumContext raw_value_style_enum() { - Raw_value_style_enumContext _localctx = new Raw_value_style_enumContext(Context, State); - EnterRule(_localctx, 62, RULE_raw_value_style_enum); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 555; - Match(T__4); - State = 556; - enum_name(); - State = 558; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 557; - generic_parameter_clause(); - } - } - - State = 560; - type_inheritance_clause(); - State = 562; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 561; - generic_where_clause(); - } - } - - State = 564; - Match(OpLBrace); - State = 565; - raw_value_style_enum_members(); - State = 566; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enum_membersContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_memberContext raw_value_style_enum_member() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_membersContext raw_value_style_enum_members() { - return GetRuleContext(0); - } - public Raw_value_style_enum_membersContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum_members; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum_members(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum_members(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enum_membersContext raw_value_style_enum_members() { - Raw_value_style_enum_membersContext _localctx = new Raw_value_style_enum_membersContext(Context, State); - EnterRule(_localctx, 64, RULE_raw_value_style_enum_members); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 568; - raw_value_style_enum_member(); - State = 570; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - State = 569; - raw_value_style_enum_members(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enum_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_clauseContext raw_value_style_enum_case_clause() { - return GetRuleContext(0); - } - public Raw_value_style_enum_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum_member(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enum_memberContext raw_value_style_enum_member() { - Raw_value_style_enum_memberContext _localctx = new Raw_value_style_enum_memberContext(Context, State); - EnterRule(_localctx, 66, RULE_raw_value_style_enum_member); - try { - State = 574; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,47,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 572; - nominal_declaration(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 573; - raw_value_style_enum_case_clause(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enum_case_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - public Raw_value_style_enum_case_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum_case_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum_case_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum_case_clause(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enum_case_clauseContext raw_value_style_enum_case_clause() { - Raw_value_style_enum_case_clauseContext _localctx = new Raw_value_style_enum_case_clauseContext(Context, State); - EnterRule(_localctx, 68, RULE_raw_value_style_enum_case_clause); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 577; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 576; - attributes(); - } - } - - State = 579; - Match(T__12); - State = 580; - raw_value_style_enum_case_list(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enum_case_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_caseContext raw_value_style_enum_case() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { - return GetRuleContext(0); - } - public Raw_value_style_enum_case_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum_case_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum_case_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum_case_list(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enum_case_listContext raw_value_style_enum_case_list() { - Raw_value_style_enum_case_listContext _localctx = new Raw_value_style_enum_case_listContext(Context, State); - EnterRule(_localctx, 70, RULE_raw_value_style_enum_case_list); - try { - State = 587; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,49,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 582; - raw_value_style_enum_case(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 583; - raw_value_style_enum_case(); - State = 584; - Match(OpComma); - State = 585; - raw_value_style_enum_case_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_style_enum_caseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Enum_case_nameContext enum_case_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_assignmentContext raw_value_assignment() { - return GetRuleContext(0); - } - public Raw_value_style_enum_caseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_style_enum_case; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_style_enum_case(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_style_enum_case(this); - } - } - - [RuleVersion(0)] - public Raw_value_style_enum_caseContext raw_value_style_enum_case() { - Raw_value_style_enum_caseContext _localctx = new Raw_value_style_enum_caseContext(Context, State); - EnterRule(_localctx, 72, RULE_raw_value_style_enum_case); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 589; - enum_case_name(); - State = 591; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAssign) { - { - State = 590; - raw_value_assignment(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_assignmentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Raw_value_literalContext raw_value_literal() { - return GetRuleContext(0); - } - public Raw_value_assignmentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_assignment; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_assignment(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_assignment(this); - } - } - - [RuleVersion(0)] - public Raw_value_assignmentContext raw_value_assignment() { - Raw_value_assignmentContext _localctx = new Raw_value_assignmentContext(Context, State); - EnterRule(_localctx, 74, RULE_raw_value_assignment); - try { - EnterOuterAlt(_localctx, 1); - { - State = 593; - Match(OpAssign); - State = 594; - raw_value_literal(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Raw_value_literalContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Numeric_literalContext numeric_literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Static_string_literal() { return GetToken(SwiftInterfaceParser.Static_string_literal, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { - return GetRuleContext(0); - } - public Raw_value_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_raw_value_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRaw_value_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRaw_value_literal(this); - } - } - - [RuleVersion(0)] - public Raw_value_literalContext raw_value_literal() { - Raw_value_literalContext _localctx = new Raw_value_literalContext(Context, State); - EnterRule(_localctx, 76, RULE_raw_value_literal); - try { - State = 599; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case Binary_literal: - case Octal_literal: - case Decimal_literal: - case Pure_decimal_digits: - case Hexadecimal_literal: - case OpPlus: - case OpMinus: - EnterOuterAlt(_localctx, 1); - { - State = 596; - numeric_literal(); - } - break; - case Static_string_literal: - EnterOuterAlt(_localctx, 2); - { - State = 597; - Match(Static_string_literal); - } - break; - case T__61: - case T__62: - EnterOuterAlt(_localctx, 3); - { - State = 598; - boolean_literal(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Struct_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Struct_nameContext struct_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Struct_bodyContext struct_body() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - public Struct_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_struct_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterStruct_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitStruct_declaration(this); - } - } - - [RuleVersion(0)] - public Struct_declarationContext struct_declaration() { - Struct_declarationContext _localctx = new Struct_declarationContext(Context, State); - EnterRule(_localctx, 78, RULE_struct_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 602; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 601; - attributes(); - } - } - - State = 605; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 604; - access_level_modifier(); - } - } - - State = 607; - Match(T__2); - State = 608; - struct_name(); - State = 610; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 609; - generic_parameter_clause(); - } - } - - State = 613; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 612; - type_inheritance_clause(); - } - } - - State = 616; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 615; - generic_where_clause(); - } - } - - State = 618; - struct_body(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Struct_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Struct_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_struct_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterStruct_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitStruct_name(this); - } - } - - [RuleVersion(0)] - public Struct_nameContext struct_name() { - Struct_nameContext _localctx = new Struct_nameContext(Context, State); - EnterRule(_localctx, 80, RULE_struct_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 620; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Struct_bodyContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Struct_memberContext[] struct_member() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Struct_memberContext struct_member(int i) { - return GetRuleContext(i); - } - public Struct_bodyContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_struct_body; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterStruct_body(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitStruct_body(this); - } - } - - [RuleVersion(0)] - public Struct_bodyContext struct_body() { - Struct_bodyContext _localctx = new Struct_bodyContext(Context, State); - EnterRule(_localctx, 82, RULE_struct_body); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 622; - Match(OpLBrace); - State = 626; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - { - State = 623; - struct_member(); - } - } - State = 628; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 629; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Struct_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { - return GetRuleContext(0); - } - public Struct_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_struct_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterStruct_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitStruct_member(this); - } - } - - [RuleVersion(0)] - public Struct_memberContext struct_member() { - Struct_memberContext _localctx = new Struct_memberContext(Context, State); - EnterRule(_localctx, 84, RULE_struct_member); - try { - EnterOuterAlt(_localctx, 1); - { - State = 631; - nominal_declaration(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Class_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Class_nameContext class_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Class_bodyContext class_body() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Final_clauseContext final_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - public Class_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_class_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterClass_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitClass_declaration(this); - } - } - - [RuleVersion(0)] - public Class_declarationContext class_declaration() { - Class_declarationContext _localctx = new Class_declarationContext(Context, State); - EnterRule(_localctx, 86, RULE_class_declaration); - int _la; - try { - State = 675; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,69,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 634; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 633; - attributes(); - } - } - - State = 637; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 636; - access_level_modifier(); - } - } - - State = 640; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__13) { - { - State = 639; - final_clause(); - } - } - - State = 642; - Match(T__3); - State = 643; - class_name(); - State = 645; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 644; - generic_parameter_clause(); - } - } - - State = 648; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 647; - type_inheritance_clause(); - } - } - - State = 651; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 650; - generic_where_clause(); - } - } - - State = 653; - class_body(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 656; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 655; - attributes(); - } - } - - State = 658; - final_clause(); - State = 660; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 659; - access_level_modifier(); - } - } - - State = 662; - Match(T__3); - State = 663; - class_name(); - State = 665; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 664; - generic_parameter_clause(); - } - } - - State = 668; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 667; - type_inheritance_clause(); - } - } - - State = 671; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 670; - generic_where_clause(); - } - } - - State = 673; - class_body(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Class_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Class_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_class_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterClass_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitClass_name(this); - } - } - - [RuleVersion(0)] - public Class_nameContext class_name() { - Class_nameContext _localctx = new Class_nameContext(Context, State); - EnterRule(_localctx, 88, RULE_class_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 677; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Class_bodyContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Class_memberContext[] class_member() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Class_memberContext class_member(int i) { - return GetRuleContext(i); - } - public Class_bodyContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_class_body; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterClass_body(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitClass_body(this); - } - } - - [RuleVersion(0)] - public Class_bodyContext class_body() { - Class_bodyContext _localctx = new Class_bodyContext(Context, State); - EnterRule(_localctx, 90, RULE_class_body); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 679; - Match(OpLBrace); - State = 683; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - { - State = 680; - class_member(); - } - } - State = 685; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 686; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Class_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Nominal_declarationContext nominal_declaration() { - return GetRuleContext(0); - } - public Class_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_class_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterClass_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitClass_member(this); - } - } - - [RuleVersion(0)] - public Class_memberContext class_member() { - Class_memberContext _localctx = new Class_memberContext(Context, State); - EnterRule(_localctx, 92, RULE_class_member); - try { - EnterOuterAlt(_localctx, 1); - { - State = 688; - nominal_declaration(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Final_clauseContext : ParserRuleContext { - public Final_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_final_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFinal_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFinal_clause(this); - } - } - - [RuleVersion(0)] - public Final_clauseContext final_clause() { - Final_clauseContext _localctx = new Final_clauseContext(Context, State); - EnterRule(_localctx, 94, RULE_final_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 690; - Match(T__13); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Protocol_nameContext protocol_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_bodyContext protocol_body() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - public Protocol_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_declaration(this); - } - } - - [RuleVersion(0)] - public Protocol_declarationContext protocol_declaration() { - Protocol_declarationContext _localctx = new Protocol_declarationContext(Context, State); - EnterRule(_localctx, 96, RULE_protocol_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 693; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 692; - attributes(); - } - } - - State = 696; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 695; - access_level_modifier(); - } - } - - State = 698; - Match(T__5); - State = 699; - protocol_name(); - State = 701; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 700; - type_inheritance_clause(); - } - } - - State = 703; - protocol_body(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Protocol_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_name(this); - } - } - - [RuleVersion(0)] - public Protocol_nameContext protocol_name() { - Protocol_nameContext _localctx = new Protocol_nameContext(Context, State); - EnterRule(_localctx, 98, RULE_protocol_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 705; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_bodyContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_memberContext[] protocol_member() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_memberContext protocol_member(int i) { - return GetRuleContext(i); - } - public Protocol_bodyContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_body; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_body(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_body(this); - } - } - - [RuleVersion(0)] - public Protocol_bodyContext protocol_body() { - Protocol_bodyContext _localctx = new Protocol_bodyContext(Context, State); - EnterRule(_localctx, 100, RULE_protocol_body); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 707; - Match(OpLBrace); - State = 711; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__3) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__27) | (1L << T__28) | (1L << T__32) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - { - State = 708; - protocol_member(); - } - } - State = 713; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 714; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Protocol_member_declarationContext protocol_member_declaration() { - return GetRuleContext(0); - } - public Protocol_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_member(this); - } - } - - [RuleVersion(0)] - public Protocol_memberContext protocol_member() { - Protocol_memberContext _localctx = new Protocol_memberContext(Context, State); - EnterRule(_localctx, 102, RULE_protocol_member); - try { - EnterOuterAlt(_localctx, 1); - { - State = 716; - protocol_member_declaration(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_member_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Variable_declarationContext variable_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_declarationContext function_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Initializer_declarationContext initializer_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Subscript_declarationContext subscript_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_associated_type_declarationContext protocol_associated_type_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Typealias_declarationContext typealias_declaration() { - return GetRuleContext(0); - } - public Protocol_member_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_member_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_member_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_member_declaration(this); - } - } - - [RuleVersion(0)] - public Protocol_member_declarationContext protocol_member_declaration() { - Protocol_member_declarationContext _localctx = new Protocol_member_declarationContext(Context, State); - EnterRule(_localctx, 104, RULE_protocol_member_declaration); - try { - State = 724; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,75,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 718; - variable_declaration(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 719; - function_declaration(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 720; - initializer_declaration(); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 721; - subscript_declaration(); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 722; - protocol_associated_type_declaration(); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 723; - typealias_declaration(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Operator_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Prefix_operator_declarationContext prefix_operator_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Postfix_operator_declarationContext postfix_operator_declaration() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Infix_operator_declarationContext infix_operator_declaration() { - return GetRuleContext(0); - } - public Operator_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_operator_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOperator_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOperator_declaration(this); - } - } - - [RuleVersion(0)] - public Operator_declarationContext operator_declaration() { - Operator_declarationContext _localctx = new Operator_declarationContext(Context, State); - EnterRule(_localctx, 106, RULE_operator_declaration); - try { - State = 729; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__14: - EnterOuterAlt(_localctx, 1); - { - State = 726; - prefix_operator_declaration(); - } - break; - case T__16: - EnterOuterAlt(_localctx, 2); - { - State = 727; - postfix_operator_declaration(); - } - break; - case T__17: - EnterOuterAlt(_localctx, 3); - { - State = 728; - infix_operator_declaration(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Prefix_operator_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - public Prefix_operator_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_prefix_operator_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrefix_operator_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrefix_operator_declaration(this); - } - } - - [RuleVersion(0)] - public Prefix_operator_declarationContext prefix_operator_declaration() { - Prefix_operator_declarationContext _localctx = new Prefix_operator_declarationContext(Context, State); - EnterRule(_localctx, 108, RULE_prefix_operator_declaration); - try { - EnterOuterAlt(_localctx, 1); - { - State = 731; - Match(T__14); - State = 732; - Match(T__15); - State = 733; - @operator(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Postfix_operator_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - public Postfix_operator_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_postfix_operator_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPostfix_operator_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPostfix_operator_declaration(this); - } - } - - [RuleVersion(0)] - public Postfix_operator_declarationContext postfix_operator_declaration() { - Postfix_operator_declarationContext _localctx = new Postfix_operator_declarationContext(Context, State); - EnterRule(_localctx, 110, RULE_postfix_operator_declaration); - try { - EnterOuterAlt(_localctx, 1); - { - State = 735; - Match(T__16); - State = 736; - Match(T__15); - State = 737; - @operator(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Infix_operator_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Infix_operator_groupContext infix_operator_group() { - return GetRuleContext(0); - } - public Infix_operator_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_infix_operator_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInfix_operator_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInfix_operator_declaration(this); - } - } - - [RuleVersion(0)] - public Infix_operator_declarationContext infix_operator_declaration() { - Infix_operator_declarationContext _localctx = new Infix_operator_declarationContext(Context, State); - EnterRule(_localctx, 112, RULE_infix_operator_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 739; - Match(T__17); - State = 740; - Match(T__15); - State = 741; - @operator(); - State = 743; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 742; - infix_operator_group(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Infix_operator_groupContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name() { - return GetRuleContext(0); - } - public Infix_operator_groupContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_infix_operator_group; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInfix_operator_group(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInfix_operator_group(this); - } - } - - [RuleVersion(0)] - public Infix_operator_groupContext infix_operator_group() { - Infix_operator_groupContext _localctx = new Infix_operator_groupContext(Context, State); - EnterRule(_localctx, 114, RULE_infix_operator_group); - try { - EnterOuterAlt(_localctx, 1); - { - State = 745; - Match(OpColon); - State = 746; - precedence_group_name(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_attributeContext[] precedence_group_attribute() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_attributeContext precedence_group_attribute(int i) { - return GetRuleContext(i); - } - public Precedence_group_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_declaration(this); - } - } - - [RuleVersion(0)] - public Precedence_group_declarationContext precedence_group_declaration() { - Precedence_group_declarationContext _localctx = new Precedence_group_declarationContext(Context, State); - EnterRule(_localctx, 116, RULE_precedence_group_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 748; - Match(T__18); - State = 749; - precedence_group_name(); - State = 750; - Match(OpLBrace); - State = 754; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22))) != 0)) { - { - { - State = 751; - precedence_group_attribute(); - } - } - State = 756; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 757; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_attributeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_relationContext precedence_group_relation() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_assignmentContext precedence_group_assignment() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_associativityContext precedence_group_associativity() { - return GetRuleContext(0); - } - public Precedence_group_attributeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_attribute; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_attribute(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_attribute(this); - } - } - - [RuleVersion(0)] - public Precedence_group_attributeContext precedence_group_attribute() { - Precedence_group_attributeContext _localctx = new Precedence_group_attributeContext(Context, State); - EnterRule(_localctx, 118, RULE_precedence_group_attribute); - try { - State = 762; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__19: - case T__20: - EnterOuterAlt(_localctx, 1); - { - State = 759; - precedence_group_relation(); - } - break; - case T__21: - EnterOuterAlt(_localctx, 2); - { - State = 760; - precedence_group_assignment(); - } - break; - case T__22: - EnterOuterAlt(_localctx, 3); - { - State = 761; - precedence_group_associativity(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_relationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_namesContext precedence_group_names() { - return GetRuleContext(0); - } - public Precedence_group_relationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_relation; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_relation(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_relation(this); - } - } - - [RuleVersion(0)] - public Precedence_group_relationContext precedence_group_relation() { - Precedence_group_relationContext _localctx = new Precedence_group_relationContext(Context, State); - EnterRule(_localctx, 120, RULE_precedence_group_relation); - try { - State = 770; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__19: - EnterOuterAlt(_localctx, 1); - { - State = 764; - Match(T__19); - State = 765; - Match(OpColon); - State = 766; - precedence_group_names(); - } - break; - case T__20: - EnterOuterAlt(_localctx, 2); - { - State = 767; - Match(T__20); - State = 768; - Match(OpColon); - State = 769; - precedence_group_names(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_assignmentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { - return GetRuleContext(0); - } - public Precedence_group_assignmentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_assignment; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_assignment(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_assignment(this); - } - } - - [RuleVersion(0)] - public Precedence_group_assignmentContext precedence_group_assignment() { - Precedence_group_assignmentContext _localctx = new Precedence_group_assignmentContext(Context, State); - EnterRule(_localctx, 122, RULE_precedence_group_assignment); - try { - EnterOuterAlt(_localctx, 1); - { - State = 772; - Match(T__21); - State = 773; - Match(OpColon); - State = 774; - boolean_literal(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_associativityContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public AssociativityContext associativity() { - return GetRuleContext(0); - } - public Precedence_group_associativityContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_associativity; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_associativity(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_associativity(this); - } - } - - [RuleVersion(0)] - public Precedence_group_associativityContext precedence_group_associativity() { - Precedence_group_associativityContext _localctx = new Precedence_group_associativityContext(Context, State); - EnterRule(_localctx, 124, RULE_precedence_group_associativity); - try { - EnterOuterAlt(_localctx, 1); - { - State = 776; - Match(T__22); - State = 777; - Match(OpColon); - State = 778; - associativity(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class AssociativityContext : ParserRuleContext { - public AssociativityContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_associativity; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAssociativity(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAssociativity(this); - } - } - - [RuleVersion(0)] - public AssociativityContext associativity() { - AssociativityContext _localctx = new AssociativityContext(Context, State); - EnterRule(_localctx, 126, RULE_associativity); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 780; - _la = TokenStream.LA(1); - if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__23) | (1L << T__24) | (1L << T__25))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_namesContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext[] precedence_group_name() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Precedence_group_nameContext precedence_group_name(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Precedence_group_namesContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_names; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_names(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_names(this); - } - } - - [RuleVersion(0)] - public Precedence_group_namesContext precedence_group_names() { - Precedence_group_namesContext _localctx = new Precedence_group_namesContext(Context, State); - EnterRule(_localctx, 128, RULE_precedence_group_names); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 782; - precedence_group_name(); - State = 787; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 783; - Match(OpComma); - State = 784; - precedence_group_name(); - } - } - State = 789; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Precedence_group_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Precedence_group_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_precedence_group_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPrecedence_group_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPrecedence_group_name(this); - } - } - - [RuleVersion(0)] - public Precedence_group_nameContext precedence_group_name() { - Precedence_group_nameContext _localctx = new Precedence_group_nameContext(Context, State); - EnterRule(_localctx, 130, RULE_precedence_group_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 790; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Extension_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Extension_bodyContext extension_body() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - public Extension_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_extension_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterExtension_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitExtension_declaration(this); - } - } - - [RuleVersion(0)] - public Extension_declarationContext extension_declaration() { - Extension_declarationContext _localctx = new Extension_declarationContext(Context, State); - EnterRule(_localctx, 132, RULE_extension_declaration); - int _la; - try { - State = 816; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,87,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 793; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 792; - attributes(); - } - } - - State = 796; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 795; - access_level_modifier(); - } - } - - State = 798; - Match(T__26); - State = 799; - type_identifier(); - State = 801; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 800; - type_inheritance_clause(); - } - } - - State = 803; - extension_body(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 806; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 805; - attributes(); - } - } - - State = 809; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 808; - access_level_modifier(); - } - } - - State = 811; - Match(T__26); - State = 812; - type_identifier(); - State = 813; - generic_where_clause(); - State = 814; - extension_body(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Extension_bodyContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Extension_memberContext[] extension_member() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Extension_memberContext extension_member(int i) { - return GetRuleContext(i); - } - public Extension_bodyContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_extension_body; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterExtension_body(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitExtension_body(this); - } - } - - [RuleVersion(0)] - public Extension_bodyContext extension_body() { - Extension_bodyContext _localctx = new Extension_bodyContext(Context, State); - EnterRule(_localctx, 134, RULE_extension_body); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 818; - Match(OpLBrace); - State = 822; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__26) | (1L << T__27) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) || _la==OpAt) { - { - { - State = 819; - extension_member(); - } - } - State = 824; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 825; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Extension_memberContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public DeclarationContext declaration() { - return GetRuleContext(0); - } - public Extension_memberContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_extension_member; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterExtension_member(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitExtension_member(this); - } - } - - [RuleVersion(0)] - public Extension_memberContext extension_member() { - Extension_memberContext _localctx = new Extension_memberContext(Context, State); - EnterRule(_localctx, 136, RULE_extension_member); - try { - EnterOuterAlt(_localctx, 1); - { - State = 827; - declaration(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Subscript_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Subscript_headContext subscript_head() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Subscript_resultContext subscript_result() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Getter_setter_keyword_blockContext getter_setter_keyword_block() { - return GetRuleContext(0); - } - public Subscript_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_subscript_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSubscript_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSubscript_declaration(this); - } - } - - [RuleVersion(0)] - public Subscript_declarationContext subscript_declaration() { - Subscript_declarationContext _localctx = new Subscript_declarationContext(Context, State); - EnterRule(_localctx, 138, RULE_subscript_declaration); - try { - State = 836; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,89,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 829; - subscript_head(); - State = 830; - subscript_result(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 832; - subscript_head(); - State = 833; - subscript_result(); - State = 834; - getter_setter_keyword_block(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Subscript_headContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { - return GetRuleContext(0); - } - public Subscript_headContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_subscript_head; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSubscript_head(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSubscript_head(this); - } - } - - [RuleVersion(0)] - public Subscript_headContext subscript_head() { - Subscript_headContext _localctx = new Subscript_headContext(Context, State); - EnterRule(_localctx, 140, RULE_subscript_head); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 839; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 838; - attributes(); - } - } - - State = 842; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 841; - declaration_modifiers(); - } - } - - State = 844; - Match(T__27); - State = 845; - parameter_clause(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Subscript_resultContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - public Subscript_resultContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_subscript_result; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSubscript_result(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSubscript_result(this); - } - } - - [RuleVersion(0)] - public Subscript_resultContext subscript_result() { - Subscript_resultContext _localctx = new Subscript_resultContext(Context, State); - EnterRule(_localctx, 142, RULE_subscript_result); - try { - EnterOuterAlt(_localctx, 1); - { - State = 847; - arrow_operator(); - State = 849; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,92,Context) ) { - case 1: - { - State = 848; - attributes(); - } - break; - } - State = 851; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_associated_type_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Typealias_nameContext typealias_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_clauseContext type_inheritance_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Typealias_assignmentContext typealias_assignment() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - public Protocol_associated_type_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_associated_type_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_associated_type_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_associated_type_declaration(this); - } - } - - [RuleVersion(0)] - public Protocol_associated_type_declarationContext protocol_associated_type_declaration() { - Protocol_associated_type_declarationContext _localctx = new Protocol_associated_type_declarationContext(Context, State); - EnterRule(_localctx, 144, RULE_protocol_associated_type_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 854; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 853; - attributes(); - } - } - - State = 857; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49))) != 0)) { - { - State = 856; - access_level_modifier(); - } - } - - State = 859; - Match(T__28); - State = 860; - typealias_name(); - State = 862; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpColon) { - { - State = 861; - type_inheritance_clause(); - } - } - - State = 865; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAssign) { - { - State = 864; - typealias_assignment(); - } - } - - State = 868; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 867; - generic_where_clause(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Function_headContext function_head() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_nameContext function_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_signatureContext function_signature() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_bodyContext function_body() { - return GetRuleContext(0); - } - public Function_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_declaration(this); - } - } - - [RuleVersion(0)] - public Function_declarationContext function_declaration() { - Function_declarationContext _localctx = new Function_declarationContext(Context, State); - EnterRule(_localctx, 146, RULE_function_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 870; - function_head(); - State = 871; - function_name(); - State = 873; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 872; - generic_parameter_clause(); - } - } - - State = 875; - function_signature(); - State = 877; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 876; - generic_where_clause(); - } - } - - State = 880; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLBrace) { - { - State = 879; - function_body(); - } - } - - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_headContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { - return GetRuleContext(0); - } - public Function_headContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_head; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_head(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_head(this); - } - } - - [RuleVersion(0)] - public Function_headContext function_head() { - Function_headContext _localctx = new Function_headContext(Context, State); - EnterRule(_localctx, 148, RULE_function_head); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 883; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 882; - attributes(); - } - } - - State = 886; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 885; - declaration_modifiers(); - } - } - - State = 888; - Match(T__7); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Operator_nameContext operator_name() { - return GetRuleContext(0); - } - public Function_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_name(this); - } - } - - [RuleVersion(0)] - public Function_nameContext function_name() { - Function_nameContext _localctx = new Function_nameContext(Context, State); - EnterRule(_localctx, 150, RULE_function_name); - try { - State = 892; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__9: - case T__10: - case T__11: - case T__13: - case T__14: - case T__16: - case T__17: - case T__19: - case T__20: - case T__21: - case T__22: - case T__23: - case T__24: - case T__25: - case T__34: - case T__35: - case T__36: - case T__37: - case T__38: - case T__39: - case T__41: - case T__42: - case T__43: - case T__44: - case T__49: - case T__50: - case T__51: - case T__54: - case T__55: - case T__67: - case T__68: - case T__69: - case T__70: - case T__71: - case T__72: - case T__73: - case T__74: - case T__75: - case T__76: - case T__77: - case T__78: - case T__79: - case T__80: - case T__81: - case T__82: - case T__83: - case T__84: - case T__85: - case T__86: - case T__87: - case T__88: - case T__89: - case T__90: - case T__91: - case Identifier: - EnterOuterAlt(_localctx, 1); - { - State = 890; - declaration_identifier(); - } - break; - case T__64: - case Operator: - EnterOuterAlt(_localctx, 2); - { - State = 891; - operator_name(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_bodyContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext[] dyckSubExpression() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext dyckSubExpression(int i) { - return GetRuleContext(i); - } - public Function_bodyContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_body; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_body(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_body(this); - } - } - - [RuleVersion(0)] - public Function_bodyContext function_body() { - Function_bodyContext _localctx = new Function_bodyContext(Context, State); - EnterRule(_localctx, 152, RULE_function_body); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 894; - Match(OpLBrace); - State = 898; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { - { - { - State = 895; - dyckSubExpression(); - } - } - State = 900; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 901; - Match(OpRBrace); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Operator_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - public Operator_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_operator_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOperator_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOperator_name(this); - } - } - - [RuleVersion(0)] - public Operator_nameContext operator_name() { - Operator_nameContext _localctx = new Operator_nameContext(Context, State); - EnterRule(_localctx, 154, RULE_operator_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 903; - @operator(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_signatureContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Async_clauseContext async_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Throws_clauseContext throws_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Function_resultContext function_result() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Rethrows_clauseContext rethrows_clause() { - return GetRuleContext(0); - } - public Function_signatureContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_signature; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_signature(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_signature(this); - } - } - - [RuleVersion(0)] - public Function_signatureContext function_signature() { - Function_signatureContext _localctx = new Function_signatureContext(Context, State); - EnterRule(_localctx, 156, RULE_function_signature); - int _la; - try { - State = 923; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,110,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 905; - parameter_clause(); - State = 907; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__29) { - { - State = 906; - async_clause(); - } - } - - State = 910; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__30) { - { - State = 909; - throws_clause(); - } - } - - State = 913; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__65) { - { - State = 912; - function_result(); - } - } - - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 915; - parameter_clause(); - State = 917; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__29) { - { - State = 916; - async_clause(); - } - } - - State = 919; - rethrows_clause(); - State = 921; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__65) { - { - State = 920; - function_result(); - } - } - - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Async_clauseContext : ParserRuleContext { - public Async_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_async_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAsync_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAsync_clause(this); - } - } - - [RuleVersion(0)] - public Async_clauseContext async_clause() { - Async_clauseContext _localctx = new Async_clauseContext(Context, State); - EnterRule(_localctx, 158, RULE_async_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 925; - Match(T__29); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Throws_clauseContext : ParserRuleContext { - public Throws_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_throws_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterThrows_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitThrows_clause(this); - } - } - - [RuleVersion(0)] - public Throws_clauseContext throws_clause() { - Throws_clauseContext _localctx = new Throws_clauseContext(Context, State); - EnterRule(_localctx, 160, RULE_throws_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 927; - Match(T__30); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Rethrows_clauseContext : ParserRuleContext { - public Rethrows_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_rethrows_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRethrows_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRethrows_clause(this); - } - } - - [RuleVersion(0)] - public Rethrows_clauseContext rethrows_clause() { - Rethrows_clauseContext _localctx = new Rethrows_clauseContext(Context, State); - EnterRule(_localctx, 162, RULE_rethrows_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 929; - Match(T__31); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_resultContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - public Function_resultContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_result; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_result(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_result(this); - } - } - - [RuleVersion(0)] - public Function_resultContext function_result() { - Function_resultContext _localctx = new Function_resultContext(Context, State); - EnterRule(_localctx, 164, RULE_function_result); - try { - EnterOuterAlt(_localctx, 1); - { - State = 931; - arrow_operator(); - State = 933; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,111,Context) ) { - case 1: - { - State = 932; - attributes(); - } - break; - } - State = 935; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Initializer_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Initializer_headContext initializer_head() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Parameter_clauseContext parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_clauseContext generic_parameter_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Throws_clauseContext throws_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_where_clauseContext generic_where_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Rethrows_clauseContext rethrows_clause() { - return GetRuleContext(0); - } - public Initializer_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_initializer_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInitializer_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInitializer_declaration(this); - } - } - - [RuleVersion(0)] - public Initializer_declarationContext initializer_declaration() { - Initializer_declarationContext _localctx = new Initializer_declarationContext(Context, State); - EnterRule(_localctx, 166, RULE_initializer_declaration); - int _la; - try { - State = 957; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,117,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 937; - initializer_head(); - State = 939; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 938; - generic_parameter_clause(); - } - } - - State = 941; - parameter_clause(); - State = 943; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__30) { - { - State = 942; - throws_clause(); - } - } - - State = 946; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 945; - generic_where_clause(); - } - } - - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 948; - initializer_head(); - State = 950; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpLess) { - { - State = 949; - generic_parameter_clause(); - } - } - - State = 952; - parameter_clause(); - State = 953; - rethrows_clause(); - State = 955; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__63) { - { - State = 954; - generic_where_clause(); - } - } - - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Initializer_headContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } - public Initializer_headContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_initializer_head; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInitializer_head(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInitializer_head(this); - } - } - - [RuleVersion(0)] - public Initializer_headContext initializer_head() { - Initializer_headContext _localctx = new Initializer_headContext(Context, State); - EnterRule(_localctx, 168, RULE_initializer_head); - int _la; - try { - State = 982; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,124,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 960; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 959; - attributes(); - } - } - - State = 963; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 962; - declaration_modifiers(); - } - } - - State = 965; - Match(T__32); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 967; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 966; - attributes(); - } - } - - State = 970; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 969; - declaration_modifiers(); - } - } - - State = 972; - Match(T__32); - State = 973; - Match(OpQuestion); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 975; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 974; - attributes(); - } - } - - State = 978; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 977; - declaration_modifiers(); - } - } - - State = 980; - Match(T__32); - State = 981; - Match(OpBang); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Deinitializer_declarationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifiersContext declaration_modifiers() { - return GetRuleContext(0); - } - public Deinitializer_declarationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_deinitializer_declaration; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDeinitializer_declaration(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDeinitializer_declaration(this); - } - } - - [RuleVersion(0)] - public Deinitializer_declarationContext deinitializer_declaration() { - Deinitializer_declarationContext _localctx = new Deinitializer_declarationContext(Context, State); - EnterRule(_localctx, 170, RULE_deinitializer_declaration); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 985; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 984; - attributes(); - } - } - - State = 988; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0)) { - { - State = 987; - declaration_modifiers(); - } - } - - State = 990; - Match(T__33); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Parameter_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Parameter_listContext parameter_list() { - return GetRuleContext(0); - } - public Parameter_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_parameter_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterParameter_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitParameter_clause(this); - } - } - - [RuleVersion(0)] - public Parameter_clauseContext parameter_clause() { - Parameter_clauseContext _localctx = new Parameter_clauseContext(Context, State); - EnterRule(_localctx, 172, RULE_parameter_clause); - try { - State = 998; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,127,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 992; - Match(OpLParen); - State = 993; - Match(OpRParen); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 994; - Match(OpLParen); - State = 995; - parameter_list(); - State = 996; - Match(OpRParen); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Parameter_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ParameterContext[] parameter() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public ParameterContext parameter(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Parameter_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_parameter_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterParameter_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitParameter_list(this); - } - } - - [RuleVersion(0)] - public Parameter_listContext parameter_list() { - Parameter_listContext _localctx = new Parameter_listContext(Context, State); - EnterRule(_localctx, 174, RULE_parameter_list); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1000; - parameter(); - State = 1005; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 1001; - Match(OpComma); - State = 1002; - parameter(); - } - } - State = 1007; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class ParameterContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Local_parameter_nameContext local_parameter_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public External_parameter_nameContext external_parameter_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public DefaultInitializerContext defaultInitializer() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Range_operatorContext range_operator() { - return GetRuleContext(0); - } - public ParameterContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_parameter; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterParameter(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitParameter(this); - } - } - - [RuleVersion(0)] - public ParameterContext parameter() { - ParameterContext _localctx = new ParameterContext(Context, State); - EnterRule(_localctx, 176, RULE_parameter); - int _la; - try { - State = 1023; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,132,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1009; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,129,Context) ) { - case 1: - { - State = 1008; - external_parameter_name(); - } - break; - } - State = 1011; - local_parameter_name(); - State = 1012; - type_annotation(); - State = 1014; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAssign) { - { - State = 1013; - defaultInitializer(); - } - } - - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1017; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,131,Context) ) { - case 1: - { - State = 1016; - external_parameter_name(); - } - break; - } - State = 1019; - local_parameter_name(); - State = 1020; - type_annotation(); - State = 1021; - range_operator(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class External_parameter_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { - return GetRuleContext(0); - } - public External_parameter_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_external_parameter_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterExternal_parameter_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitExternal_parameter_name(this); - } - } - - [RuleVersion(0)] - public External_parameter_nameContext external_parameter_name() { - External_parameter_nameContext _localctx = new External_parameter_nameContext(Context, State); - EnterRule(_localctx, 178, RULE_external_parameter_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1025; - label_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Local_parameter_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { - return GetRuleContext(0); - } - public Local_parameter_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_local_parameter_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterLocal_parameter_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitLocal_parameter_name(this); - } - } - - [RuleVersion(0)] - public Local_parameter_nameContext local_parameter_name() { - Local_parameter_nameContext _localctx = new Local_parameter_nameContext(Context, State); - EnterRule(_localctx, 180, RULE_local_parameter_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1027; - label_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class DefaultInitializerContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } - [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext[] dyckExpression() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext dyckExpression(int i) { - return GetRuleContext(i); - } - public DefaultInitializerContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_defaultInitializer; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDefaultInitializer(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDefaultInitializer(this); - } - } - - [RuleVersion(0)] - public DefaultInitializerContext defaultInitializer() { - DefaultInitializerContext _localctx = new DefaultInitializerContext(Context, State); - EnterRule(_localctx, 182, RULE_defaultInitializer); - try { - int _alt; - EnterOuterAlt(_localctx, 1); - { - State = 1029; - Match(OpAssign); - State = 1031; - ErrorHandler.Sync(this); - _alt = 1; - do { - switch (_alt) { - case 1: - { - { - State = 1030; - dyckExpression(); - } - } - break; - default: - throw new NoViableAltException(this); - } - State = 1033; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,133,Context); - } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class DyckExpressionContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext[] dyckSubExpression() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public DyckSubExpressionContext dyckSubExpression(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public LiteralContext literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public DotSymbolContext dotSymbol() { - return GetRuleContext(0); - } - public DyckExpressionContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_dyckExpression; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDyckExpression(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDyckExpression(this); - } - } - - [RuleVersion(0)] - public DyckExpressionContext dyckExpression() { - DyckExpressionContext _localctx = new DyckExpressionContext(Context, State); - EnterRule(_localctx, 184, RULE_dyckExpression); - int _la; - try { - State = 1063; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,137,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1035; - Match(OpLParen); - State = 1039; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { - { - { - State = 1036; - dyckSubExpression(); - } - } - State = 1041; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 1042; - Match(OpRParen); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1043; - Match(OpLBracket); - State = 1047; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { - { - { - State = 1044; - dyckSubExpression(); - } - } - State = 1049; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 1050; - Match(OpRBracket); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1051; - Match(OpLBrace); - State = 1055; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpAmp - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 128)) & ~0x3f) == 0 && ((1L << (_la - 128)) & ((1L << (OpBang - 128)) | (1L << (OpDot - 128)) | (1L << (OpComma - 128)) | (1L << (OpTilde - 128)) | (1L << (OpColon - 128)) | (1L << (OpSemi - 128)) | (1L << (OpAt - 128)) | (1L << (OpPound - 128)) | (1L << (OpBackTick - 128)) | (1L << (OpUnder - 128)) | (1L << (OpLParen - 128)) | (1L << (OpLBracket - 128)) | (1L << (OpLBrace - 128)) | (1L << (Operator - 128)) | (1L << (OpGreater - 128)))) != 0)) { - { - { - State = 1052; - dyckSubExpression(); - } - } - State = 1057; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - State = 1058; - Match(OpRBrace); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 1059; - label_identifier(); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 1060; - literal(); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 1061; - @operator(); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 1062; - dotSymbol(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class DyckSubExpressionContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public DyckExpressionContext dyckExpression() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Any_other_things_for_dyck_expressionContext any_other_things_for_dyck_expression() { - return GetRuleContext(0); - } - public DyckSubExpressionContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_dyckSubExpression; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDyckSubExpression(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDyckSubExpression(this); - } - } - - [RuleVersion(0)] - public DyckSubExpressionContext dyckSubExpression() { - DyckSubExpressionContext _localctx = new DyckSubExpressionContext(Context, State); - EnterRule(_localctx, 186, RULE_dyckSubExpression); - try { - State = 1067; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,138,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1065; - dyckExpression(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1066; - any_other_things_for_dyck_expression(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Any_other_things_for_dyck_expressionContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpSemi() { return GetToken(SwiftInterfaceParser.OpSemi, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPound() { return GetToken(SwiftInterfaceParser.OpPound, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBackTick() { return GetToken(SwiftInterfaceParser.OpBackTick, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpUnder() { return GetToken(SwiftInterfaceParser.OpUnder, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPlus() { return GetToken(SwiftInterfaceParser.OpPlus, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpMinus() { return GetToken(SwiftInterfaceParser.OpMinus, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAmp() { return GetToken(SwiftInterfaceParser.OpAmp, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpTilde() { return GetToken(SwiftInterfaceParser.OpTilde, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpGreater() { return GetToken(SwiftInterfaceParser.OpGreater, 0); } - [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { - return GetRuleContext(0); - } - public Any_other_things_for_dyck_expressionContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_any_other_things_for_dyck_expression; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAny_other_things_for_dyck_expression(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAny_other_things_for_dyck_expression(this); - } - } - - [RuleVersion(0)] - public Any_other_things_for_dyck_expressionContext any_other_things_for_dyck_expression() { - Any_other_things_for_dyck_expressionContext _localctx = new Any_other_things_for_dyck_expressionContext(Context, State); - EnterRule(_localctx, 188, RULE_any_other_things_for_dyck_expression); - try { - State = 1089; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__64: - case OpPlus: - case OpMinus: - case OpAssign: - case OpAmp: - case OpQuestion: - case OpBang: - case OpDot: - case OpComma: - case OpTilde: - case OpColon: - case OpSemi: - case OpAt: - case OpPound: - case OpBackTick: - case OpUnder: - case OpGreater: - EnterOuterAlt(_localctx, 1); - { - State = 1086; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case OpDot: - { - State = 1069; - Match(OpDot); - } - break; - case OpComma: - { - State = 1070; - Match(OpComma); - } - break; - case OpColon: - { - State = 1071; - Match(OpColon); - } - break; - case OpSemi: - { - State = 1072; - Match(OpSemi); - } - break; - case OpAssign: - { - State = 1073; - Match(OpAssign); - } - break; - case OpAt: - { - State = 1074; - Match(OpAt); - } - break; - case OpPound: - { - State = 1075; - Match(OpPound); - } - break; - case OpBackTick: - { - State = 1076; - Match(OpBackTick); - } - break; - case OpQuestion: - { - State = 1077; - Match(OpQuestion); - } - break; - case OpUnder: - { - State = 1078; - Match(OpUnder); - } - break; - case OpPlus: - { - State = 1079; - Match(OpPlus); - } - break; - case OpMinus: - { - State = 1080; - Match(OpMinus); - } - break; - case OpAmp: - { - State = 1081; - Match(OpAmp); - } - break; - case OpBang: - { - State = 1082; - Match(OpBang); - } - break; - case OpTilde: - { - State = 1083; - Match(OpTilde); - } - break; - case OpGreater: - { - State = 1084; - Match(OpGreater); - } - break; - case T__64: - { - State = 1085; - opGreater(); - } - break; - default: - throw new NoViableAltException(this); - } - } - break; - case T__65: - EnterOuterAlt(_localctx, 2); - { - State = 1088; - arrow_operator(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class DotSymbolContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public DotSymbolContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_dotSymbol; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDotSymbol(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDotSymbol(this); - } - } - - [RuleVersion(0)] - public DotSymbolContext dotSymbol() { - DotSymbolContext _localctx = new DotSymbolContext(Context, State); - EnterRule(_localctx, 190, RULE_dotSymbol); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1091; - Match(OpDot); - State = 1092; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Declaration_identifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Identifier() { return GetToken(SwiftInterfaceParser.Identifier, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Keyword_as_identifier_in_declarationsContext keyword_as_identifier_in_declarations() { - return GetRuleContext(0); - } - public Declaration_identifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_declaration_identifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDeclaration_identifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDeclaration_identifier(this); - } - } - - [RuleVersion(0)] - public Declaration_identifierContext declaration_identifier() { - Declaration_identifierContext _localctx = new Declaration_identifierContext(Context, State); - EnterRule(_localctx, 192, RULE_declaration_identifier); - try { - State = 1096; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case Identifier: - EnterOuterAlt(_localctx, 1); - { - State = 1094; - Match(Identifier); - } - break; - case T__9: - case T__10: - case T__11: - case T__13: - case T__14: - case T__16: - case T__17: - case T__19: - case T__20: - case T__21: - case T__22: - case T__23: - case T__24: - case T__25: - case T__34: - case T__35: - case T__36: - case T__37: - case T__38: - case T__39: - case T__41: - case T__42: - case T__43: - case T__44: - case T__49: - case T__50: - case T__51: - case T__54: - case T__55: - case T__67: - case T__68: - case T__69: - case T__70: - case T__71: - case T__72: - case T__73: - case T__74: - case T__75: - case T__76: - case T__77: - case T__78: - case T__79: - case T__80: - case T__81: - case T__82: - case T__83: - case T__84: - case T__85: - case T__86: - case T__87: - case T__88: - case T__89: - case T__90: - case T__91: - EnterOuterAlt(_localctx, 2); - { - State = 1095; - keyword_as_identifier_in_declarations(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Type_inheritance_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Class_requirementContext class_requirement() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_listContext type_inheritance_list() { - return GetRuleContext(0); - } - public Type_inheritance_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type_inheritance_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterType_inheritance_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitType_inheritance_clause(this); - } - } - - [RuleVersion(0)] - public Type_inheritance_clauseContext type_inheritance_clause() { - Type_inheritance_clauseContext _localctx = new Type_inheritance_clauseContext(Context, State); - EnterRule(_localctx, 194, RULE_type_inheritance_clause); - try { - State = 1107; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,142,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1098; - Match(OpColon); - State = 1099; - class_requirement(); - State = 1100; - Match(OpComma); - State = 1101; - type_inheritance_list(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1103; - Match(OpColon); - State = 1104; - class_requirement(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1105; - Match(OpColon); - State = 1106; - type_inheritance_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Type_inheritance_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Type_inheritance_listContext type_inheritance_list() { - return GetRuleContext(0); - } - public Type_inheritance_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type_inheritance_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterType_inheritance_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitType_inheritance_list(this); - } - } - - [RuleVersion(0)] - public Type_inheritance_listContext type_inheritance_list() { - Type_inheritance_listContext _localctx = new Type_inheritance_listContext(Context, State); - EnterRule(_localctx, 196, RULE_type_inheritance_list); - try { - State = 1114; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,143,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1109; - type_identifier(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1110; - type_identifier(); - State = 1111; - Match(OpComma); - State = 1112; - type_inheritance_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Class_requirementContext : ParserRuleContext { - public Class_requirementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_class_requirement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterClass_requirement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitClass_requirement(this); - } - } - - [RuleVersion(0)] - public Class_requirementContext class_requirement() { - Class_requirementContext _localctx = new Class_requirementContext(Context, State); - EnterRule(_localctx, 198, RULE_class_requirement); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1116; - Match(T__3); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class AttributeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Attribute_nameContext attribute_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Attribute_argument_clauseContext attribute_argument_clause() { - return GetRuleContext(0); - } - public AttributeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_attribute; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAttribute(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAttribute(this); - } - } - - [RuleVersion(0)] - public AttributeContext attribute() { - AttributeContext _localctx = new AttributeContext(Context, State); - EnterRule(_localctx, 200, RULE_attribute); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1118; - Match(OpAt); - State = 1119; - attribute_name(); - State = 1121; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,144,Context) ) { - case 1: - { - State = 1120; - attribute_argument_clause(); - } - break; - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Attribute_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - public Attribute_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_attribute_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAttribute_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAttribute_name(this); - } - } - - [RuleVersion(0)] - public Attribute_nameContext attribute_name() { - Attribute_nameContext _localctx = new Attribute_nameContext(Context, State); - EnterRule(_localctx, 202, RULE_attribute_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1123; - type_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Attribute_argument_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokensContext balanced_tokens() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - public Attribute_argument_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_attribute_argument_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAttribute_argument_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAttribute_argument_clause(this); - } - } - - [RuleVersion(0)] - public Attribute_argument_clauseContext attribute_argument_clause() { - Attribute_argument_clauseContext _localctx = new Attribute_argument_clauseContext(Context, State); - EnterRule(_localctx, 204, RULE_attribute_argument_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1125; - Match(OpLParen); - State = 1126; - balanced_tokens(); - State = 1127; - Match(OpRParen); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class AttributesContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public AttributeContext[] attribute() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributeContext attribute(int i) { - return GetRuleContext(i); - } - public AttributesContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_attributes; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAttributes(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAttributes(this); - } - } - - [RuleVersion(0)] - public AttributesContext attributes() { - AttributesContext _localctx = new AttributesContext(Context, State); - EnterRule(_localctx, 206, RULE_attributes); - try { - int _alt; - EnterOuterAlt(_localctx, 1); - { - State = 1130; - ErrorHandler.Sync(this); - _alt = 1; - do { - switch (_alt) { - case 1: - { - { - State = 1129; - attribute(); - } - } - break; - default: - throw new NoViableAltException(this); - } - State = 1132; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,145,Context); - } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Balanced_tokensContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokenContext[] balanced_token() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokenContext balanced_token(int i) { - return GetRuleContext(i); - } - public Balanced_tokensContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_balanced_tokens; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterBalanced_tokens(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitBalanced_tokens(this); - } - } - - [RuleVersion(0)] - public Balanced_tokensContext balanced_tokens() { - Balanced_tokensContext _localctx = new Balanced_tokensContext(Context, State); - EnterRule(_localctx, 208, RULE_balanced_tokens); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1137; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__64 - 64)) | (1L << (T__65 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Binary_literal - 64)) | (1L << (Octal_literal - 64)) | (1L << (Decimal_literal - 64)) | (1L << (Pure_decimal_digits - 64)) | (1L << (Hexadecimal_literal - 64)) | (1L << (Static_string_literal - 64)) | (1L << (Identifier - 64)) | (1L << (OpPlus - 64)) | (1L << (OpMinus - 64)) | (1L << (OpAssign - 64)) | (1L << (OpQuestion - 64)))) != 0) || ((((_la - 129)) & ~0x3f) == 0 && ((1L << (_la - 129)) & ((1L << (OpDot - 129)) | (1L << (OpComma - 129)) | (1L << (OpColon - 129)) | (1L << (OpSemi - 129)) | (1L << (OpAt - 129)) | (1L << (OpPound - 129)) | (1L << (OpBackTick - 129)) | (1L << (OpLParen - 129)) | (1L << (OpLBracket - 129)) | (1L << (OpLBrace - 129)) | (1L << (Operator - 129)))) != 0)) { - { - { - State = 1134; - balanced_token(); - } - } - State = 1139; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Balanced_tokenContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Balanced_tokensContext balanced_tokens() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBrace() { return GetToken(SwiftInterfaceParser.OpLBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBrace() { return GetToken(SwiftInterfaceParser.OpRBrace, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public LiteralContext literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Any_punctuation_for_balanced_tokenContext any_punctuation_for_balanced_token() { - return GetRuleContext(0); - } - public Balanced_tokenContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_balanced_token; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterBalanced_token(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitBalanced_token(this); - } - } - - [RuleVersion(0)] - public Balanced_tokenContext balanced_token() { - Balanced_tokenContext _localctx = new Balanced_tokenContext(Context, State); - EnterRule(_localctx, 210, RULE_balanced_token); - try { - State = 1156; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,147,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1140; - Match(OpLParen); - State = 1141; - balanced_tokens(); - State = 1142; - Match(OpRParen); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1144; - Match(OpLBracket); - State = 1145; - balanced_tokens(); - State = 1146; - Match(OpRBracket); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1148; - Match(OpLBrace); - State = 1149; - balanced_tokens(); - State = 1150; - Match(OpRBrace); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 1152; - label_identifier(); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 1153; - literal(); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 1154; - @operator(); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 1155; - any_punctuation_for_balanced_token(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Any_punctuation_for_balanced_tokenContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpSemi() { return GetToken(SwiftInterfaceParser.OpSemi, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAssign() { return GetToken(SwiftInterfaceParser.OpAssign, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAt() { return GetToken(SwiftInterfaceParser.OpAt, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPound() { return GetToken(SwiftInterfaceParser.OpPound, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBackTick() { return GetToken(SwiftInterfaceParser.OpBackTick, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { - return GetRuleContext(0); - } - public Any_punctuation_for_balanced_tokenContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_any_punctuation_for_balanced_token; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAny_punctuation_for_balanced_token(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAny_punctuation_for_balanced_token(this); - } - } - - [RuleVersion(0)] - public Any_punctuation_for_balanced_tokenContext any_punctuation_for_balanced_token() { - Any_punctuation_for_balanced_tokenContext _localctx = new Any_punctuation_for_balanced_tokenContext(Context, State); - EnterRule(_localctx, 212, RULE_any_punctuation_for_balanced_token); - int _la; - try { - State = 1160; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case OpAssign: - case OpQuestion: - case OpDot: - case OpComma: - case OpColon: - case OpSemi: - case OpAt: - case OpPound: - case OpBackTick: - EnterOuterAlt(_localctx, 1); - { - State = 1158; - _la = TokenStream.LA(1); - if ( !(((((_la - 124)) & ~0x3f) == 0 && ((1L << (_la - 124)) & ((1L << (OpAssign - 124)) | (1L << (OpQuestion - 124)) | (1L << (OpDot - 124)) | (1L << (OpComma - 124)) | (1L << (OpColon - 124)) | (1L << (OpSemi - 124)) | (1L << (OpAt - 124)) | (1L << (OpPound - 124)) | (1L << (OpBackTick - 124)))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - break; - case T__65: - EnterOuterAlt(_localctx, 2); - { - State = 1159; - arrow_operator(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Declaration_modifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Access_level_modifierContext access_level_modifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Mutation_modifierContext mutation_modifier() { - return GetRuleContext(0); - } - public Declaration_modifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_declaration_modifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDeclaration_modifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDeclaration_modifier(this); - } - } - - [RuleVersion(0)] - public Declaration_modifierContext declaration_modifier() { - Declaration_modifierContext _localctx = new Declaration_modifierContext(Context, State); - EnterRule(_localctx, 214, RULE_declaration_modifier); - try { - State = 1186; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,149,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1162; - Match(T__3); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1163; - Match(T__34); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1164; - Match(T__35); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 1165; - Match(T__13); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 1166; - Match(T__17); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 1167; - Match(T__36); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 1168; - Match(T__37); - } - break; - case 8: - EnterOuterAlt(_localctx, 8); - { - State = 1169; - Match(T__38); - } - break; - case 9: - EnterOuterAlt(_localctx, 9); - { - State = 1170; - Match(T__16); - } - break; - case 10: - EnterOuterAlt(_localctx, 10); - { - State = 1171; - Match(T__14); - } - break; - case 11: - EnterOuterAlt(_localctx, 11); - { - State = 1172; - Match(T__39); - } - break; - case 12: - EnterOuterAlt(_localctx, 12); - { - State = 1173; - Match(T__40); - } - break; - case 13: - EnterOuterAlt(_localctx, 13); - { - State = 1174; - Match(T__41); - } - break; - case 14: - EnterOuterAlt(_localctx, 14); - { - State = 1175; - Match(T__41); - State = 1176; - Match(OpLParen); - State = 1177; - Match(T__42); - State = 1178; - Match(OpRParen); - } - break; - case 15: - EnterOuterAlt(_localctx, 15); - { - State = 1179; - Match(T__41); - State = 1180; - Match(OpLParen); - State = 1181; - Match(T__43); - State = 1182; - Match(OpRParen); - } - break; - case 16: - EnterOuterAlt(_localctx, 16); - { - State = 1183; - Match(T__44); - } - break; - case 17: - EnterOuterAlt(_localctx, 17); - { - State = 1184; - access_level_modifier(); - } - break; - case 18: - EnterOuterAlt(_localctx, 18); - { - State = 1185; - mutation_modifier(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Declaration_modifiersContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifierContext[] declaration_modifier() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Declaration_modifierContext declaration_modifier(int i) { - return GetRuleContext(i); - } - public Declaration_modifiersContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_declaration_modifiers; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDeclaration_modifiers(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDeclaration_modifiers(this); - } - } - - [RuleVersion(0)] - public Declaration_modifiersContext declaration_modifiers() { - Declaration_modifiersContext _localctx = new Declaration_modifiersContext(Context, State); - EnterRule(_localctx, 216, RULE_declaration_modifiers); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1189; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - do { - { - { - State = 1188; - declaration_modifier(); - } - } - State = 1191; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__3) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51))) != 0) ); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Access_level_modifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - public Access_level_modifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_access_level_modifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAccess_level_modifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAccess_level_modifier(this); - } - } - - [RuleVersion(0)] - public Access_level_modifierContext access_level_modifier() { - Access_level_modifierContext _localctx = new Access_level_modifierContext(Context, State); - EnterRule(_localctx, 218, RULE_access_level_modifier); - try { - State = 1218; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,151,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1193; - Match(T__45); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1194; - Match(T__45); - State = 1195; - Match(OpLParen); - State = 1196; - Match(T__10); - State = 1197; - Match(OpRParen); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1198; - Match(T__46); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 1199; - Match(T__46); - State = 1200; - Match(OpLParen); - State = 1201; - Match(T__10); - State = 1202; - Match(OpRParen); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 1203; - Match(T__47); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 1204; - Match(T__47); - State = 1205; - Match(OpLParen); - State = 1206; - Match(T__10); - State = 1207; - Match(OpRParen); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 1208; - Match(T__48); - } - break; - case 8: - EnterOuterAlt(_localctx, 8); - { - State = 1209; - Match(T__48); - State = 1210; - Match(OpLParen); - State = 1211; - Match(T__10); - State = 1212; - Match(OpRParen); - } - break; - case 9: - EnterOuterAlt(_localctx, 9); - { - State = 1213; - Match(T__49); - } - break; - case 10: - EnterOuterAlt(_localctx, 10); - { - State = 1214; - Match(T__49); - State = 1215; - Match(OpLParen); - State = 1216; - Match(T__10); - State = 1217; - Match(OpRParen); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Mutation_modifierContext : ParserRuleContext { - public Mutation_modifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_mutation_modifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterMutation_modifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitMutation_modifier(this); - } - } - - [RuleVersion(0)] - public Mutation_modifierContext mutation_modifier() { - Mutation_modifierContext _localctx = new Mutation_modifierContext(Context, State); - EnterRule(_localctx, 220, RULE_mutation_modifier); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1220; - _la = TokenStream.LA(1); - if ( !(_la==T__50 || _la==T__51) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class PatternContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Wildcard_patternContext wildcard_pattern() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Identifier_patternContext identifier_pattern() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public PatternContext pattern() { - return GetRuleContext(0); - } - public PatternContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_pattern; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterPattern(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitPattern(this); - } - } - - [RuleVersion(0)] - public PatternContext pattern() { - return pattern(0); - } - - private PatternContext pattern(int _p) { - ParserRuleContext _parentctx = Context; - int _parentState = State; - PatternContext _localctx = new PatternContext(Context, _parentState); - PatternContext _prevctx = _localctx; - int _startState = 222; - EnterRecursionRule(_localctx, 222, RULE_pattern, _p); - try { - int _alt; - EnterOuterAlt(_localctx, 1); - { - State = 1233; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case OpUnder: - { - State = 1223; - wildcard_pattern(); - State = 1225; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,152,Context) ) { - case 1: - { - State = 1224; - type_annotation(); - } - break; - } - } - break; - case T__9: - case T__10: - case T__11: - case T__13: - case T__14: - case T__16: - case T__17: - case T__19: - case T__20: - case T__21: - case T__22: - case T__23: - case T__24: - case T__25: - case T__34: - case T__35: - case T__36: - case T__37: - case T__38: - case T__39: - case T__41: - case T__42: - case T__43: - case T__44: - case T__49: - case T__50: - case T__51: - case T__54: - case T__55: - case T__67: - case T__68: - case T__69: - case T__70: - case T__71: - case T__72: - case T__73: - case T__74: - case T__75: - case T__76: - case T__77: - case T__78: - case T__79: - case T__80: - case T__81: - case T__82: - case T__83: - case T__84: - case T__85: - case T__86: - case T__87: - case T__88: - case T__89: - case T__90: - case T__91: - case Identifier: - { - State = 1227; - identifier_pattern(); - State = 1229; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,153,Context) ) { - case 1: - { - State = 1228; - type_annotation(); - } - break; - } - } - break; - case T__52: - { - State = 1231; - Match(T__52); - State = 1232; - type(0); - } - break; - default: - throw new NoViableAltException(this); - } - Context.Stop = TokenStream.LT(-1); - State = 1240; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,155,Context); - while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) { - if ( _alt==1 ) { - if ( ParseListeners!=null ) - TriggerExitRuleEvent(); - _prevctx = _localctx; - { - { - _localctx = new PatternContext(_parentctx, _parentState); - PushNewRecursionContext(_localctx, _startState, RULE_pattern); - State = 1235; - if (!(Precpred(Context, 1))) throw new FailedPredicateException(this, "Precpred(Context, 1)"); - State = 1236; - Match(T__53); - State = 1237; - type(0); - } - } - } - State = 1242; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,155,Context); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - UnrollRecursionContexts(_parentctx); - } - return _localctx; - } - - public partial class Wildcard_patternContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpUnder() { return GetToken(SwiftInterfaceParser.OpUnder, 0); } - public Wildcard_patternContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_wildcard_pattern; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterWildcard_pattern(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitWildcard_pattern(this); - } - } - - [RuleVersion(0)] - public Wildcard_patternContext wildcard_pattern() { - Wildcard_patternContext _localctx = new Wildcard_patternContext(Context, State); - EnterRule(_localctx, 224, RULE_wildcard_pattern); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1243; - Match(OpUnder); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Identifier_patternContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Identifier_patternContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_identifier_pattern; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterIdentifier_pattern(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitIdentifier_pattern(this); - } - } - - [RuleVersion(0)] - public Identifier_patternContext identifier_pattern() { - Identifier_patternContext _localctx = new Identifier_patternContext(Context, State); - EnterRule(_localctx, 226, RULE_identifier_pattern); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1245; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_typeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_clauseContext function_type_argument_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Arrow_operatorContext arrow_operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - public Function_typeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_type; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_type(this); - } - } - - [RuleVersion(0)] - public Function_typeContext function_type() { - Function_typeContext _localctx = new Function_typeContext(Context, State); - EnterRule(_localctx, 228, RULE_function_type); - int _la; - try { - State = 1265; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,159,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1248; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 1247; - attributes(); - } - } - - State = 1250; - function_type_argument_clause(); - State = 1252; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__30) { - { - State = 1251; - Match(T__30); - } - } - - State = 1254; - arrow_operator(); - State = 1255; - type(0); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1258; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpAt) { - { - State = 1257; - attributes(); - } - } - - State = 1260; - function_type_argument_clause(); - State = 1261; - Match(T__31); - State = 1262; - arrow_operator(); - State = 1263; - type(0); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_type_argument_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_listContext function_type_argument_list() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Range_operatorContext range_operator() { - return GetRuleContext(0); - } - public Function_type_argument_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_type_argument_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_type_argument_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_type_argument_clause(this); - } - } - - [RuleVersion(0)] - public Function_type_argument_clauseContext function_type_argument_clause() { - Function_type_argument_clauseContext _localctx = new Function_type_argument_clauseContext(Context, State); - EnterRule(_localctx, 230, RULE_function_type_argument_clause); - int _la; - try { - State = 1276; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,161,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1267; - Match(OpLParen); - State = 1268; - Match(OpRParen); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1269; - Match(OpLParen); - State = 1270; - function_type_argument_list(); - State = 1272; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__66) { - { - State = 1271; - range_operator(); - } - } - - State = 1274; - Match(OpRParen); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_type_argument_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Function_type_argumentContext function_type_argument() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Function_type_argument_listContext function_type_argument_list() { - return GetRuleContext(0); - } - public Function_type_argument_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_type_argument_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_type_argument_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_type_argument_list(this); - } - } - - [RuleVersion(0)] - public Function_type_argument_listContext function_type_argument_list() { - Function_type_argument_listContext _localctx = new Function_type_argument_listContext(Context, State); - EnterRule(_localctx, 232, RULE_function_type_argument_list); - try { - State = 1283; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,162,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1278; - function_type_argument(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1279; - function_type_argument(); - State = 1280; - Match(OpComma); - State = 1281; - function_type_argument_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Function_type_argumentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Inout_clauseContext inout_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Argument_labelContext argument_label() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { - return GetRuleContext(0); - } - public Function_type_argumentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_function_type_argument; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunction_type_argument(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunction_type_argument(this); - } - } - - [RuleVersion(0)] - public Function_type_argumentContext function_type_argument() { - Function_type_argumentContext _localctx = new Function_type_argumentContext(Context, State); - EnterRule(_localctx, 234, RULE_function_type_argument); - int _la; - try { - State = 1295; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,165,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1286; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,163,Context) ) { - case 1: - { - State = 1285; - attributes(); - } - break; - } - State = 1289; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__59) { - { - State = 1288; - inout_clause(); - } - } - - State = 1291; - type(0); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1292; - argument_label(); - State = 1293; - type_annotation(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Argument_labelContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext[] label_identifier() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier(int i) { - return GetRuleContext(i); - } - public Argument_labelContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_argument_label; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterArgument_label(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitArgument_label(this); - } - } - - [RuleVersion(0)] - public Argument_labelContext argument_label() { - Argument_labelContext _localctx = new Argument_labelContext(Context, State); - EnterRule(_localctx, 236, RULE_argument_label); - try { - State = 1301; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,166,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1297; - label_identifier(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1298; - label_identifier(); - State = 1299; - label_identifier(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class TypeContext : ParserRuleContext { - public TypeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type; } } - - public TypeContext() { } - public virtual void CopyFrom(TypeContext context) { - base.CopyFrom(context); - } - } - public partial class Dict_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Dictionary_typeContext dictionary_type() { - return GetRuleContext(0); - } - public Dict_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDict_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDict_type(this); - } - } - public partial class Any_typeContext : TypeContext { - public Any_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAny_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAny_type(this); - } - } - public partial class Identifier_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - public Identifier_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterIdentifier_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitIdentifier_type(this); - } - } - public partial class Func_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Function_typeContext function_type() { - return GetRuleContext(0); - } - public Func_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterFunc_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitFunc_type(this); - } - } - public partial class Arr_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Array_typeContext array_type() { - return GetRuleContext(0); - } - public Arr_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterArr_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitArr_type(this); - } - } - public partial class Meta_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - public Meta_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterMeta_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitMeta_type(this); - } - } - public partial class Boxed_protocol_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Any_clauseContext any_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - public Boxed_protocol_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterBoxed_protocol_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitBoxed_protocol_type(this); - } - } - public partial class Optional_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpQuestion() { return GetToken(SwiftInterfaceParser.OpQuestion, 0); } - public Optional_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOptional_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOptional_type(this); - } - } - public partial class Self_typeContext : TypeContext { - public Self_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSelf_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSelf_type(this); - } - } - public partial class Unwrapped_optional_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpBang() { return GetToken(SwiftInterfaceParser.OpBang, 0); } - public Unwrapped_optional_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterUnwrapped_optional_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitUnwrapped_optional_type(this); - } - } - public partial class Proto_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - public Proto_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProto_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProto_type(this); - } - } - public partial class Tup_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Tuple_typeContext tuple_type() { - return GetRuleContext(0); - } - public Tup_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTup_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTup_type(this); - } - } - public partial class Self_longContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - public Self_longContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSelf_long(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSelf_long(this); - } - } - public partial class Proto_comp_typeContext : TypeContext { - [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { - return GetRuleContext(0); - } - public Proto_comp_typeContext(TypeContext context) { CopyFrom(context); } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProto_comp_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProto_comp_type(this); - } - } - - [RuleVersion(0)] - public TypeContext type() { - return type(0); - } - - private TypeContext type(int _p) { - ParserRuleContext _parentctx = Context; - int _parentState = State; - TypeContext _localctx = new TypeContext(Context, _parentState); - TypeContext _prevctx = _localctx; - int _startState = 238; - EnterRecursionRule(_localctx, 238, RULE_type, _p); - try { - int _alt; - EnterOuterAlt(_localctx, 1); - { - State = 1318; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,167,Context) ) { - case 1: - { - _localctx = new Arr_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - - State = 1304; - array_type(); - } - break; - case 2: - { - _localctx = new Dict_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1305; - dictionary_type(); - } - break; - case 3: - { - _localctx = new Func_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1306; - function_type(); - } - break; - case 4: - { - _localctx = new Identifier_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1307; - type_identifier(); - } - break; - case 5: - { - _localctx = new Tup_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1308; - tuple_type(); - } - break; - case 6: - { - _localctx = new Proto_comp_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1309; - protocol_composition_type(); - } - break; - case 7: - { - _localctx = new Boxed_protocol_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1310; - any_clause(); - State = 1311; - type(4); - } - break; - case 8: - { - _localctx = new Any_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1313; - Match(T__56); - } - break; - case 9: - { - _localctx = new Self_typeContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1314; - Match(T__57); - } - break; - case 10: - { - _localctx = new Self_longContext(_localctx); - Context = _localctx; - _prevctx = _localctx; - State = 1315; - Match(T__57); - State = 1316; - Match(OpDot); - State = 1317; - type_identifier(); - } - break; - } - Context.Stop = TokenStream.LT(-1); - State = 1332; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,169,Context); - while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) { - if ( _alt==1 ) { - if ( ParseListeners!=null ) - TriggerExitRuleEvent(); - _prevctx = _localctx; - { - State = 1330; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,168,Context) ) { - case 1: - { - _localctx = new Optional_typeContext(new TypeContext(_parentctx, _parentState)); - PushNewRecursionContext(_localctx, _startState, RULE_type); - State = 1320; - if (!(Precpred(Context, 9))) throw new FailedPredicateException(this, "Precpred(Context, 9)"); - State = 1321; - Match(OpQuestion); - } - break; - case 2: - { - _localctx = new Unwrapped_optional_typeContext(new TypeContext(_parentctx, _parentState)); - PushNewRecursionContext(_localctx, _startState, RULE_type); - State = 1322; - if (!(Precpred(Context, 8))) throw new FailedPredicateException(this, "Precpred(Context, 8)"); - State = 1323; - Match(OpBang); - } - break; - case 3: - { - _localctx = new Meta_typeContext(new TypeContext(_parentctx, _parentState)); - PushNewRecursionContext(_localctx, _startState, RULE_type); - State = 1324; - if (!(Precpred(Context, 6))) throw new FailedPredicateException(this, "Precpred(Context, 6)"); - State = 1325; - Match(OpDot); - State = 1326; - Match(T__54); - } - break; - case 4: - { - _localctx = new Proto_typeContext(new TypeContext(_parentctx, _parentState)); - PushNewRecursionContext(_localctx, _startState, RULE_type); - State = 1327; - if (!(Precpred(Context, 5))) throw new FailedPredicateException(this, "Precpred(Context, 5)"); - State = 1328; - Match(OpDot); - State = 1329; - Match(T__55); - } - break; - } - } - } - State = 1334; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,169,Context); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - UnrollRecursionContexts(_parentctx); - } - return _localctx; - } - - public partial class Type_annotationContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public AttributesContext attributes() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Inout_clauseContext inout_clause() { - return GetRuleContext(0); - } - public Type_annotationContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type_annotation; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterType_annotation(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitType_annotation(this); - } - } - - [RuleVersion(0)] - public Type_annotationContext type_annotation() { - Type_annotationContext _localctx = new Type_annotationContext(Context, State); - EnterRule(_localctx, 240, RULE_type_annotation); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1335; - Match(OpColon); - State = 1337; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,170,Context) ) { - case 1: - { - State = 1336; - attributes(); - } - break; - } - State = 1340; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==T__59) { - { - State = 1339; - inout_clause(); - } - } - - State = 1342; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Any_clauseContext : ParserRuleContext { - public Any_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_any_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterAny_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitAny_clause(this); - } - } - - [RuleVersion(0)] - public Any_clauseContext any_clause() { - Any_clauseContext _localctx = new Any_clauseContext(Context, State); - EnterRule(_localctx, 242, RULE_any_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1344; - Match(T__58); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Inout_clauseContext : ParserRuleContext { - public Inout_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_inout_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInout_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInout_clause(this); - } - } - - [RuleVersion(0)] - public Inout_clauseContext inout_clause() { - Inout_clauseContext _localctx = new Inout_clauseContext(Context, State); - EnterRule(_localctx, 244, RULE_inout_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1346; - Match(T__59); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Type_identifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_nameContext type_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_argument_clauseContext generic_argument_clause() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpDot() { return GetToken(SwiftInterfaceParser.OpDot, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - public Type_identifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type_identifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterType_identifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitType_identifier(this); - } - } - - [RuleVersion(0)] - public Type_identifierContext type_identifier() { - Type_identifierContext _localctx = new Type_identifierContext(Context, State); - EnterRule(_localctx, 246, RULE_type_identifier); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1348; - type_name(); - State = 1350; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,172,Context) ) { - case 1: - { - State = 1349; - generic_argument_clause(); - } - break; - } - State = 1354; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,173,Context) ) { - case 1: - { - State = 1352; - Match(OpDot); - State = 1353; - type_identifier(); - } - break; - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Type_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Declaration_identifierContext declaration_identifier() { - return GetRuleContext(0); - } - public Type_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_type_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterType_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitType_name(this); - } - } - - [RuleVersion(0)] - public Type_nameContext type_name() { - Type_nameContext _localctx = new Type_nameContext(Context, State); - EnterRule(_localctx, 248, RULE_type_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1356; - declaration_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Tuple_typeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLParen() { return GetToken(SwiftInterfaceParser.OpLParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRParen() { return GetToken(SwiftInterfaceParser.OpRParen, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_element_listContext tuple_type_element_list() { - return GetRuleContext(0); - } - public Tuple_typeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_tuple_type; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTuple_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTuple_type(this); - } - } - - [RuleVersion(0)] - public Tuple_typeContext tuple_type() { - Tuple_typeContext _localctx = new Tuple_typeContext(Context, State); - EnterRule(_localctx, 250, RULE_tuple_type); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1358; - Match(OpLParen); - State = 1360; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__58) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)) | (1L << (Identifier - 64)))) != 0) || ((((_la - 134)) & ~0x3f) == 0 && ((1L << (_la - 134)) & ((1L << (OpAt - 134)) | (1L << (OpLParen - 134)) | (1L << (OpLBracket - 134)))) != 0)) { - { - State = 1359; - tuple_type_element_list(); - } - } - - State = 1362; - Match(OpRParen); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Tuple_type_element_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_elementContext tuple_type_element() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma() { return GetToken(SwiftInterfaceParser.OpComma, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Tuple_type_element_listContext tuple_type_element_list() { - return GetRuleContext(0); - } - public Tuple_type_element_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_tuple_type_element_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTuple_type_element_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTuple_type_element_list(this); - } - } - - [RuleVersion(0)] - public Tuple_type_element_listContext tuple_type_element_list() { - Tuple_type_element_listContext _localctx = new Tuple_type_element_listContext(Context, State); - EnterRule(_localctx, 252, RULE_tuple_type_element_list); - try { - State = 1369; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,175,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1364; - tuple_type_element(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1365; - tuple_type_element(); - State = 1366; - Match(OpComma); - State = 1367; - tuple_type_element_list(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Tuple_type_elementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Element_nameContext element_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_annotationContext type_annotation() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - public Tuple_type_elementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_tuple_type_element; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterTuple_type_element(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitTuple_type_element(this); - } - } - - [RuleVersion(0)] - public Tuple_type_elementContext tuple_type_element() { - Tuple_type_elementContext _localctx = new Tuple_type_elementContext(Context, State); - EnterRule(_localctx, 254, RULE_tuple_type_element); - try { - State = 1375; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,176,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1371; - element_name(); - State = 1372; - type_annotation(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1374; - type(0); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Element_nameContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Label_identifierContext label_identifier() { - return GetRuleContext(0); - } - public Element_nameContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_element_name; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterElement_name(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitElement_name(this); - } - } - - [RuleVersion(0)] - public Element_nameContext element_name() { - Element_nameContext _localctx = new Element_nameContext(Context, State); - EnterRule(_localctx, 256, RULE_element_name); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1377; - label_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Array_typeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } - public Array_typeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_array_type; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterArray_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitArray_type(this); - } - } - - [RuleVersion(0)] - public Array_typeContext array_type() { - Array_typeContext _localctx = new Array_typeContext(Context, State); - EnterRule(_localctx, 258, RULE_array_type); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1379; - Match(OpLBracket); - State = 1380; - type(0); - State = 1381; - Match(OpRBracket); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Dictionary_typeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLBracket() { return GetToken(SwiftInterfaceParser.OpLBracket, 0); } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext[] type() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpRBracket() { return GetToken(SwiftInterfaceParser.OpRBracket, 0); } - public Dictionary_typeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_dictionary_type; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterDictionary_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitDictionary_type(this); - } - } - - [RuleVersion(0)] - public Dictionary_typeContext dictionary_type() { - Dictionary_typeContext _localctx = new Dictionary_typeContext(Context, State); - EnterRule(_localctx, 260, RULE_dictionary_type); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1383; - Match(OpLBracket); - State = 1384; - type(0); - State = 1385; - Match(OpColon); - State = 1386; - type(0); - State = 1387; - Match(OpRBracket); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_composition_typeContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Protocol_identifierContext[] protocol_identifier() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_identifierContext protocol_identifier(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpAmp() { return GetTokens(SwiftInterfaceParser.OpAmp); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpAmp(int i) { - return GetToken(SwiftInterfaceParser.OpAmp, i); - } - public Protocol_composition_typeContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_composition_type; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_composition_type(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_composition_type(this); - } - } - - [RuleVersion(0)] - public Protocol_composition_typeContext protocol_composition_type() { - Protocol_composition_typeContext _localctx = new Protocol_composition_typeContext(Context, State); - EnterRule(_localctx, 262, RULE_protocol_composition_type); - try { - int _alt; - EnterOuterAlt(_localctx, 1); - { - State = 1389; - protocol_identifier(); - State = 1392; - ErrorHandler.Sync(this); - _alt = 1; - do { - switch (_alt) { - case 1: - { - { - State = 1390; - Match(OpAmp); - State = 1391; - protocol_identifier(); - } - } - break; - default: - throw new NoViableAltException(this); - } - State = 1394; - ErrorHandler.Sync(this); - _alt = Interpreter.AdaptivePredict(TokenStream,177,Context); - } while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Protocol_identifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - public Protocol_identifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_protocol_identifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterProtocol_identifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitProtocol_identifier(this); - } - } - - [RuleVersion(0)] - public Protocol_identifierContext protocol_identifier() { - Protocol_identifierContext _localctx = new Protocol_identifierContext(Context, State); - EnterRule(_localctx, 264, RULE_protocol_identifier); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1396; - type_identifier(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class LiteralContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Numeric_literalContext numeric_literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public String_literalContext string_literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Boolean_literalContext boolean_literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Nil_literalContext nil_literal() { - return GetRuleContext(0); - } - public LiteralContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterLiteral(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitLiteral(this); - } - } - - [RuleVersion(0)] - public LiteralContext literal() { - LiteralContext _localctx = new LiteralContext(Context, State); - EnterRule(_localctx, 266, RULE_literal); - try { - State = 1402; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case Binary_literal: - case Octal_literal: - case Decimal_literal: - case Pure_decimal_digits: - case Hexadecimal_literal: - case OpPlus: - case OpMinus: - EnterOuterAlt(_localctx, 1); - { - State = 1398; - numeric_literal(); - } - break; - case Static_string_literal: - EnterOuterAlt(_localctx, 2); - { - State = 1399; - string_literal(); - } - break; - case T__61: - case T__62: - EnterOuterAlt(_localctx, 3); - { - State = 1400; - boolean_literal(); - } - break; - case T__60: - EnterOuterAlt(_localctx, 4); - { - State = 1401; - nil_literal(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Nil_literalContext : ParserRuleContext { - public Nil_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_nil_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterNil_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitNil_literal(this); - } - } - - [RuleVersion(0)] - public Nil_literalContext nil_literal() { - Nil_literalContext _localctx = new Nil_literalContext(Context, State); - EnterRule(_localctx, 268, RULE_nil_literal); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1404; - Match(T__60); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Boolean_literalContext : ParserRuleContext { - public Boolean_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_boolean_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterBoolean_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitBoolean_literal(this); - } - } - - [RuleVersion(0)] - public Boolean_literalContext boolean_literal() { - Boolean_literalContext _localctx = new Boolean_literalContext(Context, State); - EnterRule(_localctx, 270, RULE_boolean_literal); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1406; - _la = TokenStream.LA(1); - if ( !(_la==T__61 || _la==T__62) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Numeric_literalContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Integer_literalContext integer_literal() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpPlus() { return GetToken(SwiftInterfaceParser.OpPlus, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpMinus() { return GetToken(SwiftInterfaceParser.OpMinus, 0); } - public Numeric_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_numeric_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterNumeric_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitNumeric_literal(this); - } - } - - [RuleVersion(0)] - public Numeric_literalContext numeric_literal() { - Numeric_literalContext _localctx = new Numeric_literalContext(Context, State); - EnterRule(_localctx, 272, RULE_numeric_literal); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1409; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - if (_la==OpPlus || _la==OpMinus) { - { - State = 1408; - _la = TokenStream.LA(1); - if ( !(_la==OpPlus || _la==OpMinus) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - - State = 1411; - integer_literal(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Integer_literalContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Binary_literal() { return GetToken(SwiftInterfaceParser.Binary_literal, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Octal_literal() { return GetToken(SwiftInterfaceParser.Octal_literal, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Decimal_literal() { return GetToken(SwiftInterfaceParser.Decimal_literal, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Pure_decimal_digits() { return GetToken(SwiftInterfaceParser.Pure_decimal_digits, 0); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Hexadecimal_literal() { return GetToken(SwiftInterfaceParser.Hexadecimal_literal, 0); } - public Integer_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_integer_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterInteger_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitInteger_literal(this); - } - } - - [RuleVersion(0)] - public Integer_literalContext integer_literal() { - Integer_literalContext _localctx = new Integer_literalContext(Context, State); - EnterRule(_localctx, 274, RULE_integer_literal); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1413; - _la = TokenStream.LA(1); - if ( !(((((_la - 113)) & ~0x3f) == 0 && ((1L << (_la - 113)) & ((1L << (Binary_literal - 113)) | (1L << (Octal_literal - 113)) | (1L << (Decimal_literal - 113)) | (1L << (Pure_decimal_digits - 113)) | (1L << (Hexadecimal_literal - 113)))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class String_literalContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Static_string_literal() { return GetToken(SwiftInterfaceParser.Static_string_literal, 0); } - public String_literalContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_string_literal; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterString_literal(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitString_literal(this); - } - } - - [RuleVersion(0)] - public String_literalContext string_literal() { - String_literalContext _localctx = new String_literalContext(Context, State); - EnterRule(_localctx, 276, RULE_string_literal); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1415; - Match(Static_string_literal); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Label_identifierContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Identifier() { return GetToken(SwiftInterfaceParser.Identifier, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Keyword_as_identifier_in_labelsContext keyword_as_identifier_in_labels() { - return GetRuleContext(0); - } - public Label_identifierContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_label_identifier; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterLabel_identifier(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitLabel_identifier(this); - } - } - - [RuleVersion(0)] - public Label_identifierContext label_identifier() { - Label_identifierContext _localctx = new Label_identifierContext(Context, State); - EnterRule(_localctx, 278, RULE_label_identifier); - try { - State = 1419; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case Identifier: - EnterOuterAlt(_localctx, 1); - { - State = 1417; - Match(Identifier); - } - break; - case T__0: - case T__1: - case T__2: - case T__3: - case T__4: - case T__5: - case T__7: - case T__9: - case T__10: - case T__11: - case T__12: - case T__13: - case T__14: - case T__15: - case T__16: - case T__17: - case T__18: - case T__19: - case T__20: - case T__21: - case T__22: - case T__23: - case T__24: - case T__25: - case T__26: - case T__27: - case T__28: - case T__30: - case T__31: - case T__32: - case T__33: - case T__34: - case T__35: - case T__36: - case T__37: - case T__38: - case T__39: - case T__40: - case T__41: - case T__42: - case T__43: - case T__44: - case T__45: - case T__46: - case T__47: - case T__48: - case T__49: - case T__50: - case T__51: - case T__52: - case T__53: - case T__54: - case T__55: - case T__56: - case T__57: - case T__60: - case T__61: - case T__62: - case T__63: - case T__67: - case T__68: - case T__69: - case T__70: - case T__71: - case T__72: - case T__73: - case T__74: - case T__75: - case T__76: - case T__77: - case T__78: - case T__79: - case T__80: - case T__81: - case T__82: - case T__83: - case T__84: - case T__85: - case T__86: - case T__87: - case T__88: - case T__89: - case T__90: - case T__91: - case T__92: - case T__93: - case T__94: - case T__95: - case T__96: - case T__97: - case T__98: - case T__99: - case T__100: - case T__101: - case T__102: - case T__103: - case T__104: - case T__105: - case T__106: - case T__107: - case T__108: - case T__109: - case T__110: - case T__111: - EnterOuterAlt(_localctx, 2); - { - State = 1418; - keyword_as_identifier_in_labels(); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_parameter_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLess() { return GetToken(SwiftInterfaceParser.OpLess, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameter_listContext generic_parameter_list() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { - return GetRuleContext(0); - } - public Generic_parameter_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_parameter_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_parameter_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_parameter_clause(this); - } - } - - [RuleVersion(0)] - public Generic_parameter_clauseContext generic_parameter_clause() { - Generic_parameter_clauseContext _localctx = new Generic_parameter_clauseContext(Context, State); - EnterRule(_localctx, 280, RULE_generic_parameter_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1421; - Match(OpLess); - State = 1422; - generic_parameter_list(); - State = 1423; - opGreater(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_parameter_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameterContext[] generic_parameter() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_parameterContext generic_parameter(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Generic_parameter_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_parameter_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_parameter_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_parameter_list(this); - } - } - - [RuleVersion(0)] - public Generic_parameter_listContext generic_parameter_list() { - Generic_parameter_listContext _localctx = new Generic_parameter_listContext(Context, State); - EnterRule(_localctx, 282, RULE_generic_parameter_list); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1425; - generic_parameter(); - State = 1430; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 1426; - Match(OpComma); - State = 1427; - generic_parameter(); - } - } - State = 1432; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_parameterContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_nameContext type_name() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { - return GetRuleContext(0); - } - public Generic_parameterContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_parameter; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_parameter(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_parameter(this); - } - } - - [RuleVersion(0)] - public Generic_parameterContext generic_parameter() { - Generic_parameterContext _localctx = new Generic_parameterContext(Context, State); - EnterRule(_localctx, 284, RULE_generic_parameter); - try { - State = 1442; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,182,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1433; - type_name(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1434; - type_name(); - State = 1435; - Match(OpColon); - State = 1436; - type_identifier(); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1438; - type_name(); - State = 1439; - Match(OpColon); - State = 1440; - protocol_composition_type(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_where_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Requirement_listContext requirement_list() { - return GetRuleContext(0); - } - public Generic_where_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_where_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_where_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_where_clause(this); - } - } - - [RuleVersion(0)] - public Generic_where_clauseContext generic_where_clause() { - Generic_where_clauseContext _localctx = new Generic_where_clauseContext(Context, State); - EnterRule(_localctx, 286, RULE_generic_where_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1444; - Match(T__63); - State = 1445; - requirement_list(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Requirement_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public RequirementContext[] requirement() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public RequirementContext requirement(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Requirement_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_requirement_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRequirement_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRequirement_list(this); - } - } - - [RuleVersion(0)] - public Requirement_listContext requirement_list() { - Requirement_listContext _localctx = new Requirement_listContext(Context, State); - EnterRule(_localctx, 288, RULE_requirement_list); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1447; - requirement(); - State = 1452; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 1448; - Match(OpComma); - State = 1449; - requirement(); - } - } - State = 1454; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class RequirementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Conformance_requirementContext conformance_requirement() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public Same_type_requirementContext same_type_requirement() { - return GetRuleContext(0); - } - public RequirementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_requirement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRequirement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRequirement(this); - } - } - - [RuleVersion(0)] - public RequirementContext requirement() { - RequirementContext _localctx = new RequirementContext(Context, State); - EnterRule(_localctx, 290, RULE_requirement); - try { - State = 1457; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,184,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1455; - conformance_requirement(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1456; - same_type_requirement(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Conformance_requirementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext[] type_identifier() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpColon() { return GetToken(SwiftInterfaceParser.OpColon, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Protocol_composition_typeContext protocol_composition_type() { - return GetRuleContext(0); - } - public Conformance_requirementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_conformance_requirement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterConformance_requirement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitConformance_requirement(this); - } - } - - [RuleVersion(0)] - public Conformance_requirementContext conformance_requirement() { - Conformance_requirementContext _localctx = new Conformance_requirementContext(Context, State); - EnterRule(_localctx, 292, RULE_conformance_requirement); - try { - State = 1467; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,185,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1459; - type_identifier(); - State = 1460; - Match(OpColon); - State = 1461; - type_identifier(); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1463; - type_identifier(); - State = 1464; - Match(OpColon); - State = 1465; - protocol_composition_type(); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Same_type_requirementContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Type_identifierContext type_identifier() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public OperatorContext @operator() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - public Same_type_requirementContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_same_type_requirement; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterSame_type_requirement(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitSame_type_requirement(this); - } - } - - [RuleVersion(0)] - public Same_type_requirementContext same_type_requirement() { - Same_type_requirementContext _localctx = new Same_type_requirementContext(Context, State); - EnterRule(_localctx, 294, RULE_same_type_requirement); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1469; - type_identifier(); - State = 1470; - @operator(); - State = 1471; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_argument_clauseContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpLess() { return GetToken(SwiftInterfaceParser.OpLess, 0); } - [System.Diagnostics.DebuggerNonUserCode] public Generic_argument_listContext generic_argument_list() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public OpGreaterContext opGreater() { - return GetRuleContext(0); - } - public Generic_argument_clauseContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_argument_clause; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_argument_clause(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_argument_clause(this); - } - } - - [RuleVersion(0)] - public Generic_argument_clauseContext generic_argument_clause() { - Generic_argument_clauseContext _localctx = new Generic_argument_clauseContext(Context, State); - EnterRule(_localctx, 296, RULE_generic_argument_clause); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1473; - Match(OpLess); - State = 1474; - generic_argument_list(); - State = 1475; - opGreater(); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_argument_listContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Generic_argumentContext[] generic_argument() { - return GetRuleContexts(); - } - [System.Diagnostics.DebuggerNonUserCode] public Generic_argumentContext generic_argument(int i) { - return GetRuleContext(i); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode[] OpComma() { return GetTokens(SwiftInterfaceParser.OpComma); } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode OpComma(int i) { - return GetToken(SwiftInterfaceParser.OpComma, i); - } - public Generic_argument_listContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_argument_list; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_argument_list(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_argument_list(this); - } - } - - [RuleVersion(0)] - public Generic_argument_listContext generic_argument_list() { - Generic_argument_listContext _localctx = new Generic_argument_listContext(Context, State); - EnterRule(_localctx, 298, RULE_generic_argument_list); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1477; - generic_argument(); - State = 1482; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - while (_la==OpComma) { - { - { - State = 1478; - Match(OpComma); - State = 1479; - generic_argument(); - } - } - State = 1484; - ErrorHandler.Sync(this); - _la = TokenStream.LA(1); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Generic_argumentContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public TypeContext type() { - return GetRuleContext(0); - } - public Generic_argumentContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_generic_argument; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterGeneric_argument(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitGeneric_argument(this); - } - } - - [RuleVersion(0)] - public Generic_argumentContext generic_argument() { - Generic_argumentContext _localctx = new Generic_argumentContext(Context, State); - EnterRule(_localctx, 300, RULE_generic_argument); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1485; - type(0); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class OpGreaterContext : ParserRuleContext { - public OpGreaterContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_opGreater; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOpGreater(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOpGreater(this); - } - } - - [RuleVersion(0)] - public OpGreaterContext opGreater() { - OpGreaterContext _localctx = new OpGreaterContext(Context, State); - EnterRule(_localctx, 302, RULE_opGreater); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1487; - Match(T__64); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Arrow_operatorContext : ParserRuleContext { - public Arrow_operatorContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_arrow_operator; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterArrow_operator(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitArrow_operator(this); - } - } - - [RuleVersion(0)] - public Arrow_operatorContext arrow_operator() { - Arrow_operatorContext _localctx = new Arrow_operatorContext(Context, State); - EnterRule(_localctx, 304, RULE_arrow_operator); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1489; - Match(T__65); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Range_operatorContext : ParserRuleContext { - public Range_operatorContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_range_operator; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterRange_operator(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitRange_operator(this); - } - } - - [RuleVersion(0)] - public Range_operatorContext range_operator() { - Range_operatorContext _localctx = new Range_operatorContext(Context, State); - EnterRule(_localctx, 306, RULE_range_operator); - try { - EnterOuterAlt(_localctx, 1); - { - State = 1491; - Match(T__66); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Keyword_as_identifier_in_declarationsContext : ParserRuleContext { - public Keyword_as_identifier_in_declarationsContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_keyword_as_identifier_in_declarations; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterKeyword_as_identifier_in_declarations(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitKeyword_as_identifier_in_declarations(this); - } - } - - [RuleVersion(0)] - public Keyword_as_identifier_in_declarationsContext keyword_as_identifier_in_declarations() { - Keyword_as_identifier_in_declarationsContext _localctx = new Keyword_as_identifier_in_declarationsContext(Context, State); - EnterRule(_localctx, 308, RULE_keyword_as_identifier_in_declarations); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1493; - _la = TokenStream.LA(1); - if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__13) | (1L << T__14) | (1L << T__16) | (1L << T__17) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__54) | (1L << T__55))) != 0) || ((((_la - 68)) & ~0x3f) == 0 && ((1L << (_la - 68)) & ((1L << (T__67 - 68)) | (1L << (T__68 - 68)) | (1L << (T__69 - 68)) | (1L << (T__70 - 68)) | (1L << (T__71 - 68)) | (1L << (T__72 - 68)) | (1L << (T__73 - 68)) | (1L << (T__74 - 68)) | (1L << (T__75 - 68)) | (1L << (T__76 - 68)) | (1L << (T__77 - 68)) | (1L << (T__78 - 68)) | (1L << (T__79 - 68)) | (1L << (T__80 - 68)) | (1L << (T__81 - 68)) | (1L << (T__82 - 68)) | (1L << (T__83 - 68)) | (1L << (T__84 - 68)) | (1L << (T__85 - 68)) | (1L << (T__86 - 68)) | (1L << (T__87 - 68)) | (1L << (T__88 - 68)) | (1L << (T__89 - 68)) | (1L << (T__90 - 68)) | (1L << (T__91 - 68)))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Keyword_as_identifier_in_labelsContext : ParserRuleContext { - public Keyword_as_identifier_in_labelsContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_keyword_as_identifier_in_labels; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterKeyword_as_identifier_in_labels(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitKeyword_as_identifier_in_labels(this); - } - } - - [RuleVersion(0)] - public Keyword_as_identifier_in_labelsContext keyword_as_identifier_in_labels() { - Keyword_as_identifier_in_labelsContext _localctx = new Keyword_as_identifier_in_labelsContext(Context, State); - EnterRule(_localctx, 310, RULE_keyword_as_identifier_in_labels); - int _la; - try { - EnterOuterAlt(_localctx, 1); - { - State = 1495; - _la = TokenStream.LA(1); - if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__7) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << T__16) | (1L << T__17) | (1L << T__18) | (1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27) | (1L << T__28) | (1L << T__30) | (1L << T__31) | (1L << T__32) | (1L << T__33) | (1L << T__34) | (1L << T__35) | (1L << T__36) | (1L << T__37) | (1L << T__38) | (1L << T__39) | (1L << T__40) | (1L << T__41) | (1L << T__42) | (1L << T__43) | (1L << T__44) | (1L << T__45) | (1L << T__46) | (1L << T__47) | (1L << T__48) | (1L << T__49) | (1L << T__50) | (1L << T__51) | (1L << T__52) | (1L << T__53) | (1L << T__54) | (1L << T__55) | (1L << T__56) | (1L << T__57) | (1L << T__60) | (1L << T__61) | (1L << T__62))) != 0) || ((((_la - 64)) & ~0x3f) == 0 && ((1L << (_la - 64)) & ((1L << (T__63 - 64)) | (1L << (T__67 - 64)) | (1L << (T__68 - 64)) | (1L << (T__69 - 64)) | (1L << (T__70 - 64)) | (1L << (T__71 - 64)) | (1L << (T__72 - 64)) | (1L << (T__73 - 64)) | (1L << (T__74 - 64)) | (1L << (T__75 - 64)) | (1L << (T__76 - 64)) | (1L << (T__77 - 64)) | (1L << (T__78 - 64)) | (1L << (T__79 - 64)) | (1L << (T__80 - 64)) | (1L << (T__81 - 64)) | (1L << (T__82 - 64)) | (1L << (T__83 - 64)) | (1L << (T__84 - 64)) | (1L << (T__85 - 64)) | (1L << (T__86 - 64)) | (1L << (T__87 - 64)) | (1L << (T__88 - 64)) | (1L << (T__89 - 64)) | (1L << (T__90 - 64)) | (1L << (T__91 - 64)) | (1L << (T__92 - 64)) | (1L << (T__93 - 64)) | (1L << (T__94 - 64)) | (1L << (T__95 - 64)) | (1L << (T__96 - 64)) | (1L << (T__97 - 64)) | (1L << (T__98 - 64)) | (1L << (T__99 - 64)) | (1L << (T__100 - 64)) | (1L << (T__101 - 64)) | (1L << (T__102 - 64)) | (1L << (T__103 - 64)) | (1L << (T__104 - 64)) | (1L << (T__105 - 64)) | (1L << (T__106 - 64)) | (1L << (T__107 - 64)) | (1L << (T__108 - 64)) | (1L << (T__109 - 64)) | (1L << (T__110 - 64)) | (1L << (T__111 - 64)))) != 0)) ) { - ErrorHandler.RecoverInline(this); - } - else { - ErrorHandler.ReportMatch(this); - Consume(); - } - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class OperatorContext : ParserRuleContext { - [System.Diagnostics.DebuggerNonUserCode] public Operator_anglesContext operator_angles() { - return GetRuleContext(0); - } - [System.Diagnostics.DebuggerNonUserCode] public ITerminalNode Operator() { return GetToken(SwiftInterfaceParser.Operator, 0); } - public OperatorContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_operator; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOperator(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOperator(this); - } - } - - [RuleVersion(0)] - public OperatorContext @operator() { - OperatorContext _localctx = new OperatorContext(Context, State); - EnterRule(_localctx, 312, RULE_operator); - try { - State = 1499; - ErrorHandler.Sync(this); - switch (TokenStream.LA(1)) { - case T__64: - EnterOuterAlt(_localctx, 1); - { - State = 1497; - operator_angles(); - } - break; - case Operator: - EnterOuterAlt(_localctx, 2); - { - State = 1498; - Match(Operator); - } - break; - default: - throw new NoViableAltException(this); - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public partial class Operator_anglesContext : ParserRuleContext { - public Operator_anglesContext(ParserRuleContext parent, int invokingState) - : base(parent, invokingState) - { - } - public override int RuleIndex { get { return RULE_operator_angles; } } - [System.Diagnostics.DebuggerNonUserCode] - public override void EnterRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.EnterOperator_angles(this); - } - [System.Diagnostics.DebuggerNonUserCode] - public override void ExitRule(IParseTreeListener listener) { - ISwiftInterfaceListener typedListener = listener as ISwiftInterfaceListener; - if (typedListener != null) typedListener.ExitOperator_angles(this); - } - } - - [RuleVersion(0)] - public Operator_anglesContext operator_angles() { - Operator_anglesContext _localctx = new Operator_anglesContext(Context, State); - EnterRule(_localctx, 314, RULE_operator_angles); - try { - State = 1533; - ErrorHandler.Sync(this); - switch ( Interpreter.AdaptivePredict(TokenStream,188,Context) ) { - case 1: - EnterOuterAlt(_localctx, 1); - { - State = 1501; - Match(T__64); - } - break; - case 2: - EnterOuterAlt(_localctx, 2); - { - State = 1502; - Match(T__64); - State = 1503; - Match(T__64); - } - break; - case 3: - EnterOuterAlt(_localctx, 3); - { - State = 1504; - Match(T__64); - State = 1505; - Match(T__64); - State = 1506; - Match(T__64); - } - break; - case 4: - EnterOuterAlt(_localctx, 4); - { - State = 1507; - Match(T__64); - State = 1508; - Match(T__64); - State = 1509; - Match(T__64); - State = 1510; - Match(T__64); - State = 1511; - Match(T__64); - } - break; - case 5: - EnterOuterAlt(_localctx, 5); - { - State = 1512; - Match(T__64); - State = 1513; - Match(T__64); - State = 1514; - Match(T__64); - State = 1515; - Match(T__64); - State = 1516; - Match(T__64); - State = 1517; - Match(T__64); - } - break; - case 6: - EnterOuterAlt(_localctx, 6); - { - State = 1518; - Match(T__64); - State = 1519; - Match(T__64); - State = 1520; - Match(T__64); - State = 1521; - Match(T__64); - State = 1522; - Match(T__64); - State = 1523; - Match(T__64); - State = 1524; - Match(T__64); - } - break; - case 7: - EnterOuterAlt(_localctx, 7); - { - State = 1525; - Match(T__64); - State = 1526; - Match(T__64); - State = 1527; - Match(T__64); - State = 1528; - Match(T__64); - State = 1529; - Match(T__64); - State = 1530; - Match(T__64); - State = 1531; - Match(T__64); - State = 1532; - Match(T__64); - } - break; - } - } - catch (RecognitionException re) { - _localctx.exception = re; - ErrorHandler.ReportError(this, re); - ErrorHandler.Recover(this, re); - } - finally { - ExitRule(); - } - return _localctx; - } - - public override bool Sempred(RuleContext _localctx, int ruleIndex, int predIndex) { - switch (ruleIndex) { - case 111: return pattern_sempred((PatternContext)_localctx, predIndex); - case 119: return type_sempred((TypeContext)_localctx, predIndex); - } - return true; - } - private bool pattern_sempred(PatternContext _localctx, int predIndex) { - switch (predIndex) { - case 0: return Precpred(Context, 1); - } - return true; - } - private bool type_sempred(TypeContext _localctx, int predIndex) { - switch (predIndex) { - case 1: return Precpred(Context, 9); - case 2: return Precpred(Context, 8); - case 3: return Precpred(Context, 6); - case 4: return Precpred(Context, 5); - } - return true; - } - - private static char[] _serializedATN = { - '\x3', '\x608B', '\xA72A', '\x8133', '\xB9ED', '\x417C', '\x3BE7', '\x7786', - '\x5964', '\x3', '\x98', '\x602', '\x4', '\x2', '\t', '\x2', '\x4', '\x3', - '\t', '\x3', '\x4', '\x4', '\t', '\x4', '\x4', '\x5', '\t', '\x5', '\x4', - '\x6', '\t', '\x6', '\x4', '\a', '\t', '\a', '\x4', '\b', '\t', '\b', - '\x4', '\t', '\t', '\t', '\x4', '\n', '\t', '\n', '\x4', '\v', '\t', '\v', - '\x4', '\f', '\t', '\f', '\x4', '\r', '\t', '\r', '\x4', '\xE', '\t', - '\xE', '\x4', '\xF', '\t', '\xF', '\x4', '\x10', '\t', '\x10', '\x4', - '\x11', '\t', '\x11', '\x4', '\x12', '\t', '\x12', '\x4', '\x13', '\t', - '\x13', '\x4', '\x14', '\t', '\x14', '\x4', '\x15', '\t', '\x15', '\x4', - '\x16', '\t', '\x16', '\x4', '\x17', '\t', '\x17', '\x4', '\x18', '\t', - '\x18', '\x4', '\x19', '\t', '\x19', '\x4', '\x1A', '\t', '\x1A', '\x4', - '\x1B', '\t', '\x1B', '\x4', '\x1C', '\t', '\x1C', '\x4', '\x1D', '\t', - '\x1D', '\x4', '\x1E', '\t', '\x1E', '\x4', '\x1F', '\t', '\x1F', '\x4', - ' ', '\t', ' ', '\x4', '!', '\t', '!', '\x4', '\"', '\t', '\"', '\x4', - '#', '\t', '#', '\x4', '$', '\t', '$', '\x4', '%', '\t', '%', '\x4', '&', - '\t', '&', '\x4', '\'', '\t', '\'', '\x4', '(', '\t', '(', '\x4', ')', - '\t', ')', '\x4', '*', '\t', '*', '\x4', '+', '\t', '+', '\x4', ',', '\t', - ',', '\x4', '-', '\t', '-', '\x4', '.', '\t', '.', '\x4', '/', '\t', '/', - '\x4', '\x30', '\t', '\x30', '\x4', '\x31', '\t', '\x31', '\x4', '\x32', - '\t', '\x32', '\x4', '\x33', '\t', '\x33', '\x4', '\x34', '\t', '\x34', - '\x4', '\x35', '\t', '\x35', '\x4', '\x36', '\t', '\x36', '\x4', '\x37', - '\t', '\x37', '\x4', '\x38', '\t', '\x38', '\x4', '\x39', '\t', '\x39', - '\x4', ':', '\t', ':', '\x4', ';', '\t', ';', '\x4', '<', '\t', '<', '\x4', - '=', '\t', '=', '\x4', '>', '\t', '>', '\x4', '?', '\t', '?', '\x4', '@', - '\t', '@', '\x4', '\x41', '\t', '\x41', '\x4', '\x42', '\t', '\x42', '\x4', - '\x43', '\t', '\x43', '\x4', '\x44', '\t', '\x44', '\x4', '\x45', '\t', - '\x45', '\x4', '\x46', '\t', '\x46', '\x4', 'G', '\t', 'G', '\x4', 'H', - '\t', 'H', '\x4', 'I', '\t', 'I', '\x4', 'J', '\t', 'J', '\x4', 'K', '\t', - 'K', '\x4', 'L', '\t', 'L', '\x4', 'M', '\t', 'M', '\x4', 'N', '\t', 'N', - '\x4', 'O', '\t', 'O', '\x4', 'P', '\t', 'P', '\x4', 'Q', '\t', 'Q', '\x4', - 'R', '\t', 'R', '\x4', 'S', '\t', 'S', '\x4', 'T', '\t', 'T', '\x4', 'U', - '\t', 'U', '\x4', 'V', '\t', 'V', '\x4', 'W', '\t', 'W', '\x4', 'X', '\t', - 'X', '\x4', 'Y', '\t', 'Y', '\x4', 'Z', '\t', 'Z', '\x4', '[', '\t', '[', - '\x4', '\\', '\t', '\\', '\x4', ']', '\t', ']', '\x4', '^', '\t', '^', - '\x4', '_', '\t', '_', '\x4', '`', '\t', '`', '\x4', '\x61', '\t', '\x61', - '\x4', '\x62', '\t', '\x62', '\x4', '\x63', '\t', '\x63', '\x4', '\x64', - '\t', '\x64', '\x4', '\x65', '\t', '\x65', '\x4', '\x66', '\t', '\x66', - '\x4', 'g', '\t', 'g', '\x4', 'h', '\t', 'h', '\x4', 'i', '\t', 'i', '\x4', - 'j', '\t', 'j', '\x4', 'k', '\t', 'k', '\x4', 'l', '\t', 'l', '\x4', 'm', - '\t', 'm', '\x4', 'n', '\t', 'n', '\x4', 'o', '\t', 'o', '\x4', 'p', '\t', - 'p', '\x4', 'q', '\t', 'q', '\x4', 'r', '\t', 'r', '\x4', 's', '\t', 's', - '\x4', 't', '\t', 't', '\x4', 'u', '\t', 'u', '\x4', 'v', '\t', 'v', '\x4', - 'w', '\t', 'w', '\x4', 'x', '\t', 'x', '\x4', 'y', '\t', 'y', '\x4', 'z', - '\t', 'z', '\x4', '{', '\t', '{', '\x4', '|', '\t', '|', '\x4', '}', '\t', - '}', '\x4', '~', '\t', '~', '\x4', '\x7F', '\t', '\x7F', '\x4', '\x80', - '\t', '\x80', '\x4', '\x81', '\t', '\x81', '\x4', '\x82', '\t', '\x82', - '\x4', '\x83', '\t', '\x83', '\x4', '\x84', '\t', '\x84', '\x4', '\x85', - '\t', '\x85', '\x4', '\x86', '\t', '\x86', '\x4', '\x87', '\t', '\x87', - '\x4', '\x88', '\t', '\x88', '\x4', '\x89', '\t', '\x89', '\x4', '\x8A', - '\t', '\x8A', '\x4', '\x8B', '\t', '\x8B', '\x4', '\x8C', '\t', '\x8C', - '\x4', '\x8D', '\t', '\x8D', '\x4', '\x8E', '\t', '\x8E', '\x4', '\x8F', - '\t', '\x8F', '\x4', '\x90', '\t', '\x90', '\x4', '\x91', '\t', '\x91', - '\x4', '\x92', '\t', '\x92', '\x4', '\x93', '\t', '\x93', '\x4', '\x94', - '\t', '\x94', '\x4', '\x95', '\t', '\x95', '\x4', '\x96', '\t', '\x96', - '\x4', '\x97', '\t', '\x97', '\x4', '\x98', '\t', '\x98', '\x4', '\x99', - '\t', '\x99', '\x4', '\x9A', '\t', '\x9A', '\x4', '\x9B', '\t', '\x9B', - '\x4', '\x9C', '\t', '\x9C', '\x4', '\x9D', '\t', '\x9D', '\x4', '\x9E', - '\t', '\x9E', '\x4', '\x9F', '\t', '\x9F', '\x3', '\x2', '\a', '\x2', - '\x140', '\n', '\x2', '\f', '\x2', '\xE', '\x2', '\x143', '\v', '\x2', - '\x3', '\x3', '\x3', '\x3', '\x3', '\x3', '\x5', '\x3', '\x148', '\n', - '\x3', '\x3', '\x4', '\x3', '\x4', '\x3', '\x5', '\x3', '\x5', '\x3', - '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', - '\x5', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x5', '\x5', '\x157', - '\n', '\x5', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', - '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', - '\x6', '\x3', '\x6', '\x3', '\x6', '\x3', '\x6', '\x5', '\x6', '\x166', - '\n', '\x6', '\x3', '\a', '\x5', '\a', '\x169', '\n', '\a', '\x3', '\a', - '\x3', '\a', '\x5', '\a', '\x16D', '\n', '\a', '\x3', '\a', '\x3', '\a', - '\x3', '\b', '\x3', '\b', '\x3', '\t', '\x3', '\t', '\x3', '\t', '\a', - '\t', '\x176', '\n', '\t', '\f', '\t', '\xE', '\t', '\x179', '\v', '\t', - '\x3', '\n', '\x3', '\n', '\x3', '\v', '\x3', '\v', '\x3', '\v', '\x3', - '\v', '\a', '\v', '\x181', '\n', '\v', '\f', '\v', '\xE', '\v', '\x184', - '\v', '\v', '\x3', '\f', '\x5', '\f', '\x187', '\n', '\f', '\x3', '\f', - '\x5', '\f', '\x18A', '\n', '\f', '\x3', '\f', '\x3', '\f', '\x5', '\f', - '\x18E', '\n', '\f', '\x3', '\f', '\x5', '\f', '\x191', '\n', '\f', '\x3', - '\f', '\x5', '\f', '\x194', '\n', '\f', '\x3', '\r', '\x3', '\r', '\x3', - '\r', '\x5', '\r', '\x199', '\n', '\r', '\x3', '\r', '\x3', '\r', '\x3', - '\r', '\x5', '\r', '\x19E', '\n', '\r', '\x5', '\r', '\x1A0', '\n', '\r', - '\x3', '\xE', '\x3', '\xE', '\x3', '\xF', '\x3', '\xF', '\x3', '\x10', - '\x3', '\x10', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', - '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', - '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', '\x3', '\x11', - '\x5', '\x11', '\x1B6', '\n', '\x11', '\x3', '\x12', '\x5', '\x12', '\x1B9', - '\n', '\x12', '\x3', '\x12', '\x5', '\x12', '\x1BC', '\n', '\x12', '\x3', - '\x12', '\x3', '\x12', '\x5', '\x12', '\x1C0', '\n', '\x12', '\x3', '\x13', - '\x5', '\x13', '\x1C3', '\n', '\x13', '\x3', '\x13', '\x5', '\x13', '\x1C6', - '\n', '\x13', '\x3', '\x13', '\x3', '\x13', '\x5', '\x13', '\x1CA', '\n', - '\x13', '\x3', '\x13', '\x5', '\x13', '\x1CD', '\n', '\x13', '\x3', '\x13', - '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x3', '\x13', '\x5', '\x13', - '\x1D4', '\n', '\x13', '\x3', '\x14', '\x3', '\x14', '\x3', '\x15', '\x5', - '\x15', '\x1D9', '\n', '\x15', '\x3', '\x15', '\x5', '\x15', '\x1DC', - '\n', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x15', '\x5', '\x15', - '\x1E1', '\n', '\x15', '\x3', '\x15', '\x3', '\x15', '\x3', '\x16', '\x3', - '\x16', '\x3', '\x17', '\x3', '\x17', '\x3', '\x17', '\x3', '\x18', '\x5', - '\x18', '\x1EB', '\n', '\x18', '\x3', '\x18', '\x5', '\x18', '\x1EE', - '\n', '\x18', '\x3', '\x18', '\x3', '\x18', '\x5', '\x18', '\x1F2', '\n', - '\x18', '\x3', '\x18', '\x5', '\x18', '\x1F5', '\n', '\x18', '\x3', '\x18', - '\x5', '\x18', '\x1F8', '\n', '\x18', '\x3', '\x19', '\x5', '\x19', '\x1FB', - '\n', '\x19', '\x3', '\x19', '\x3', '\x19', '\x3', '\x19', '\x5', '\x19', - '\x200', '\n', '\x19', '\x3', '\x19', '\x5', '\x19', '\x203', '\n', '\x19', - '\x3', '\x19', '\x5', '\x19', '\x206', '\n', '\x19', '\x3', '\x19', '\x3', - '\x19', '\x5', '\x19', '\x20A', '\n', '\x19', '\x3', '\x19', '\x3', '\x19', - '\x3', '\x1A', '\x3', '\x1A', '\x5', '\x1A', '\x210', '\n', '\x1A', '\x3', - '\x1B', '\x3', '\x1B', '\x5', '\x1B', '\x214', '\n', '\x1B', '\x3', '\x1C', - '\x5', '\x1C', '\x217', '\n', '\x1C', '\x3', '\x1C', '\x5', '\x1C', '\x21A', - '\n', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1C', '\x3', '\x1D', - '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x3', '\x1D', '\x5', '\x1D', - '\x224', '\n', '\x1D', '\x3', '\x1E', '\x3', '\x1E', '\x5', '\x1E', '\x228', - '\n', '\x1E', '\x3', '\x1F', '\x3', '\x1F', '\x3', ' ', '\x3', ' ', '\x3', - '!', '\x3', '!', '\x3', '!', '\x5', '!', '\x231', '\n', '!', '\x3', '!', - '\x3', '!', '\x5', '!', '\x235', '\n', '!', '\x3', '!', '\x3', '!', '\x3', - '!', '\x3', '!', '\x3', '\"', '\x3', '\"', '\x5', '\"', '\x23D', '\n', - '\"', '\x3', '#', '\x3', '#', '\x5', '#', '\x241', '\n', '#', '\x3', '$', - '\x5', '$', '\x244', '\n', '$', '\x3', '$', '\x3', '$', '\x3', '$', '\x3', - '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x3', '%', '\x5', '%', '\x24E', - '\n', '%', '\x3', '&', '\x3', '&', '\x5', '&', '\x252', '\n', '&', '\x3', - '\'', '\x3', '\'', '\x3', '\'', '\x3', '(', '\x3', '(', '\x3', '(', '\x5', - '(', '\x25A', '\n', '(', '\x3', ')', '\x5', ')', '\x25D', '\n', ')', '\x3', - ')', '\x5', ')', '\x260', '\n', ')', '\x3', ')', '\x3', ')', '\x3', ')', - '\x5', ')', '\x265', '\n', ')', '\x3', ')', '\x5', ')', '\x268', '\n', - ')', '\x3', ')', '\x5', ')', '\x26B', '\n', ')', '\x3', ')', '\x3', ')', - '\x3', '*', '\x3', '*', '\x3', '+', '\x3', '+', '\a', '+', '\x273', '\n', - '+', '\f', '+', '\xE', '+', '\x276', '\v', '+', '\x3', '+', '\x3', '+', - '\x3', ',', '\x3', ',', '\x3', '-', '\x5', '-', '\x27D', '\n', '-', '\x3', - '-', '\x5', '-', '\x280', '\n', '-', '\x3', '-', '\x5', '-', '\x283', - '\n', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x288', '\n', - '-', '\x3', '-', '\x5', '-', '\x28B', '\n', '-', '\x3', '-', '\x5', '-', - '\x28E', '\n', '-', '\x3', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x293', - '\n', '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x297', '\n', '-', '\x3', - '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x29C', '\n', '-', '\x3', '-', - '\x5', '-', '\x29F', '\n', '-', '\x3', '-', '\x5', '-', '\x2A2', '\n', - '-', '\x3', '-', '\x3', '-', '\x5', '-', '\x2A6', '\n', '-', '\x3', '.', - '\x3', '.', '\x3', '/', '\x3', '/', '\a', '/', '\x2AC', '\n', '/', '\f', - '/', '\xE', '/', '\x2AF', '\v', '/', '\x3', '/', '\x3', '/', '\x3', '\x30', - '\x3', '\x30', '\x3', '\x31', '\x3', '\x31', '\x3', '\x32', '\x5', '\x32', - '\x2B8', '\n', '\x32', '\x3', '\x32', '\x5', '\x32', '\x2BB', '\n', '\x32', - '\x3', '\x32', '\x3', '\x32', '\x3', '\x32', '\x5', '\x32', '\x2C0', '\n', - '\x32', '\x3', '\x32', '\x3', '\x32', '\x3', '\x33', '\x3', '\x33', '\x3', - '\x34', '\x3', '\x34', '\a', '\x34', '\x2C8', '\n', '\x34', '\f', '\x34', - '\xE', '\x34', '\x2CB', '\v', '\x34', '\x3', '\x34', '\x3', '\x34', '\x3', - '\x35', '\x3', '\x35', '\x3', '\x36', '\x3', '\x36', '\x3', '\x36', '\x3', - '\x36', '\x3', '\x36', '\x3', '\x36', '\x5', '\x36', '\x2D7', '\n', '\x36', - '\x3', '\x37', '\x3', '\x37', '\x3', '\x37', '\x5', '\x37', '\x2DC', '\n', - '\x37', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', '\x38', '\x3', - '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', '\x39', '\x3', ':', '\x3', - ':', '\x3', ':', '\x3', ':', '\x5', ':', '\x2EA', '\n', ':', '\x3', ';', - '\x3', ';', '\x3', ';', '\x3', '<', '\x3', '<', '\x3', '<', '\x3', '<', - '\a', '<', '\x2F3', '\n', '<', '\f', '<', '\xE', '<', '\x2F6', '\v', '<', - '\x3', '<', '\x3', '<', '\x3', '=', '\x3', '=', '\x3', '=', '\x5', '=', - '\x2FD', '\n', '=', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', '>', '\x3', - '>', '\x3', '>', '\x5', '>', '\x305', '\n', '>', '\x3', '?', '\x3', '?', - '\x3', '?', '\x3', '?', '\x3', '@', '\x3', '@', '\x3', '@', '\x3', '@', - '\x3', '\x41', '\x3', '\x41', '\x3', '\x42', '\x3', '\x42', '\x3', '\x42', - '\a', '\x42', '\x314', '\n', '\x42', '\f', '\x42', '\xE', '\x42', '\x317', - '\v', '\x42', '\x3', '\x43', '\x3', '\x43', '\x3', '\x44', '\x5', '\x44', - '\x31C', '\n', '\x44', '\x3', '\x44', '\x5', '\x44', '\x31F', '\n', '\x44', - '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', '\x44', '\x324', '\n', - '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', '\x44', '\x329', - '\n', '\x44', '\x3', '\x44', '\x5', '\x44', '\x32C', '\n', '\x44', '\x3', - '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x3', '\x44', '\x5', - '\x44', '\x333', '\n', '\x44', '\x3', '\x45', '\x3', '\x45', '\a', '\x45', - '\x337', '\n', '\x45', '\f', '\x45', '\xE', '\x45', '\x33A', '\v', '\x45', - '\x3', '\x45', '\x3', '\x45', '\x3', '\x46', '\x3', '\x46', '\x3', 'G', - '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', '\x3', 'G', - '\x5', 'G', '\x347', '\n', 'G', '\x3', 'H', '\x5', 'H', '\x34A', '\n', - 'H', '\x3', 'H', '\x5', 'H', '\x34D', '\n', 'H', '\x3', 'H', '\x3', 'H', - '\x3', 'H', '\x3', 'I', '\x3', 'I', '\x5', 'I', '\x354', '\n', 'I', '\x3', - 'I', '\x3', 'I', '\x3', 'J', '\x5', 'J', '\x359', '\n', 'J', '\x3', 'J', - '\x5', 'J', '\x35C', '\n', 'J', '\x3', 'J', '\x3', 'J', '\x3', 'J', '\x5', - 'J', '\x361', '\n', 'J', '\x3', 'J', '\x5', 'J', '\x364', '\n', 'J', '\x3', - 'J', '\x5', 'J', '\x367', '\n', 'J', '\x3', 'K', '\x3', 'K', '\x3', 'K', - '\x5', 'K', '\x36C', '\n', 'K', '\x3', 'K', '\x3', 'K', '\x5', 'K', '\x370', - '\n', 'K', '\x3', 'K', '\x5', 'K', '\x373', '\n', 'K', '\x3', 'L', '\x5', - 'L', '\x376', '\n', 'L', '\x3', 'L', '\x5', 'L', '\x379', '\n', 'L', '\x3', - 'L', '\x3', 'L', '\x3', 'M', '\x3', 'M', '\x5', 'M', '\x37F', '\n', 'M', - '\x3', 'N', '\x3', 'N', '\a', 'N', '\x383', '\n', 'N', '\f', 'N', '\xE', - 'N', '\x386', '\v', 'N', '\x3', 'N', '\x3', 'N', '\x3', 'O', '\x3', 'O', - '\x3', 'P', '\x3', 'P', '\x5', 'P', '\x38E', '\n', 'P', '\x3', 'P', '\x5', - 'P', '\x391', '\n', 'P', '\x3', 'P', '\x5', 'P', '\x394', '\n', 'P', '\x3', - 'P', '\x3', 'P', '\x5', 'P', '\x398', '\n', 'P', '\x3', 'P', '\x3', 'P', - '\x5', 'P', '\x39C', '\n', 'P', '\x5', 'P', '\x39E', '\n', 'P', '\x3', - 'Q', '\x3', 'Q', '\x3', 'R', '\x3', 'R', '\x3', 'S', '\x3', 'S', '\x3', - 'T', '\x3', 'T', '\x5', 'T', '\x3A8', '\n', 'T', '\x3', 'T', '\x3', 'T', - '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3AE', '\n', 'U', '\x3', 'U', '\x3', - 'U', '\x5', 'U', '\x3B2', '\n', 'U', '\x3', 'U', '\x5', 'U', '\x3B5', - '\n', 'U', '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3B9', '\n', 'U', '\x3', - 'U', '\x3', 'U', '\x3', 'U', '\x5', 'U', '\x3BE', '\n', 'U', '\x5', 'U', - '\x3C0', '\n', 'U', '\x3', 'V', '\x5', 'V', '\x3C3', '\n', 'V', '\x3', - 'V', '\x5', 'V', '\x3C6', '\n', 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', - '\x3CA', '\n', 'V', '\x3', 'V', '\x5', 'V', '\x3CD', '\n', 'V', '\x3', - 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', '\x3D2', '\n', 'V', '\x3', 'V', - '\x5', 'V', '\x3D5', '\n', 'V', '\x3', 'V', '\x3', 'V', '\x5', 'V', '\x3D9', - '\n', 'V', '\x3', 'W', '\x5', 'W', '\x3DC', '\n', 'W', '\x3', 'W', '\x5', - 'W', '\x3DF', '\n', 'W', '\x3', 'W', '\x3', 'W', '\x3', 'X', '\x3', 'X', - '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x3', 'X', '\x5', 'X', '\x3E9', '\n', - 'X', '\x3', 'Y', '\x3', 'Y', '\x3', 'Y', '\a', 'Y', '\x3EE', '\n', 'Y', - '\f', 'Y', '\xE', 'Y', '\x3F1', '\v', 'Y', '\x3', 'Z', '\x5', 'Z', '\x3F4', - '\n', 'Z', '\x3', 'Z', '\x3', 'Z', '\x3', 'Z', '\x5', 'Z', '\x3F9', '\n', - 'Z', '\x3', 'Z', '\x5', 'Z', '\x3FC', '\n', 'Z', '\x3', 'Z', '\x3', 'Z', - '\x3', 'Z', '\x3', 'Z', '\x5', 'Z', '\x402', '\n', 'Z', '\x3', '[', '\x3', - '[', '\x3', '\\', '\x3', '\\', '\x3', ']', '\x3', ']', '\x6', ']', '\x40A', - '\n', ']', '\r', ']', '\xE', ']', '\x40B', '\x3', '^', '\x3', '^', '\a', - '^', '\x410', '\n', '^', '\f', '^', '\xE', '^', '\x413', '\v', '^', '\x3', - '^', '\x3', '^', '\x3', '^', '\a', '^', '\x418', '\n', '^', '\f', '^', - '\xE', '^', '\x41B', '\v', '^', '\x3', '^', '\x3', '^', '\x3', '^', '\a', - '^', '\x420', '\n', '^', '\f', '^', '\xE', '^', '\x423', '\v', '^', '\x3', - '^', '\x3', '^', '\x3', '^', '\x3', '^', '\x3', '^', '\x5', '^', '\x42A', - '\n', '^', '\x3', '_', '\x3', '_', '\x5', '_', '\x42E', '\n', '_', '\x3', - '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', - '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', - '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x3', '`', '\x5', '`', '\x441', - '\n', '`', '\x3', '`', '\x5', '`', '\x444', '\n', '`', '\x3', '\x61', - '\x3', '\x61', '\x3', '\x61', '\x3', '\x62', '\x3', '\x62', '\x5', '\x62', - '\x44B', '\n', '\x62', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', - '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', '\x63', '\x3', - '\x63', '\x5', '\x63', '\x456', '\n', '\x63', '\x3', '\x64', '\x3', '\x64', - '\x3', '\x64', '\x3', '\x64', '\x3', '\x64', '\x5', '\x64', '\x45D', '\n', - '\x64', '\x3', '\x65', '\x3', '\x65', '\x3', '\x66', '\x3', '\x66', '\x3', - '\x66', '\x5', '\x66', '\x464', '\n', '\x66', '\x3', 'g', '\x3', 'g', - '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', 'h', '\x3', 'i', '\x6', 'i', - '\x46D', '\n', 'i', '\r', 'i', '\xE', 'i', '\x46E', '\x3', 'j', '\a', - 'j', '\x472', '\n', 'j', '\f', 'j', '\xE', 'j', '\x475', '\v', 'j', '\x3', - 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', - 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x3', - 'k', '\x3', 'k', '\x3', 'k', '\x3', 'k', '\x5', 'k', '\x487', '\n', 'k', - '\x3', 'l', '\x3', 'l', '\x5', 'l', '\x48B', '\n', 'l', '\x3', 'm', '\x3', - 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', - 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', - 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', - 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x3', 'm', '\x5', 'm', '\x4A5', - '\n', 'm', '\x3', 'n', '\x6', 'n', '\x4A8', '\n', 'n', '\r', 'n', '\xE', - 'n', '\x4A9', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', - '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', - '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', - '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', '\x3', 'o', - '\x3', 'o', '\x3', 'o', '\x5', 'o', '\x4C5', '\n', 'o', '\x3', 'p', '\x3', - 'p', '\x3', 'q', '\x3', 'q', '\x3', 'q', '\x5', 'q', '\x4CC', '\n', 'q', - '\x3', 'q', '\x3', 'q', '\x5', 'q', '\x4D0', '\n', 'q', '\x3', 'q', '\x3', - 'q', '\x5', 'q', '\x4D4', '\n', 'q', '\x3', 'q', '\x3', 'q', '\x3', 'q', - '\a', 'q', '\x4D9', '\n', 'q', '\f', 'q', '\xE', 'q', '\x4DC', '\v', 'q', - '\x3', 'r', '\x3', 'r', '\x3', 's', '\x3', 's', '\x3', 't', '\x5', 't', - '\x4E3', '\n', 't', '\x3', 't', '\x3', 't', '\x5', 't', '\x4E7', '\n', - 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x5', 't', '\x4ED', - '\n', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', '\x3', 't', - '\x5', 't', '\x4F4', '\n', 't', '\x3', 'u', '\x3', 'u', '\x3', 'u', '\x3', - 'u', '\x3', 'u', '\x5', 'u', '\x4FB', '\n', 'u', '\x3', 'u', '\x3', 'u', - '\x5', 'u', '\x4FF', '\n', 'u', '\x3', 'v', '\x3', 'v', '\x3', 'v', '\x3', - 'v', '\x3', 'v', '\x5', 'v', '\x506', '\n', 'v', '\x3', 'w', '\x5', 'w', - '\x509', '\n', 'w', '\x3', 'w', '\x5', 'w', '\x50C', '\n', 'w', '\x3', - 'w', '\x3', 'w', '\x3', 'w', '\x3', 'w', '\x5', 'w', '\x512', '\n', 'w', - '\x3', 'x', '\x3', 'x', '\x3', 'x', '\x3', 'x', '\x5', 'x', '\x518', '\n', - 'x', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', - 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', - 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x5', 'y', '\x529', '\n', 'y', - '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', - '\x3', 'y', '\x3', 'y', '\x3', 'y', '\x3', 'y', '\a', 'y', '\x535', '\n', - 'y', '\f', 'y', '\xE', 'y', '\x538', '\v', 'y', '\x3', 'z', '\x3', 'z', - '\x5', 'z', '\x53C', '\n', 'z', '\x3', 'z', '\x5', 'z', '\x53F', '\n', - 'z', '\x3', 'z', '\x3', 'z', '\x3', '{', '\x3', '{', '\x3', '|', '\x3', - '|', '\x3', '}', '\x3', '}', '\x5', '}', '\x549', '\n', '}', '\x3', '}', - '\x3', '}', '\x5', '}', '\x54D', '\n', '}', '\x3', '~', '\x3', '~', '\x3', - '\x7F', '\x3', '\x7F', '\x5', '\x7F', '\x553', '\n', '\x7F', '\x3', '\x7F', - '\x3', '\x7F', '\x3', '\x80', '\x3', '\x80', '\x3', '\x80', '\x3', '\x80', - '\x3', '\x80', '\x5', '\x80', '\x55C', '\n', '\x80', '\x3', '\x81', '\x3', - '\x81', '\x3', '\x81', '\x3', '\x81', '\x5', '\x81', '\x562', '\n', '\x81', - '\x3', '\x82', '\x3', '\x82', '\x3', '\x83', '\x3', '\x83', '\x3', '\x83', - '\x3', '\x83', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', '\x3', '\x84', - '\x3', '\x84', '\x3', '\x84', '\x3', '\x85', '\x3', '\x85', '\x3', '\x85', - '\x6', '\x85', '\x573', '\n', '\x85', '\r', '\x85', '\xE', '\x85', '\x574', - '\x3', '\x86', '\x3', '\x86', '\x3', '\x87', '\x3', '\x87', '\x3', '\x87', - '\x3', '\x87', '\x5', '\x87', '\x57D', '\n', '\x87', '\x3', '\x88', '\x3', - '\x88', '\x3', '\x89', '\x3', '\x89', '\x3', '\x8A', '\x5', '\x8A', '\x584', - '\n', '\x8A', '\x3', '\x8A', '\x3', '\x8A', '\x3', '\x8B', '\x3', '\x8B', - '\x3', '\x8C', '\x3', '\x8C', '\x3', '\x8D', '\x3', '\x8D', '\x5', '\x8D', - '\x58E', '\n', '\x8D', '\x3', '\x8E', '\x3', '\x8E', '\x3', '\x8E', '\x3', - '\x8E', '\x3', '\x8F', '\x3', '\x8F', '\x3', '\x8F', '\a', '\x8F', '\x597', - '\n', '\x8F', '\f', '\x8F', '\xE', '\x8F', '\x59A', '\v', '\x8F', '\x3', - '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', - '\x90', '\x3', '\x90', '\x3', '\x90', '\x3', '\x90', '\x5', '\x90', '\x5A5', - '\n', '\x90', '\x3', '\x91', '\x3', '\x91', '\x3', '\x91', '\x3', '\x92', - '\x3', '\x92', '\x3', '\x92', '\a', '\x92', '\x5AD', '\n', '\x92', '\f', - '\x92', '\xE', '\x92', '\x5B0', '\v', '\x92', '\x3', '\x93', '\x3', '\x93', - '\x5', '\x93', '\x5B4', '\n', '\x93', '\x3', '\x94', '\x3', '\x94', '\x3', - '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', '\x94', '\x3', - '\x94', '\x5', '\x94', '\x5BE', '\n', '\x94', '\x3', '\x95', '\x3', '\x95', - '\x3', '\x95', '\x3', '\x95', '\x3', '\x96', '\x3', '\x96', '\x3', '\x96', - '\x3', '\x96', '\x3', '\x97', '\x3', '\x97', '\x3', '\x97', '\a', '\x97', - '\x5CB', '\n', '\x97', '\f', '\x97', '\xE', '\x97', '\x5CE', '\v', '\x97', - '\x3', '\x98', '\x3', '\x98', '\x3', '\x99', '\x3', '\x99', '\x3', '\x9A', - '\x3', '\x9A', '\x3', '\x9B', '\x3', '\x9B', '\x3', '\x9C', '\x3', '\x9C', - '\x3', '\x9D', '\x3', '\x9D', '\x3', '\x9E', '\x3', '\x9E', '\x5', '\x9E', - '\x5DE', '\n', '\x9E', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', - '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x3', '\x9F', '\x5', '\x9F', '\x600', - '\n', '\x9F', '\x3', '\x9F', '\x2', '\x4', '\xE0', '\xF0', '\xA0', '\x2', - '\x4', '\x6', '\b', '\n', '\f', '\xE', '\x10', '\x12', '\x14', '\x16', - '\x18', '\x1A', '\x1C', '\x1E', ' ', '\"', '$', '&', '(', '*', ',', '.', - '\x30', '\x32', '\x34', '\x36', '\x38', ':', '<', '>', '@', '\x42', '\x44', - '\x46', 'H', 'J', 'L', 'N', 'P', 'R', 'T', 'V', 'X', 'Z', '\\', '^', '`', - '\x62', '\x64', '\x66', 'h', 'j', 'l', 'n', 'p', 'r', 't', 'v', 'x', 'z', - '|', '~', '\x80', '\x82', '\x84', '\x86', '\x88', '\x8A', '\x8C', '\x8E', - '\x90', '\x92', '\x94', '\x96', '\x98', '\x9A', '\x9C', '\x9E', '\xA0', - '\xA2', '\xA4', '\xA6', '\xA8', '\xAA', '\xAC', '\xAE', '\xB0', '\xB2', - '\xB4', '\xB6', '\xB8', '\xBA', '\xBC', '\xBE', '\xC0', '\xC2', '\xC4', - '\xC6', '\xC8', '\xCA', '\xCC', '\xCE', '\xD0', '\xD2', '\xD4', '\xD6', - '\xD8', '\xDA', '\xDC', '\xDE', '\xE0', '\xE2', '\xE4', '\xE6', '\xE8', - '\xEA', '\xEC', '\xEE', '\xF0', '\xF2', '\xF4', '\xF6', '\xF8', '\xFA', - '\xFC', '\xFE', '\x100', '\x102', '\x104', '\x106', '\x108', '\x10A', - '\x10C', '\x10E', '\x110', '\x112', '\x114', '\x116', '\x118', '\x11A', - '\x11C', '\x11E', '\x120', '\x122', '\x124', '\x126', '\x128', '\x12A', - '\x12C', '\x12E', '\x130', '\x132', '\x134', '\x136', '\x138', '\x13A', - '\x13C', '\x2', '\v', '\x3', '\x2', '\x4', '\n', '\x3', '\x2', '\x1A', - '\x1C', '\x6', '\x2', '~', '~', '\x80', '\x80', '\x83', '\x84', '\x86', - '\x8A', '\x3', '\x2', '\x35', '\x36', '\x3', '\x2', '@', '\x41', '\x3', - '\x2', '|', '}', '\x3', '\x2', 's', 'w', '\v', '\x2', '\f', '\xE', '\x10', - '\x11', '\x13', '\x14', '\x16', '\x1C', '%', '*', ',', '/', '\x34', '\x36', - '\x39', ':', '\x46', '^', '\b', '\x2', '\x3', '\b', '\n', '\n', '\f', - '\x1F', '!', '<', '?', '\x42', '\x46', 'r', '\x2', '\x683', '\x2', '\x141', - '\x3', '\x2', '\x2', '\x2', '\x4', '\x147', '\x3', '\x2', '\x2', '\x2', - '\x6', '\x149', '\x3', '\x2', '\x2', '\x2', '\b', '\x156', '\x3', '\x2', - '\x2', '\x2', '\n', '\x165', '\x3', '\x2', '\x2', '\x2', '\f', '\x168', - '\x3', '\x2', '\x2', '\x2', '\xE', '\x170', '\x3', '\x2', '\x2', '\x2', - '\x10', '\x172', '\x3', '\x2', '\x2', '\x2', '\x12', '\x17A', '\x3', '\x2', - '\x2', '\x2', '\x14', '\x17C', '\x3', '\x2', '\x2', '\x2', '\x16', '\x193', - '\x3', '\x2', '\x2', '\x2', '\x18', '\x19F', '\x3', '\x2', '\x2', '\x2', - '\x1A', '\x1A1', '\x3', '\x2', '\x2', '\x2', '\x1C', '\x1A3', '\x3', '\x2', - '\x2', '\x2', '\x1E', '\x1A5', '\x3', '\x2', '\x2', '\x2', ' ', '\x1B5', - '\x3', '\x2', '\x2', '\x2', '\"', '\x1B8', '\x3', '\x2', '\x2', '\x2', - '$', '\x1D3', '\x3', '\x2', '\x2', '\x2', '&', '\x1D5', '\x3', '\x2', - '\x2', '\x2', '(', '\x1D8', '\x3', '\x2', '\x2', '\x2', '*', '\x1E4', - '\x3', '\x2', '\x2', '\x2', ',', '\x1E6', '\x3', '\x2', '\x2', '\x2', - '.', '\x1F7', '\x3', '\x2', '\x2', '\x2', '\x30', '\x1FA', '\x3', '\x2', - '\x2', '\x2', '\x32', '\x20D', '\x3', '\x2', '\x2', '\x2', '\x34', '\x213', - '\x3', '\x2', '\x2', '\x2', '\x36', '\x216', '\x3', '\x2', '\x2', '\x2', - '\x38', '\x223', '\x3', '\x2', '\x2', '\x2', ':', '\x225', '\x3', '\x2', - '\x2', '\x2', '<', '\x229', '\x3', '\x2', '\x2', '\x2', '>', '\x22B', - '\x3', '\x2', '\x2', '\x2', '@', '\x22D', '\x3', '\x2', '\x2', '\x2', - '\x42', '\x23A', '\x3', '\x2', '\x2', '\x2', '\x44', '\x240', '\x3', '\x2', - '\x2', '\x2', '\x46', '\x243', '\x3', '\x2', '\x2', '\x2', 'H', '\x24D', - '\x3', '\x2', '\x2', '\x2', 'J', '\x24F', '\x3', '\x2', '\x2', '\x2', - 'L', '\x253', '\x3', '\x2', '\x2', '\x2', 'N', '\x259', '\x3', '\x2', - '\x2', '\x2', 'P', '\x25C', '\x3', '\x2', '\x2', '\x2', 'R', '\x26E', - '\x3', '\x2', '\x2', '\x2', 'T', '\x270', '\x3', '\x2', '\x2', '\x2', - 'V', '\x279', '\x3', '\x2', '\x2', '\x2', 'X', '\x2A5', '\x3', '\x2', - '\x2', '\x2', 'Z', '\x2A7', '\x3', '\x2', '\x2', '\x2', '\\', '\x2A9', - '\x3', '\x2', '\x2', '\x2', '^', '\x2B2', '\x3', '\x2', '\x2', '\x2', - '`', '\x2B4', '\x3', '\x2', '\x2', '\x2', '\x62', '\x2B7', '\x3', '\x2', - '\x2', '\x2', '\x64', '\x2C3', '\x3', '\x2', '\x2', '\x2', '\x66', '\x2C5', - '\x3', '\x2', '\x2', '\x2', 'h', '\x2CE', '\x3', '\x2', '\x2', '\x2', - 'j', '\x2D6', '\x3', '\x2', '\x2', '\x2', 'l', '\x2DB', '\x3', '\x2', - '\x2', '\x2', 'n', '\x2DD', '\x3', '\x2', '\x2', '\x2', 'p', '\x2E1', - '\x3', '\x2', '\x2', '\x2', 'r', '\x2E5', '\x3', '\x2', '\x2', '\x2', - 't', '\x2EB', '\x3', '\x2', '\x2', '\x2', 'v', '\x2EE', '\x3', '\x2', - '\x2', '\x2', 'x', '\x2FC', '\x3', '\x2', '\x2', '\x2', 'z', '\x304', - '\x3', '\x2', '\x2', '\x2', '|', '\x306', '\x3', '\x2', '\x2', '\x2', - '~', '\x30A', '\x3', '\x2', '\x2', '\x2', '\x80', '\x30E', '\x3', '\x2', - '\x2', '\x2', '\x82', '\x310', '\x3', '\x2', '\x2', '\x2', '\x84', '\x318', - '\x3', '\x2', '\x2', '\x2', '\x86', '\x332', '\x3', '\x2', '\x2', '\x2', - '\x88', '\x334', '\x3', '\x2', '\x2', '\x2', '\x8A', '\x33D', '\x3', '\x2', - '\x2', '\x2', '\x8C', '\x346', '\x3', '\x2', '\x2', '\x2', '\x8E', '\x349', - '\x3', '\x2', '\x2', '\x2', '\x90', '\x351', '\x3', '\x2', '\x2', '\x2', - '\x92', '\x358', '\x3', '\x2', '\x2', '\x2', '\x94', '\x368', '\x3', '\x2', - '\x2', '\x2', '\x96', '\x375', '\x3', '\x2', '\x2', '\x2', '\x98', '\x37E', - '\x3', '\x2', '\x2', '\x2', '\x9A', '\x380', '\x3', '\x2', '\x2', '\x2', - '\x9C', '\x389', '\x3', '\x2', '\x2', '\x2', '\x9E', '\x39D', '\x3', '\x2', - '\x2', '\x2', '\xA0', '\x39F', '\x3', '\x2', '\x2', '\x2', '\xA2', '\x3A1', - '\x3', '\x2', '\x2', '\x2', '\xA4', '\x3A3', '\x3', '\x2', '\x2', '\x2', - '\xA6', '\x3A5', '\x3', '\x2', '\x2', '\x2', '\xA8', '\x3BF', '\x3', '\x2', - '\x2', '\x2', '\xAA', '\x3D8', '\x3', '\x2', '\x2', '\x2', '\xAC', '\x3DB', - '\x3', '\x2', '\x2', '\x2', '\xAE', '\x3E8', '\x3', '\x2', '\x2', '\x2', - '\xB0', '\x3EA', '\x3', '\x2', '\x2', '\x2', '\xB2', '\x401', '\x3', '\x2', - '\x2', '\x2', '\xB4', '\x403', '\x3', '\x2', '\x2', '\x2', '\xB6', '\x405', - '\x3', '\x2', '\x2', '\x2', '\xB8', '\x407', '\x3', '\x2', '\x2', '\x2', - '\xBA', '\x429', '\x3', '\x2', '\x2', '\x2', '\xBC', '\x42D', '\x3', '\x2', - '\x2', '\x2', '\xBE', '\x443', '\x3', '\x2', '\x2', '\x2', '\xC0', '\x445', - '\x3', '\x2', '\x2', '\x2', '\xC2', '\x44A', '\x3', '\x2', '\x2', '\x2', - '\xC4', '\x455', '\x3', '\x2', '\x2', '\x2', '\xC6', '\x45C', '\x3', '\x2', - '\x2', '\x2', '\xC8', '\x45E', '\x3', '\x2', '\x2', '\x2', '\xCA', '\x460', - '\x3', '\x2', '\x2', '\x2', '\xCC', '\x465', '\x3', '\x2', '\x2', '\x2', - '\xCE', '\x467', '\x3', '\x2', '\x2', '\x2', '\xD0', '\x46C', '\x3', '\x2', - '\x2', '\x2', '\xD2', '\x473', '\x3', '\x2', '\x2', '\x2', '\xD4', '\x486', - '\x3', '\x2', '\x2', '\x2', '\xD6', '\x48A', '\x3', '\x2', '\x2', '\x2', - '\xD8', '\x4A4', '\x3', '\x2', '\x2', '\x2', '\xDA', '\x4A7', '\x3', '\x2', - '\x2', '\x2', '\xDC', '\x4C4', '\x3', '\x2', '\x2', '\x2', '\xDE', '\x4C6', - '\x3', '\x2', '\x2', '\x2', '\xE0', '\x4D3', '\x3', '\x2', '\x2', '\x2', - '\xE2', '\x4DD', '\x3', '\x2', '\x2', '\x2', '\xE4', '\x4DF', '\x3', '\x2', - '\x2', '\x2', '\xE6', '\x4F3', '\x3', '\x2', '\x2', '\x2', '\xE8', '\x4FE', - '\x3', '\x2', '\x2', '\x2', '\xEA', '\x505', '\x3', '\x2', '\x2', '\x2', - '\xEC', '\x511', '\x3', '\x2', '\x2', '\x2', '\xEE', '\x517', '\x3', '\x2', - '\x2', '\x2', '\xF0', '\x528', '\x3', '\x2', '\x2', '\x2', '\xF2', '\x539', - '\x3', '\x2', '\x2', '\x2', '\xF4', '\x542', '\x3', '\x2', '\x2', '\x2', - '\xF6', '\x544', '\x3', '\x2', '\x2', '\x2', '\xF8', '\x546', '\x3', '\x2', - '\x2', '\x2', '\xFA', '\x54E', '\x3', '\x2', '\x2', '\x2', '\xFC', '\x550', - '\x3', '\x2', '\x2', '\x2', '\xFE', '\x55B', '\x3', '\x2', '\x2', '\x2', - '\x100', '\x561', '\x3', '\x2', '\x2', '\x2', '\x102', '\x563', '\x3', - '\x2', '\x2', '\x2', '\x104', '\x565', '\x3', '\x2', '\x2', '\x2', '\x106', - '\x569', '\x3', '\x2', '\x2', '\x2', '\x108', '\x56F', '\x3', '\x2', '\x2', - '\x2', '\x10A', '\x576', '\x3', '\x2', '\x2', '\x2', '\x10C', '\x57C', - '\x3', '\x2', '\x2', '\x2', '\x10E', '\x57E', '\x3', '\x2', '\x2', '\x2', - '\x110', '\x580', '\x3', '\x2', '\x2', '\x2', '\x112', '\x583', '\x3', - '\x2', '\x2', '\x2', '\x114', '\x587', '\x3', '\x2', '\x2', '\x2', '\x116', - '\x589', '\x3', '\x2', '\x2', '\x2', '\x118', '\x58D', '\x3', '\x2', '\x2', - '\x2', '\x11A', '\x58F', '\x3', '\x2', '\x2', '\x2', '\x11C', '\x593', - '\x3', '\x2', '\x2', '\x2', '\x11E', '\x5A4', '\x3', '\x2', '\x2', '\x2', - '\x120', '\x5A6', '\x3', '\x2', '\x2', '\x2', '\x122', '\x5A9', '\x3', - '\x2', '\x2', '\x2', '\x124', '\x5B3', '\x3', '\x2', '\x2', '\x2', '\x126', - '\x5BD', '\x3', '\x2', '\x2', '\x2', '\x128', '\x5BF', '\x3', '\x2', '\x2', - '\x2', '\x12A', '\x5C3', '\x3', '\x2', '\x2', '\x2', '\x12C', '\x5C7', - '\x3', '\x2', '\x2', '\x2', '\x12E', '\x5CF', '\x3', '\x2', '\x2', '\x2', - '\x130', '\x5D1', '\x3', '\x2', '\x2', '\x2', '\x132', '\x5D3', '\x3', - '\x2', '\x2', '\x2', '\x134', '\x5D5', '\x3', '\x2', '\x2', '\x2', '\x136', - '\x5D7', '\x3', '\x2', '\x2', '\x2', '\x138', '\x5D9', '\x3', '\x2', '\x2', - '\x2', '\x13A', '\x5DD', '\x3', '\x2', '\x2', '\x2', '\x13C', '\x5FF', - '\x3', '\x2', '\x2', '\x2', '\x13E', '\x140', '\x5', '\x4', '\x3', '\x2', - '\x13F', '\x13E', '\x3', '\x2', '\x2', '\x2', '\x140', '\x143', '\x3', - '\x2', '\x2', '\x2', '\x141', '\x13F', '\x3', '\x2', '\x2', '\x2', '\x141', - '\x142', '\x3', '\x2', '\x2', '\x2', '\x142', '\x3', '\x3', '\x2', '\x2', - '\x2', '\x143', '\x141', '\x3', '\x2', '\x2', '\x2', '\x144', '\x148', - '\x5', '\f', '\a', '\x2', '\x145', '\x148', '\x5', '\b', '\x5', '\x2', - '\x146', '\x148', '\x5', '\x6', '\x4', '\x2', '\x147', '\x144', '\x3', - '\x2', '\x2', '\x2', '\x147', '\x145', '\x3', '\x2', '\x2', '\x2', '\x147', - '\x146', '\x3', '\x2', '\x2', '\x2', '\x148', '\x5', '\x3', '\x2', '\x2', - '\x2', '\x149', '\x14A', '\a', '\x97', '\x2', '\x2', '\x14A', '\a', '\x3', - '\x2', '\x2', '\x2', '\x14B', '\x157', '\x5', '\x14', '\v', '\x2', '\x14C', - '\x157', '\x5', '(', '\x15', '\x2', '\x14D', '\x157', '\x5', '\x94', 'K', - '\x2', '\x14E', '\x157', '\x5', '.', '\x18', '\x2', '\x14F', '\x157', - '\x5', 'P', ')', '\x2', '\x150', '\x157', '\x5', 'X', '-', '\x2', '\x151', - '\x157', '\x5', '\x62', '\x32', '\x2', '\x152', '\x157', '\x5', '\x86', - '\x44', '\x2', '\x153', '\x157', '\x5', '\x8C', 'G', '\x2', '\x154', '\x157', - '\x5', 'l', '\x37', '\x2', '\x155', '\x157', '\x5', 'v', '<', '\x2', '\x156', - '\x14B', '\x3', '\x2', '\x2', '\x2', '\x156', '\x14C', '\x3', '\x2', '\x2', - '\x2', '\x156', '\x14D', '\x3', '\x2', '\x2', '\x2', '\x156', '\x14E', - '\x3', '\x2', '\x2', '\x2', '\x156', '\x14F', '\x3', '\x2', '\x2', '\x2', - '\x156', '\x150', '\x3', '\x2', '\x2', '\x2', '\x156', '\x151', '\x3', - '\x2', '\x2', '\x2', '\x156', '\x152', '\x3', '\x2', '\x2', '\x2', '\x156', - '\x153', '\x3', '\x2', '\x2', '\x2', '\x156', '\x154', '\x3', '\x2', '\x2', - '\x2', '\x156', '\x155', '\x3', '\x2', '\x2', '\x2', '\x157', '\t', '\x3', - '\x2', '\x2', '\x2', '\x158', '\x166', '\x5', '\x14', '\v', '\x2', '\x159', - '\x166', '\x5', '(', '\x15', '\x2', '\x15A', '\x166', '\x5', '\x94', 'K', - '\x2', '\x15B', '\x166', '\x5', '.', '\x18', '\x2', '\x15C', '\x166', - '\x5', 'P', ')', '\x2', '\x15D', '\x166', '\x5', 'X', '-', '\x2', '\x15E', - '\x166', '\x5', '\x62', '\x32', '\x2', '\x15F', '\x166', '\x5', '\xA8', - 'U', '\x2', '\x160', '\x166', '\x5', '\xAC', 'W', '\x2', '\x161', '\x166', - '\x5', '\x86', '\x44', '\x2', '\x162', '\x166', '\x5', '\x8C', 'G', '\x2', - '\x163', '\x166', '\x5', 'l', '\x37', '\x2', '\x164', '\x166', '\x5', - 'v', '<', '\x2', '\x165', '\x158', '\x3', '\x2', '\x2', '\x2', '\x165', - '\x159', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15A', '\x3', '\x2', '\x2', - '\x2', '\x165', '\x15B', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15C', - '\x3', '\x2', '\x2', '\x2', '\x165', '\x15D', '\x3', '\x2', '\x2', '\x2', - '\x165', '\x15E', '\x3', '\x2', '\x2', '\x2', '\x165', '\x15F', '\x3', - '\x2', '\x2', '\x2', '\x165', '\x160', '\x3', '\x2', '\x2', '\x2', '\x165', - '\x161', '\x3', '\x2', '\x2', '\x2', '\x165', '\x162', '\x3', '\x2', '\x2', - '\x2', '\x165', '\x163', '\x3', '\x2', '\x2', '\x2', '\x165', '\x164', - '\x3', '\x2', '\x2', '\x2', '\x166', '\v', '\x3', '\x2', '\x2', '\x2', - '\x167', '\x169', '\x5', '\xD0', 'i', '\x2', '\x168', '\x167', '\x3', - '\x2', '\x2', '\x2', '\x168', '\x169', '\x3', '\x2', '\x2', '\x2', '\x169', - '\x16A', '\x3', '\x2', '\x2', '\x2', '\x16A', '\x16C', '\a', '\x3', '\x2', - '\x2', '\x16B', '\x16D', '\x5', '\xE', '\b', '\x2', '\x16C', '\x16B', - '\x3', '\x2', '\x2', '\x2', '\x16C', '\x16D', '\x3', '\x2', '\x2', '\x2', - '\x16D', '\x16E', '\x3', '\x2', '\x2', '\x2', '\x16E', '\x16F', '\x5', - '\x10', '\t', '\x2', '\x16F', '\r', '\x3', '\x2', '\x2', '\x2', '\x170', - '\x171', '\t', '\x2', '\x2', '\x2', '\x171', '\xF', '\x3', '\x2', '\x2', - '\x2', '\x172', '\x177', '\x5', '\x12', '\n', '\x2', '\x173', '\x174', - '\a', '\x83', '\x2', '\x2', '\x174', '\x176', '\x5', '\x12', '\n', '\x2', - '\x175', '\x173', '\x3', '\x2', '\x2', '\x2', '\x176', '\x179', '\x3', - '\x2', '\x2', '\x2', '\x177', '\x175', '\x3', '\x2', '\x2', '\x2', '\x177', - '\x178', '\x3', '\x2', '\x2', '\x2', '\x178', '\x11', '\x3', '\x2', '\x2', - '\x2', '\x179', '\x177', '\x3', '\x2', '\x2', '\x2', '\x17A', '\x17B', - '\x5', '\xC2', '\x62', '\x2', '\x17B', '\x13', '\x3', '\x2', '\x2', '\x2', - '\x17C', '\x17D', '\x5', '\x16', '\f', '\x2', '\x17D', '\x182', '\x5', - '\x18', '\r', '\x2', '\x17E', '\x17F', '\a', '\x84', '\x2', '\x2', '\x17F', - '\x181', '\x5', '\x18', '\r', '\x2', '\x180', '\x17E', '\x3', '\x2', '\x2', - '\x2', '\x181', '\x184', '\x3', '\x2', '\x2', '\x2', '\x182', '\x180', - '\x3', '\x2', '\x2', '\x2', '\x182', '\x183', '\x3', '\x2', '\x2', '\x2', - '\x183', '\x15', '\x3', '\x2', '\x2', '\x2', '\x184', '\x182', '\x3', - '\x2', '\x2', '\x2', '\x185', '\x187', '\x5', '\xD0', 'i', '\x2', '\x186', - '\x185', '\x3', '\x2', '\x2', '\x2', '\x186', '\x187', '\x3', '\x2', '\x2', - '\x2', '\x187', '\x189', '\x3', '\x2', '\x2', '\x2', '\x188', '\x18A', - '\x5', '\xDA', 'n', '\x2', '\x189', '\x188', '\x3', '\x2', '\x2', '\x2', - '\x189', '\x18A', '\x3', '\x2', '\x2', '\x2', '\x18A', '\x18B', '\x3', - '\x2', '\x2', '\x2', '\x18B', '\x194', '\x5', '\x1C', '\xF', '\x2', '\x18C', - '\x18E', '\x5', '\xD0', 'i', '\x2', '\x18D', '\x18C', '\x3', '\x2', '\x2', - '\x2', '\x18D', '\x18E', '\x3', '\x2', '\x2', '\x2', '\x18E', '\x190', - '\x3', '\x2', '\x2', '\x2', '\x18F', '\x191', '\x5', '\xDA', 'n', '\x2', - '\x190', '\x18F', '\x3', '\x2', '\x2', '\x2', '\x190', '\x191', '\x3', - '\x2', '\x2', '\x2', '\x191', '\x192', '\x3', '\x2', '\x2', '\x2', '\x192', - '\x194', '\x5', '\x1E', '\x10', '\x2', '\x193', '\x186', '\x3', '\x2', - '\x2', '\x2', '\x193', '\x18D', '\x3', '\x2', '\x2', '\x2', '\x194', '\x17', - '\x3', '\x2', '\x2', '\x2', '\x195', '\x196', '\x5', '\x1A', '\xE', '\x2', - '\x196', '\x198', '\x5', '\xF2', 'z', '\x2', '\x197', '\x199', '\x5', - ' ', '\x11', '\x2', '\x198', '\x197', '\x3', '\x2', '\x2', '\x2', '\x198', - '\x199', '\x3', '\x2', '\x2', '\x2', '\x199', '\x1A0', '\x3', '\x2', '\x2', - '\x2', '\x19A', '\x19B', '\x5', '\x1A', '\xE', '\x2', '\x19B', '\x19D', - '\x5', '\xF2', 'z', '\x2', '\x19C', '\x19E', '\x5', '\xB8', ']', '\x2', - '\x19D', '\x19C', '\x3', '\x2', '\x2', '\x2', '\x19D', '\x19E', '\x3', - '\x2', '\x2', '\x2', '\x19E', '\x1A0', '\x3', '\x2', '\x2', '\x2', '\x19F', - '\x195', '\x3', '\x2', '\x2', '\x2', '\x19F', '\x19A', '\x3', '\x2', '\x2', - '\x2', '\x1A0', '\x19', '\x3', '\x2', '\x2', '\x2', '\x1A1', '\x1A2', - '\x5', '\xC2', '\x62', '\x2', '\x1A2', '\x1B', '\x3', '\x2', '\x2', '\x2', - '\x1A3', '\x1A4', '\a', '\t', '\x2', '\x2', '\x1A4', '\x1D', '\x3', '\x2', - '\x2', '\x2', '\x1A5', '\x1A6', '\a', '\v', '\x2', '\x2', '\x1A6', '\x1F', - '\x3', '\x2', '\x2', '\x2', '\x1A7', '\x1A8', '\a', '\x90', '\x2', '\x2', - '\x1A8', '\x1A9', '\x5', '\"', '\x12', '\x2', '\x1A9', '\x1AA', '\x5', - '$', '\x13', '\x2', '\x1AA', '\x1AB', '\a', '\x91', '\x2', '\x2', '\x1AB', - '\x1B6', '\x3', '\x2', '\x2', '\x2', '\x1AC', '\x1AD', '\a', '\x90', '\x2', - '\x2', '\x1AD', '\x1AE', '\x5', '$', '\x13', '\x2', '\x1AE', '\x1AF', - '\x5', '\"', '\x12', '\x2', '\x1AF', '\x1B0', '\a', '\x91', '\x2', '\x2', - '\x1B0', '\x1B6', '\x3', '\x2', '\x2', '\x2', '\x1B1', '\x1B2', '\a', - '\x90', '\x2', '\x2', '\x1B2', '\x1B3', '\x5', '\"', '\x12', '\x2', '\x1B3', - '\x1B4', '\a', '\x91', '\x2', '\x2', '\x1B4', '\x1B6', '\x3', '\x2', '\x2', - '\x2', '\x1B5', '\x1A7', '\x3', '\x2', '\x2', '\x2', '\x1B5', '\x1AC', - '\x3', '\x2', '\x2', '\x2', '\x1B5', '\x1B1', '\x3', '\x2', '\x2', '\x2', - '\x1B6', '!', '\x3', '\x2', '\x2', '\x2', '\x1B7', '\x1B9', '\x5', '\xD0', - 'i', '\x2', '\x1B8', '\x1B7', '\x3', '\x2', '\x2', '\x2', '\x1B8', '\x1B9', - '\x3', '\x2', '\x2', '\x2', '\x1B9', '\x1BB', '\x3', '\x2', '\x2', '\x2', - '\x1BA', '\x1BC', '\x5', '\xDE', 'p', '\x2', '\x1BB', '\x1BA', '\x3', - '\x2', '\x2', '\x2', '\x1BB', '\x1BC', '\x3', '\x2', '\x2', '\x2', '\x1BC', - '\x1BD', '\x3', '\x2', '\x2', '\x2', '\x1BD', '\x1BF', '\a', '\f', '\x2', - '\x2', '\x1BE', '\x1C0', '\x5', '\xA0', 'Q', '\x2', '\x1BF', '\x1BE', - '\x3', '\x2', '\x2', '\x2', '\x1BF', '\x1C0', '\x3', '\x2', '\x2', '\x2', - '\x1C0', '#', '\x3', '\x2', '\x2', '\x2', '\x1C1', '\x1C3', '\x5', '\xD0', - 'i', '\x2', '\x1C2', '\x1C1', '\x3', '\x2', '\x2', '\x2', '\x1C2', '\x1C3', - '\x3', '\x2', '\x2', '\x2', '\x1C3', '\x1C5', '\x3', '\x2', '\x2', '\x2', - '\x1C4', '\x1C6', '\x5', '\xDE', 'p', '\x2', '\x1C5', '\x1C4', '\x3', - '\x2', '\x2', '\x2', '\x1C5', '\x1C6', '\x3', '\x2', '\x2', '\x2', '\x1C6', - '\x1C7', '\x3', '\x2', '\x2', '\x2', '\x1C7', '\x1D4', '\a', '\r', '\x2', - '\x2', '\x1C8', '\x1CA', '\x5', '\xD0', 'i', '\x2', '\x1C9', '\x1C8', - '\x3', '\x2', '\x2', '\x2', '\x1C9', '\x1CA', '\x3', '\x2', '\x2', '\x2', - '\x1CA', '\x1CC', '\x3', '\x2', '\x2', '\x2', '\x1CB', '\x1CD', '\x5', - '\xDE', 'p', '\x2', '\x1CC', '\x1CB', '\x3', '\x2', '\x2', '\x2', '\x1CC', - '\x1CD', '\x3', '\x2', '\x2', '\x2', '\x1CD', '\x1CE', '\x3', '\x2', '\x2', - '\x2', '\x1CE', '\x1CF', '\a', '\r', '\x2', '\x2', '\x1CF', '\x1D0', '\a', - '\x8C', '\x2', '\x2', '\x1D0', '\x1D1', '\x5', '&', '\x14', '\x2', '\x1D1', - '\x1D2', '\a', '\x8D', '\x2', '\x2', '\x1D2', '\x1D4', '\x3', '\x2', '\x2', - '\x2', '\x1D3', '\x1C2', '\x3', '\x2', '\x2', '\x2', '\x1D3', '\x1C9', - '\x3', '\x2', '\x2', '\x2', '\x1D4', '%', '\x3', '\x2', '\x2', '\x2', - '\x1D5', '\x1D6', '\x5', '\xC2', '\x62', '\x2', '\x1D6', '\'', '\x3', - '\x2', '\x2', '\x2', '\x1D7', '\x1D9', '\x5', '\xD0', 'i', '\x2', '\x1D8', - '\x1D7', '\x3', '\x2', '\x2', '\x2', '\x1D8', '\x1D9', '\x3', '\x2', '\x2', - '\x2', '\x1D9', '\x1DB', '\x3', '\x2', '\x2', '\x2', '\x1DA', '\x1DC', - '\x5', '\xDC', 'o', '\x2', '\x1DB', '\x1DA', '\x3', '\x2', '\x2', '\x2', - '\x1DB', '\x1DC', '\x3', '\x2', '\x2', '\x2', '\x1DC', '\x1DD', '\x3', - '\x2', '\x2', '\x2', '\x1DD', '\x1DE', '\a', '\x4', '\x2', '\x2', '\x1DE', - '\x1E0', '\x5', '*', '\x16', '\x2', '\x1DF', '\x1E1', '\x5', '\x11A', - '\x8E', '\x2', '\x1E0', '\x1DF', '\x3', '\x2', '\x2', '\x2', '\x1E0', - '\x1E1', '\x3', '\x2', '\x2', '\x2', '\x1E1', '\x1E2', '\x3', '\x2', '\x2', - '\x2', '\x1E2', '\x1E3', '\x5', ',', '\x17', '\x2', '\x1E3', ')', '\x3', - '\x2', '\x2', '\x2', '\x1E4', '\x1E5', '\x5', '\xC2', '\x62', '\x2', '\x1E5', - '+', '\x3', '\x2', '\x2', '\x2', '\x1E6', '\x1E7', '\a', '~', '\x2', '\x2', - '\x1E7', '\x1E8', '\x5', '\xF0', 'y', '\x2', '\x1E8', '-', '\x3', '\x2', - '\x2', '\x2', '\x1E9', '\x1EB', '\x5', '\xD0', 'i', '\x2', '\x1EA', '\x1E9', - '\x3', '\x2', '\x2', '\x2', '\x1EA', '\x1EB', '\x3', '\x2', '\x2', '\x2', - '\x1EB', '\x1ED', '\x3', '\x2', '\x2', '\x2', '\x1EC', '\x1EE', '\x5', - '\xDC', 'o', '\x2', '\x1ED', '\x1EC', '\x3', '\x2', '\x2', '\x2', '\x1ED', - '\x1EE', '\x3', '\x2', '\x2', '\x2', '\x1EE', '\x1EF', '\x3', '\x2', '\x2', - '\x2', '\x1EF', '\x1F8', '\x5', '\x30', '\x19', '\x2', '\x1F0', '\x1F2', - '\x5', '\xD0', 'i', '\x2', '\x1F1', '\x1F0', '\x3', '\x2', '\x2', '\x2', - '\x1F1', '\x1F2', '\x3', '\x2', '\x2', '\x2', '\x1F2', '\x1F4', '\x3', - '\x2', '\x2', '\x2', '\x1F3', '\x1F5', '\x5', '\xDC', 'o', '\x2', '\x1F4', - '\x1F3', '\x3', '\x2', '\x2', '\x2', '\x1F4', '\x1F5', '\x3', '\x2', '\x2', - '\x2', '\x1F5', '\x1F6', '\x3', '\x2', '\x2', '\x2', '\x1F6', '\x1F8', - '\x5', '@', '!', '\x2', '\x1F7', '\x1EA', '\x3', '\x2', '\x2', '\x2', - '\x1F7', '\x1F1', '\x3', '\x2', '\x2', '\x2', '\x1F8', '/', '\x3', '\x2', - '\x2', '\x2', '\x1F9', '\x1FB', '\a', '\xE', '\x2', '\x2', '\x1FA', '\x1F9', - '\x3', '\x2', '\x2', '\x2', '\x1FA', '\x1FB', '\x3', '\x2', '\x2', '\x2', - '\x1FB', '\x1FC', '\x3', '\x2', '\x2', '\x2', '\x1FC', '\x1FD', '\a', - '\a', '\x2', '\x2', '\x1FD', '\x1FF', '\x5', '<', '\x1F', '\x2', '\x1FE', - '\x200', '\x5', '\x11A', '\x8E', '\x2', '\x1FF', '\x1FE', '\x3', '\x2', - '\x2', '\x2', '\x1FF', '\x200', '\x3', '\x2', '\x2', '\x2', '\x200', '\x202', - '\x3', '\x2', '\x2', '\x2', '\x201', '\x203', '\x5', '\xC4', '\x63', '\x2', - '\x202', '\x201', '\x3', '\x2', '\x2', '\x2', '\x202', '\x203', '\x3', - '\x2', '\x2', '\x2', '\x203', '\x205', '\x3', '\x2', '\x2', '\x2', '\x204', - '\x206', '\x5', '\x120', '\x91', '\x2', '\x205', '\x204', '\x3', '\x2', - '\x2', '\x2', '\x205', '\x206', '\x3', '\x2', '\x2', '\x2', '\x206', '\x207', - '\x3', '\x2', '\x2', '\x2', '\x207', '\x209', '\a', '\x90', '\x2', '\x2', - '\x208', '\x20A', '\x5', '\x32', '\x1A', '\x2', '\x209', '\x208', '\x3', - '\x2', '\x2', '\x2', '\x209', '\x20A', '\x3', '\x2', '\x2', '\x2', '\x20A', - '\x20B', '\x3', '\x2', '\x2', '\x2', '\x20B', '\x20C', '\a', '\x91', '\x2', - '\x2', '\x20C', '\x31', '\x3', '\x2', '\x2', '\x2', '\x20D', '\x20F', - '\x5', '\x34', '\x1B', '\x2', '\x20E', '\x210', '\x5', '\x32', '\x1A', - '\x2', '\x20F', '\x20E', '\x3', '\x2', '\x2', '\x2', '\x20F', '\x210', - '\x3', '\x2', '\x2', '\x2', '\x210', '\x33', '\x3', '\x2', '\x2', '\x2', - '\x211', '\x214', '\x5', '\n', '\x6', '\x2', '\x212', '\x214', '\x5', - '\x36', '\x1C', '\x2', '\x213', '\x211', '\x3', '\x2', '\x2', '\x2', '\x213', - '\x212', '\x3', '\x2', '\x2', '\x2', '\x214', '\x35', '\x3', '\x2', '\x2', - '\x2', '\x215', '\x217', '\x5', '\xD0', 'i', '\x2', '\x216', '\x215', - '\x3', '\x2', '\x2', '\x2', '\x216', '\x217', '\x3', '\x2', '\x2', '\x2', - '\x217', '\x219', '\x3', '\x2', '\x2', '\x2', '\x218', '\x21A', '\a', - '\xE', '\x2', '\x2', '\x219', '\x218', '\x3', '\x2', '\x2', '\x2', '\x219', - '\x21A', '\x3', '\x2', '\x2', '\x2', '\x21A', '\x21B', '\x3', '\x2', '\x2', - '\x2', '\x21B', '\x21C', '\a', '\xF', '\x2', '\x2', '\x21C', '\x21D', - '\x5', '\x38', '\x1D', '\x2', '\x21D', '\x37', '\x3', '\x2', '\x2', '\x2', - '\x21E', '\x224', '\x5', ':', '\x1E', '\x2', '\x21F', '\x220', '\x5', - ':', '\x1E', '\x2', '\x220', '\x221', '\a', '\x84', '\x2', '\x2', '\x221', - '\x222', '\x5', '\x38', '\x1D', '\x2', '\x222', '\x224', '\x3', '\x2', - '\x2', '\x2', '\x223', '\x21E', '\x3', '\x2', '\x2', '\x2', '\x223', '\x21F', - '\x3', '\x2', '\x2', '\x2', '\x224', '\x39', '\x3', '\x2', '\x2', '\x2', - '\x225', '\x227', '\x5', '>', ' ', '\x2', '\x226', '\x228', '\x5', '\xFC', - '\x7F', '\x2', '\x227', '\x226', '\x3', '\x2', '\x2', '\x2', '\x227', - '\x228', '\x3', '\x2', '\x2', '\x2', '\x228', ';', '\x3', '\x2', '\x2', - '\x2', '\x229', '\x22A', '\x5', '\xC2', '\x62', '\x2', '\x22A', '=', '\x3', - '\x2', '\x2', '\x2', '\x22B', '\x22C', '\x5', '\xC2', '\x62', '\x2', '\x22C', - '?', '\x3', '\x2', '\x2', '\x2', '\x22D', '\x22E', '\a', '\a', '\x2', - '\x2', '\x22E', '\x230', '\x5', '<', '\x1F', '\x2', '\x22F', '\x231', - '\x5', '\x11A', '\x8E', '\x2', '\x230', '\x22F', '\x3', '\x2', '\x2', - '\x2', '\x230', '\x231', '\x3', '\x2', '\x2', '\x2', '\x231', '\x232', - '\x3', '\x2', '\x2', '\x2', '\x232', '\x234', '\x5', '\xC4', '\x63', '\x2', - '\x233', '\x235', '\x5', '\x120', '\x91', '\x2', '\x234', '\x233', '\x3', - '\x2', '\x2', '\x2', '\x234', '\x235', '\x3', '\x2', '\x2', '\x2', '\x235', - '\x236', '\x3', '\x2', '\x2', '\x2', '\x236', '\x237', '\a', '\x90', '\x2', - '\x2', '\x237', '\x238', '\x5', '\x42', '\"', '\x2', '\x238', '\x239', - '\a', '\x91', '\x2', '\x2', '\x239', '\x41', '\x3', '\x2', '\x2', '\x2', - '\x23A', '\x23C', '\x5', '\x44', '#', '\x2', '\x23B', '\x23D', '\x5', - '\x42', '\"', '\x2', '\x23C', '\x23B', '\x3', '\x2', '\x2', '\x2', '\x23C', - '\x23D', '\x3', '\x2', '\x2', '\x2', '\x23D', '\x43', '\x3', '\x2', '\x2', - '\x2', '\x23E', '\x241', '\x5', '\n', '\x6', '\x2', '\x23F', '\x241', - '\x5', '\x46', '$', '\x2', '\x240', '\x23E', '\x3', '\x2', '\x2', '\x2', - '\x240', '\x23F', '\x3', '\x2', '\x2', '\x2', '\x241', '\x45', '\x3', - '\x2', '\x2', '\x2', '\x242', '\x244', '\x5', '\xD0', 'i', '\x2', '\x243', - '\x242', '\x3', '\x2', '\x2', '\x2', '\x243', '\x244', '\x3', '\x2', '\x2', - '\x2', '\x244', '\x245', '\x3', '\x2', '\x2', '\x2', '\x245', '\x246', - '\a', '\xF', '\x2', '\x2', '\x246', '\x247', '\x5', 'H', '%', '\x2', '\x247', - 'G', '\x3', '\x2', '\x2', '\x2', '\x248', '\x24E', '\x5', 'J', '&', '\x2', - '\x249', '\x24A', '\x5', 'J', '&', '\x2', '\x24A', '\x24B', '\a', '\x84', - '\x2', '\x2', '\x24B', '\x24C', '\x5', 'H', '%', '\x2', '\x24C', '\x24E', - '\x3', '\x2', '\x2', '\x2', '\x24D', '\x248', '\x3', '\x2', '\x2', '\x2', - '\x24D', '\x249', '\x3', '\x2', '\x2', '\x2', '\x24E', 'I', '\x3', '\x2', - '\x2', '\x2', '\x24F', '\x251', '\x5', '>', ' ', '\x2', '\x250', '\x252', - '\x5', 'L', '\'', '\x2', '\x251', '\x250', '\x3', '\x2', '\x2', '\x2', - '\x251', '\x252', '\x3', '\x2', '\x2', '\x2', '\x252', 'K', '\x3', '\x2', - '\x2', '\x2', '\x253', '\x254', '\a', '~', '\x2', '\x2', '\x254', '\x255', - '\x5', 'N', '(', '\x2', '\x255', 'M', '\x3', '\x2', '\x2', '\x2', '\x256', - '\x25A', '\x5', '\x112', '\x8A', '\x2', '\x257', '\x25A', '\a', 'x', '\x2', - '\x2', '\x258', '\x25A', '\x5', '\x110', '\x89', '\x2', '\x259', '\x256', - '\x3', '\x2', '\x2', '\x2', '\x259', '\x257', '\x3', '\x2', '\x2', '\x2', - '\x259', '\x258', '\x3', '\x2', '\x2', '\x2', '\x25A', 'O', '\x3', '\x2', - '\x2', '\x2', '\x25B', '\x25D', '\x5', '\xD0', 'i', '\x2', '\x25C', '\x25B', - '\x3', '\x2', '\x2', '\x2', '\x25C', '\x25D', '\x3', '\x2', '\x2', '\x2', - '\x25D', '\x25F', '\x3', '\x2', '\x2', '\x2', '\x25E', '\x260', '\x5', - '\xDC', 'o', '\x2', '\x25F', '\x25E', '\x3', '\x2', '\x2', '\x2', '\x25F', - '\x260', '\x3', '\x2', '\x2', '\x2', '\x260', '\x261', '\x3', '\x2', '\x2', - '\x2', '\x261', '\x262', '\a', '\x5', '\x2', '\x2', '\x262', '\x264', - '\x5', 'R', '*', '\x2', '\x263', '\x265', '\x5', '\x11A', '\x8E', '\x2', - '\x264', '\x263', '\x3', '\x2', '\x2', '\x2', '\x264', '\x265', '\x3', - '\x2', '\x2', '\x2', '\x265', '\x267', '\x3', '\x2', '\x2', '\x2', '\x266', - '\x268', '\x5', '\xC4', '\x63', '\x2', '\x267', '\x266', '\x3', '\x2', - '\x2', '\x2', '\x267', '\x268', '\x3', '\x2', '\x2', '\x2', '\x268', '\x26A', - '\x3', '\x2', '\x2', '\x2', '\x269', '\x26B', '\x5', '\x120', '\x91', - '\x2', '\x26A', '\x269', '\x3', '\x2', '\x2', '\x2', '\x26A', '\x26B', - '\x3', '\x2', '\x2', '\x2', '\x26B', '\x26C', '\x3', '\x2', '\x2', '\x2', - '\x26C', '\x26D', '\x5', 'T', '+', '\x2', '\x26D', 'Q', '\x3', '\x2', - '\x2', '\x2', '\x26E', '\x26F', '\x5', '\xC2', '\x62', '\x2', '\x26F', - 'S', '\x3', '\x2', '\x2', '\x2', '\x270', '\x274', '\a', '\x90', '\x2', - '\x2', '\x271', '\x273', '\x5', 'V', ',', '\x2', '\x272', '\x271', '\x3', - '\x2', '\x2', '\x2', '\x273', '\x276', '\x3', '\x2', '\x2', '\x2', '\x274', - '\x272', '\x3', '\x2', '\x2', '\x2', '\x274', '\x275', '\x3', '\x2', '\x2', - '\x2', '\x275', '\x277', '\x3', '\x2', '\x2', '\x2', '\x276', '\x274', - '\x3', '\x2', '\x2', '\x2', '\x277', '\x278', '\a', '\x91', '\x2', '\x2', - '\x278', 'U', '\x3', '\x2', '\x2', '\x2', '\x279', '\x27A', '\x5', '\n', - '\x6', '\x2', '\x27A', 'W', '\x3', '\x2', '\x2', '\x2', '\x27B', '\x27D', - '\x5', '\xD0', 'i', '\x2', '\x27C', '\x27B', '\x3', '\x2', '\x2', '\x2', - '\x27C', '\x27D', '\x3', '\x2', '\x2', '\x2', '\x27D', '\x27F', '\x3', - '\x2', '\x2', '\x2', '\x27E', '\x280', '\x5', '\xDC', 'o', '\x2', '\x27F', - '\x27E', '\x3', '\x2', '\x2', '\x2', '\x27F', '\x280', '\x3', '\x2', '\x2', - '\x2', '\x280', '\x282', '\x3', '\x2', '\x2', '\x2', '\x281', '\x283', - '\x5', '`', '\x31', '\x2', '\x282', '\x281', '\x3', '\x2', '\x2', '\x2', - '\x282', '\x283', '\x3', '\x2', '\x2', '\x2', '\x283', '\x284', '\x3', - '\x2', '\x2', '\x2', '\x284', '\x285', '\a', '\x6', '\x2', '\x2', '\x285', - '\x287', '\x5', 'Z', '.', '\x2', '\x286', '\x288', '\x5', '\x11A', '\x8E', - '\x2', '\x287', '\x286', '\x3', '\x2', '\x2', '\x2', '\x287', '\x288', - '\x3', '\x2', '\x2', '\x2', '\x288', '\x28A', '\x3', '\x2', '\x2', '\x2', - '\x289', '\x28B', '\x5', '\xC4', '\x63', '\x2', '\x28A', '\x289', '\x3', - '\x2', '\x2', '\x2', '\x28A', '\x28B', '\x3', '\x2', '\x2', '\x2', '\x28B', - '\x28D', '\x3', '\x2', '\x2', '\x2', '\x28C', '\x28E', '\x5', '\x120', - '\x91', '\x2', '\x28D', '\x28C', '\x3', '\x2', '\x2', '\x2', '\x28D', - '\x28E', '\x3', '\x2', '\x2', '\x2', '\x28E', '\x28F', '\x3', '\x2', '\x2', - '\x2', '\x28F', '\x290', '\x5', '\\', '/', '\x2', '\x290', '\x2A6', '\x3', - '\x2', '\x2', '\x2', '\x291', '\x293', '\x5', '\xD0', 'i', '\x2', '\x292', - '\x291', '\x3', '\x2', '\x2', '\x2', '\x292', '\x293', '\x3', '\x2', '\x2', - '\x2', '\x293', '\x294', '\x3', '\x2', '\x2', '\x2', '\x294', '\x296', - '\x5', '`', '\x31', '\x2', '\x295', '\x297', '\x5', '\xDC', 'o', '\x2', - '\x296', '\x295', '\x3', '\x2', '\x2', '\x2', '\x296', '\x297', '\x3', - '\x2', '\x2', '\x2', '\x297', '\x298', '\x3', '\x2', '\x2', '\x2', '\x298', - '\x299', '\a', '\x6', '\x2', '\x2', '\x299', '\x29B', '\x5', 'Z', '.', - '\x2', '\x29A', '\x29C', '\x5', '\x11A', '\x8E', '\x2', '\x29B', '\x29A', - '\x3', '\x2', '\x2', '\x2', '\x29B', '\x29C', '\x3', '\x2', '\x2', '\x2', - '\x29C', '\x29E', '\x3', '\x2', '\x2', '\x2', '\x29D', '\x29F', '\x5', - '\xC4', '\x63', '\x2', '\x29E', '\x29D', '\x3', '\x2', '\x2', '\x2', '\x29E', - '\x29F', '\x3', '\x2', '\x2', '\x2', '\x29F', '\x2A1', '\x3', '\x2', '\x2', - '\x2', '\x2A0', '\x2A2', '\x5', '\x120', '\x91', '\x2', '\x2A1', '\x2A0', - '\x3', '\x2', '\x2', '\x2', '\x2A1', '\x2A2', '\x3', '\x2', '\x2', '\x2', - '\x2A2', '\x2A3', '\x3', '\x2', '\x2', '\x2', '\x2A3', '\x2A4', '\x5', - '\\', '/', '\x2', '\x2A4', '\x2A6', '\x3', '\x2', '\x2', '\x2', '\x2A5', - '\x27C', '\x3', '\x2', '\x2', '\x2', '\x2A5', '\x292', '\x3', '\x2', '\x2', - '\x2', '\x2A6', 'Y', '\x3', '\x2', '\x2', '\x2', '\x2A7', '\x2A8', '\x5', - '\xC2', '\x62', '\x2', '\x2A8', '[', '\x3', '\x2', '\x2', '\x2', '\x2A9', - '\x2AD', '\a', '\x90', '\x2', '\x2', '\x2AA', '\x2AC', '\x5', '^', '\x30', - '\x2', '\x2AB', '\x2AA', '\x3', '\x2', '\x2', '\x2', '\x2AC', '\x2AF', - '\x3', '\x2', '\x2', '\x2', '\x2AD', '\x2AB', '\x3', '\x2', '\x2', '\x2', - '\x2AD', '\x2AE', '\x3', '\x2', '\x2', '\x2', '\x2AE', '\x2B0', '\x3', - '\x2', '\x2', '\x2', '\x2AF', '\x2AD', '\x3', '\x2', '\x2', '\x2', '\x2B0', - '\x2B1', '\a', '\x91', '\x2', '\x2', '\x2B1', ']', '\x3', '\x2', '\x2', - '\x2', '\x2B2', '\x2B3', '\x5', '\n', '\x6', '\x2', '\x2B3', '_', '\x3', - '\x2', '\x2', '\x2', '\x2B4', '\x2B5', '\a', '\x10', '\x2', '\x2', '\x2B5', - '\x61', '\x3', '\x2', '\x2', '\x2', '\x2B6', '\x2B8', '\x5', '\xD0', 'i', - '\x2', '\x2B7', '\x2B6', '\x3', '\x2', '\x2', '\x2', '\x2B7', '\x2B8', - '\x3', '\x2', '\x2', '\x2', '\x2B8', '\x2BA', '\x3', '\x2', '\x2', '\x2', - '\x2B9', '\x2BB', '\x5', '\xDC', 'o', '\x2', '\x2BA', '\x2B9', '\x3', - '\x2', '\x2', '\x2', '\x2BA', '\x2BB', '\x3', '\x2', '\x2', '\x2', '\x2BB', - '\x2BC', '\x3', '\x2', '\x2', '\x2', '\x2BC', '\x2BD', '\a', '\b', '\x2', - '\x2', '\x2BD', '\x2BF', '\x5', '\x64', '\x33', '\x2', '\x2BE', '\x2C0', - '\x5', '\xC4', '\x63', '\x2', '\x2BF', '\x2BE', '\x3', '\x2', '\x2', '\x2', - '\x2BF', '\x2C0', '\x3', '\x2', '\x2', '\x2', '\x2C0', '\x2C1', '\x3', - '\x2', '\x2', '\x2', '\x2C1', '\x2C2', '\x5', '\x66', '\x34', '\x2', '\x2C2', - '\x63', '\x3', '\x2', '\x2', '\x2', '\x2C3', '\x2C4', '\x5', '\xC2', '\x62', - '\x2', '\x2C4', '\x65', '\x3', '\x2', '\x2', '\x2', '\x2C5', '\x2C9', - '\a', '\x90', '\x2', '\x2', '\x2C6', '\x2C8', '\x5', 'h', '\x35', '\x2', - '\x2C7', '\x2C6', '\x3', '\x2', '\x2', '\x2', '\x2C8', '\x2CB', '\x3', - '\x2', '\x2', '\x2', '\x2C9', '\x2C7', '\x3', '\x2', '\x2', '\x2', '\x2C9', - '\x2CA', '\x3', '\x2', '\x2', '\x2', '\x2CA', '\x2CC', '\x3', '\x2', '\x2', - '\x2', '\x2CB', '\x2C9', '\x3', '\x2', '\x2', '\x2', '\x2CC', '\x2CD', - '\a', '\x91', '\x2', '\x2', '\x2CD', 'g', '\x3', '\x2', '\x2', '\x2', - '\x2CE', '\x2CF', '\x5', 'j', '\x36', '\x2', '\x2CF', 'i', '\x3', '\x2', - '\x2', '\x2', '\x2D0', '\x2D7', '\x5', '\x14', '\v', '\x2', '\x2D1', '\x2D7', - '\x5', '\x94', 'K', '\x2', '\x2D2', '\x2D7', '\x5', '\xA8', 'U', '\x2', - '\x2D3', '\x2D7', '\x5', '\x8C', 'G', '\x2', '\x2D4', '\x2D7', '\x5', - '\x92', 'J', '\x2', '\x2D5', '\x2D7', '\x5', '(', '\x15', '\x2', '\x2D6', - '\x2D0', '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D1', '\x3', '\x2', '\x2', - '\x2', '\x2D6', '\x2D2', '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D3', - '\x3', '\x2', '\x2', '\x2', '\x2D6', '\x2D4', '\x3', '\x2', '\x2', '\x2', - '\x2D6', '\x2D5', '\x3', '\x2', '\x2', '\x2', '\x2D7', 'k', '\x3', '\x2', - '\x2', '\x2', '\x2D8', '\x2DC', '\x5', 'n', '\x38', '\x2', '\x2D9', '\x2DC', - '\x5', 'p', '\x39', '\x2', '\x2DA', '\x2DC', '\x5', 'r', ':', '\x2', '\x2DB', - '\x2D8', '\x3', '\x2', '\x2', '\x2', '\x2DB', '\x2D9', '\x3', '\x2', '\x2', - '\x2', '\x2DB', '\x2DA', '\x3', '\x2', '\x2', '\x2', '\x2DC', 'm', '\x3', - '\x2', '\x2', '\x2', '\x2DD', '\x2DE', '\a', '\x11', '\x2', '\x2', '\x2DE', - '\x2DF', '\a', '\x12', '\x2', '\x2', '\x2DF', '\x2E0', '\x5', '\x13A', - '\x9E', '\x2', '\x2E0', 'o', '\x3', '\x2', '\x2', '\x2', '\x2E1', '\x2E2', - '\a', '\x13', '\x2', '\x2', '\x2E2', '\x2E3', '\a', '\x12', '\x2', '\x2', - '\x2E3', '\x2E4', '\x5', '\x13A', '\x9E', '\x2', '\x2E4', 'q', '\x3', - '\x2', '\x2', '\x2', '\x2E5', '\x2E6', '\a', '\x14', '\x2', '\x2', '\x2E6', - '\x2E7', '\a', '\x12', '\x2', '\x2', '\x2E7', '\x2E9', '\x5', '\x13A', - '\x9E', '\x2', '\x2E8', '\x2EA', '\x5', 't', ';', '\x2', '\x2E9', '\x2E8', - '\x3', '\x2', '\x2', '\x2', '\x2E9', '\x2EA', '\x3', '\x2', '\x2', '\x2', - '\x2EA', 's', '\x3', '\x2', '\x2', '\x2', '\x2EB', '\x2EC', '\a', '\x86', - '\x2', '\x2', '\x2EC', '\x2ED', '\x5', '\x84', '\x43', '\x2', '\x2ED', - 'u', '\x3', '\x2', '\x2', '\x2', '\x2EE', '\x2EF', '\a', '\x15', '\x2', - '\x2', '\x2EF', '\x2F0', '\x5', '\x84', '\x43', '\x2', '\x2F0', '\x2F4', - '\a', '\x90', '\x2', '\x2', '\x2F1', '\x2F3', '\x5', 'x', '=', '\x2', - '\x2F2', '\x2F1', '\x3', '\x2', '\x2', '\x2', '\x2F3', '\x2F6', '\x3', - '\x2', '\x2', '\x2', '\x2F4', '\x2F2', '\x3', '\x2', '\x2', '\x2', '\x2F4', - '\x2F5', '\x3', '\x2', '\x2', '\x2', '\x2F5', '\x2F7', '\x3', '\x2', '\x2', - '\x2', '\x2F6', '\x2F4', '\x3', '\x2', '\x2', '\x2', '\x2F7', '\x2F8', - '\a', '\x91', '\x2', '\x2', '\x2F8', 'w', '\x3', '\x2', '\x2', '\x2', - '\x2F9', '\x2FD', '\x5', 'z', '>', '\x2', '\x2FA', '\x2FD', '\x5', '|', - '?', '\x2', '\x2FB', '\x2FD', '\x5', '~', '@', '\x2', '\x2FC', '\x2F9', - '\x3', '\x2', '\x2', '\x2', '\x2FC', '\x2FA', '\x3', '\x2', '\x2', '\x2', - '\x2FC', '\x2FB', '\x3', '\x2', '\x2', '\x2', '\x2FD', 'y', '\x3', '\x2', - '\x2', '\x2', '\x2FE', '\x2FF', '\a', '\x16', '\x2', '\x2', '\x2FF', '\x300', - '\a', '\x86', '\x2', '\x2', '\x300', '\x305', '\x5', '\x82', '\x42', '\x2', - '\x301', '\x302', '\a', '\x17', '\x2', '\x2', '\x302', '\x303', '\a', - '\x86', '\x2', '\x2', '\x303', '\x305', '\x5', '\x82', '\x42', '\x2', - '\x304', '\x2FE', '\x3', '\x2', '\x2', '\x2', '\x304', '\x301', '\x3', - '\x2', '\x2', '\x2', '\x305', '{', '\x3', '\x2', '\x2', '\x2', '\x306', - '\x307', '\a', '\x18', '\x2', '\x2', '\x307', '\x308', '\a', '\x86', '\x2', - '\x2', '\x308', '\x309', '\x5', '\x110', '\x89', '\x2', '\x309', '}', - '\x3', '\x2', '\x2', '\x2', '\x30A', '\x30B', '\a', '\x19', '\x2', '\x2', - '\x30B', '\x30C', '\a', '\x86', '\x2', '\x2', '\x30C', '\x30D', '\x5', - '\x80', '\x41', '\x2', '\x30D', '\x7F', '\x3', '\x2', '\x2', '\x2', '\x30E', - '\x30F', '\t', '\x3', '\x2', '\x2', '\x30F', '\x81', '\x3', '\x2', '\x2', - '\x2', '\x310', '\x315', '\x5', '\x84', '\x43', '\x2', '\x311', '\x312', - '\a', '\x84', '\x2', '\x2', '\x312', '\x314', '\x5', '\x84', '\x43', '\x2', - '\x313', '\x311', '\x3', '\x2', '\x2', '\x2', '\x314', '\x317', '\x3', - '\x2', '\x2', '\x2', '\x315', '\x313', '\x3', '\x2', '\x2', '\x2', '\x315', - '\x316', '\x3', '\x2', '\x2', '\x2', '\x316', '\x83', '\x3', '\x2', '\x2', - '\x2', '\x317', '\x315', '\x3', '\x2', '\x2', '\x2', '\x318', '\x319', - '\x5', '\xC2', '\x62', '\x2', '\x319', '\x85', '\x3', '\x2', '\x2', '\x2', - '\x31A', '\x31C', '\x5', '\xD0', 'i', '\x2', '\x31B', '\x31A', '\x3', - '\x2', '\x2', '\x2', '\x31B', '\x31C', '\x3', '\x2', '\x2', '\x2', '\x31C', - '\x31E', '\x3', '\x2', '\x2', '\x2', '\x31D', '\x31F', '\x5', '\xDC', - 'o', '\x2', '\x31E', '\x31D', '\x3', '\x2', '\x2', '\x2', '\x31E', '\x31F', - '\x3', '\x2', '\x2', '\x2', '\x31F', '\x320', '\x3', '\x2', '\x2', '\x2', - '\x320', '\x321', '\a', '\x1D', '\x2', '\x2', '\x321', '\x323', '\x5', - '\xF8', '}', '\x2', '\x322', '\x324', '\x5', '\xC4', '\x63', '\x2', '\x323', - '\x322', '\x3', '\x2', '\x2', '\x2', '\x323', '\x324', '\x3', '\x2', '\x2', - '\x2', '\x324', '\x325', '\x3', '\x2', '\x2', '\x2', '\x325', '\x326', - '\x5', '\x88', '\x45', '\x2', '\x326', '\x333', '\x3', '\x2', '\x2', '\x2', - '\x327', '\x329', '\x5', '\xD0', 'i', '\x2', '\x328', '\x327', '\x3', - '\x2', '\x2', '\x2', '\x328', '\x329', '\x3', '\x2', '\x2', '\x2', '\x329', - '\x32B', '\x3', '\x2', '\x2', '\x2', '\x32A', '\x32C', '\x5', '\xDC', - 'o', '\x2', '\x32B', '\x32A', '\x3', '\x2', '\x2', '\x2', '\x32B', '\x32C', - '\x3', '\x2', '\x2', '\x2', '\x32C', '\x32D', '\x3', '\x2', '\x2', '\x2', - '\x32D', '\x32E', '\a', '\x1D', '\x2', '\x2', '\x32E', '\x32F', '\x5', - '\xF8', '}', '\x2', '\x32F', '\x330', '\x5', '\x120', '\x91', '\x2', '\x330', - '\x331', '\x5', '\x88', '\x45', '\x2', '\x331', '\x333', '\x3', '\x2', - '\x2', '\x2', '\x332', '\x31B', '\x3', '\x2', '\x2', '\x2', '\x332', '\x328', - '\x3', '\x2', '\x2', '\x2', '\x333', '\x87', '\x3', '\x2', '\x2', '\x2', - '\x334', '\x338', '\a', '\x90', '\x2', '\x2', '\x335', '\x337', '\x5', - '\x8A', '\x46', '\x2', '\x336', '\x335', '\x3', '\x2', '\x2', '\x2', '\x337', - '\x33A', '\x3', '\x2', '\x2', '\x2', '\x338', '\x336', '\x3', '\x2', '\x2', - '\x2', '\x338', '\x339', '\x3', '\x2', '\x2', '\x2', '\x339', '\x33B', - '\x3', '\x2', '\x2', '\x2', '\x33A', '\x338', '\x3', '\x2', '\x2', '\x2', - '\x33B', '\x33C', '\a', '\x91', '\x2', '\x2', '\x33C', '\x89', '\x3', - '\x2', '\x2', '\x2', '\x33D', '\x33E', '\x5', '\b', '\x5', '\x2', '\x33E', - '\x8B', '\x3', '\x2', '\x2', '\x2', '\x33F', '\x340', '\x5', '\x8E', 'H', - '\x2', '\x340', '\x341', '\x5', '\x90', 'I', '\x2', '\x341', '\x347', - '\x3', '\x2', '\x2', '\x2', '\x342', '\x343', '\x5', '\x8E', 'H', '\x2', - '\x343', '\x344', '\x5', '\x90', 'I', '\x2', '\x344', '\x345', '\x5', - ' ', '\x11', '\x2', '\x345', '\x347', '\x3', '\x2', '\x2', '\x2', '\x346', - '\x33F', '\x3', '\x2', '\x2', '\x2', '\x346', '\x342', '\x3', '\x2', '\x2', - '\x2', '\x347', '\x8D', '\x3', '\x2', '\x2', '\x2', '\x348', '\x34A', - '\x5', '\xD0', 'i', '\x2', '\x349', '\x348', '\x3', '\x2', '\x2', '\x2', - '\x349', '\x34A', '\x3', '\x2', '\x2', '\x2', '\x34A', '\x34C', '\x3', - '\x2', '\x2', '\x2', '\x34B', '\x34D', '\x5', '\xDA', 'n', '\x2', '\x34C', - '\x34B', '\x3', '\x2', '\x2', '\x2', '\x34C', '\x34D', '\x3', '\x2', '\x2', - '\x2', '\x34D', '\x34E', '\x3', '\x2', '\x2', '\x2', '\x34E', '\x34F', - '\a', '\x1E', '\x2', '\x2', '\x34F', '\x350', '\x5', '\xAE', 'X', '\x2', - '\x350', '\x8F', '\x3', '\x2', '\x2', '\x2', '\x351', '\x353', '\x5', - '\x132', '\x9A', '\x2', '\x352', '\x354', '\x5', '\xD0', 'i', '\x2', '\x353', - '\x352', '\x3', '\x2', '\x2', '\x2', '\x353', '\x354', '\x3', '\x2', '\x2', - '\x2', '\x354', '\x355', '\x3', '\x2', '\x2', '\x2', '\x355', '\x356', - '\x5', '\xF0', 'y', '\x2', '\x356', '\x91', '\x3', '\x2', '\x2', '\x2', - '\x357', '\x359', '\x5', '\xD0', 'i', '\x2', '\x358', '\x357', '\x3', - '\x2', '\x2', '\x2', '\x358', '\x359', '\x3', '\x2', '\x2', '\x2', '\x359', - '\x35B', '\x3', '\x2', '\x2', '\x2', '\x35A', '\x35C', '\x5', '\xDC', - 'o', '\x2', '\x35B', '\x35A', '\x3', '\x2', '\x2', '\x2', '\x35B', '\x35C', - '\x3', '\x2', '\x2', '\x2', '\x35C', '\x35D', '\x3', '\x2', '\x2', '\x2', - '\x35D', '\x35E', '\a', '\x1F', '\x2', '\x2', '\x35E', '\x360', '\x5', - '*', '\x16', '\x2', '\x35F', '\x361', '\x5', '\xC4', '\x63', '\x2', '\x360', - '\x35F', '\x3', '\x2', '\x2', '\x2', '\x360', '\x361', '\x3', '\x2', '\x2', - '\x2', '\x361', '\x363', '\x3', '\x2', '\x2', '\x2', '\x362', '\x364', - '\x5', ',', '\x17', '\x2', '\x363', '\x362', '\x3', '\x2', '\x2', '\x2', - '\x363', '\x364', '\x3', '\x2', '\x2', '\x2', '\x364', '\x366', '\x3', - '\x2', '\x2', '\x2', '\x365', '\x367', '\x5', '\x120', '\x91', '\x2', - '\x366', '\x365', '\x3', '\x2', '\x2', '\x2', '\x366', '\x367', '\x3', - '\x2', '\x2', '\x2', '\x367', '\x93', '\x3', '\x2', '\x2', '\x2', '\x368', - '\x369', '\x5', '\x96', 'L', '\x2', '\x369', '\x36B', '\x5', '\x98', 'M', - '\x2', '\x36A', '\x36C', '\x5', '\x11A', '\x8E', '\x2', '\x36B', '\x36A', - '\x3', '\x2', '\x2', '\x2', '\x36B', '\x36C', '\x3', '\x2', '\x2', '\x2', - '\x36C', '\x36D', '\x3', '\x2', '\x2', '\x2', '\x36D', '\x36F', '\x5', - '\x9E', 'P', '\x2', '\x36E', '\x370', '\x5', '\x120', '\x91', '\x2', '\x36F', - '\x36E', '\x3', '\x2', '\x2', '\x2', '\x36F', '\x370', '\x3', '\x2', '\x2', - '\x2', '\x370', '\x372', '\x3', '\x2', '\x2', '\x2', '\x371', '\x373', - '\x5', '\x9A', 'N', '\x2', '\x372', '\x371', '\x3', '\x2', '\x2', '\x2', - '\x372', '\x373', '\x3', '\x2', '\x2', '\x2', '\x373', '\x95', '\x3', - '\x2', '\x2', '\x2', '\x374', '\x376', '\x5', '\xD0', 'i', '\x2', '\x375', - '\x374', '\x3', '\x2', '\x2', '\x2', '\x375', '\x376', '\x3', '\x2', '\x2', - '\x2', '\x376', '\x378', '\x3', '\x2', '\x2', '\x2', '\x377', '\x379', - '\x5', '\xDA', 'n', '\x2', '\x378', '\x377', '\x3', '\x2', '\x2', '\x2', - '\x378', '\x379', '\x3', '\x2', '\x2', '\x2', '\x379', '\x37A', '\x3', - '\x2', '\x2', '\x2', '\x37A', '\x37B', '\a', '\n', '\x2', '\x2', '\x37B', - '\x97', '\x3', '\x2', '\x2', '\x2', '\x37C', '\x37F', '\x5', '\xC2', '\x62', - '\x2', '\x37D', '\x37F', '\x5', '\x9C', 'O', '\x2', '\x37E', '\x37C', - '\x3', '\x2', '\x2', '\x2', '\x37E', '\x37D', '\x3', '\x2', '\x2', '\x2', - '\x37F', '\x99', '\x3', '\x2', '\x2', '\x2', '\x380', '\x384', '\a', '\x90', - '\x2', '\x2', '\x381', '\x383', '\x5', '\xBC', '_', '\x2', '\x382', '\x381', - '\x3', '\x2', '\x2', '\x2', '\x383', '\x386', '\x3', '\x2', '\x2', '\x2', - '\x384', '\x382', '\x3', '\x2', '\x2', '\x2', '\x384', '\x385', '\x3', - '\x2', '\x2', '\x2', '\x385', '\x387', '\x3', '\x2', '\x2', '\x2', '\x386', - '\x384', '\x3', '\x2', '\x2', '\x2', '\x387', '\x388', '\a', '\x91', '\x2', - '\x2', '\x388', '\x9B', '\x3', '\x2', '\x2', '\x2', '\x389', '\x38A', - '\x5', '\x13A', '\x9E', '\x2', '\x38A', '\x9D', '\x3', '\x2', '\x2', '\x2', - '\x38B', '\x38D', '\x5', '\xAE', 'X', '\x2', '\x38C', '\x38E', '\x5', - '\xA0', 'Q', '\x2', '\x38D', '\x38C', '\x3', '\x2', '\x2', '\x2', '\x38D', - '\x38E', '\x3', '\x2', '\x2', '\x2', '\x38E', '\x390', '\x3', '\x2', '\x2', - '\x2', '\x38F', '\x391', '\x5', '\xA2', 'R', '\x2', '\x390', '\x38F', - '\x3', '\x2', '\x2', '\x2', '\x390', '\x391', '\x3', '\x2', '\x2', '\x2', - '\x391', '\x393', '\x3', '\x2', '\x2', '\x2', '\x392', '\x394', '\x5', - '\xA6', 'T', '\x2', '\x393', '\x392', '\x3', '\x2', '\x2', '\x2', '\x393', - '\x394', '\x3', '\x2', '\x2', '\x2', '\x394', '\x39E', '\x3', '\x2', '\x2', - '\x2', '\x395', '\x397', '\x5', '\xAE', 'X', '\x2', '\x396', '\x398', - '\x5', '\xA0', 'Q', '\x2', '\x397', '\x396', '\x3', '\x2', '\x2', '\x2', - '\x397', '\x398', '\x3', '\x2', '\x2', '\x2', '\x398', '\x399', '\x3', - '\x2', '\x2', '\x2', '\x399', '\x39B', '\x5', '\xA4', 'S', '\x2', '\x39A', - '\x39C', '\x5', '\xA6', 'T', '\x2', '\x39B', '\x39A', '\x3', '\x2', '\x2', - '\x2', '\x39B', '\x39C', '\x3', '\x2', '\x2', '\x2', '\x39C', '\x39E', - '\x3', '\x2', '\x2', '\x2', '\x39D', '\x38B', '\x3', '\x2', '\x2', '\x2', - '\x39D', '\x395', '\x3', '\x2', '\x2', '\x2', '\x39E', '\x9F', '\x3', - '\x2', '\x2', '\x2', '\x39F', '\x3A0', '\a', ' ', '\x2', '\x2', '\x3A0', - '\xA1', '\x3', '\x2', '\x2', '\x2', '\x3A1', '\x3A2', '\a', '!', '\x2', - '\x2', '\x3A2', '\xA3', '\x3', '\x2', '\x2', '\x2', '\x3A3', '\x3A4', - '\a', '\"', '\x2', '\x2', '\x3A4', '\xA5', '\x3', '\x2', '\x2', '\x2', - '\x3A5', '\x3A7', '\x5', '\x132', '\x9A', '\x2', '\x3A6', '\x3A8', '\x5', - '\xD0', 'i', '\x2', '\x3A7', '\x3A6', '\x3', '\x2', '\x2', '\x2', '\x3A7', - '\x3A8', '\x3', '\x2', '\x2', '\x2', '\x3A8', '\x3A9', '\x3', '\x2', '\x2', - '\x2', '\x3A9', '\x3AA', '\x5', '\xF0', 'y', '\x2', '\x3AA', '\xA7', '\x3', - '\x2', '\x2', '\x2', '\x3AB', '\x3AD', '\x5', '\xAA', 'V', '\x2', '\x3AC', - '\x3AE', '\x5', '\x11A', '\x8E', '\x2', '\x3AD', '\x3AC', '\x3', '\x2', - '\x2', '\x2', '\x3AD', '\x3AE', '\x3', '\x2', '\x2', '\x2', '\x3AE', '\x3AF', - '\x3', '\x2', '\x2', '\x2', '\x3AF', '\x3B1', '\x5', '\xAE', 'X', '\x2', - '\x3B0', '\x3B2', '\x5', '\xA2', 'R', '\x2', '\x3B1', '\x3B0', '\x3', - '\x2', '\x2', '\x2', '\x3B1', '\x3B2', '\x3', '\x2', '\x2', '\x2', '\x3B2', - '\x3B4', '\x3', '\x2', '\x2', '\x2', '\x3B3', '\x3B5', '\x5', '\x120', - '\x91', '\x2', '\x3B4', '\x3B3', '\x3', '\x2', '\x2', '\x2', '\x3B4', - '\x3B5', '\x3', '\x2', '\x2', '\x2', '\x3B5', '\x3C0', '\x3', '\x2', '\x2', - '\x2', '\x3B6', '\x3B8', '\x5', '\xAA', 'V', '\x2', '\x3B7', '\x3B9', - '\x5', '\x11A', '\x8E', '\x2', '\x3B8', '\x3B7', '\x3', '\x2', '\x2', - '\x2', '\x3B8', '\x3B9', '\x3', '\x2', '\x2', '\x2', '\x3B9', '\x3BA', - '\x3', '\x2', '\x2', '\x2', '\x3BA', '\x3BB', '\x5', '\xAE', 'X', '\x2', - '\x3BB', '\x3BD', '\x5', '\xA4', 'S', '\x2', '\x3BC', '\x3BE', '\x5', - '\x120', '\x91', '\x2', '\x3BD', '\x3BC', '\x3', '\x2', '\x2', '\x2', - '\x3BD', '\x3BE', '\x3', '\x2', '\x2', '\x2', '\x3BE', '\x3C0', '\x3', - '\x2', '\x2', '\x2', '\x3BF', '\x3AB', '\x3', '\x2', '\x2', '\x2', '\x3BF', - '\x3B6', '\x3', '\x2', '\x2', '\x2', '\x3C0', '\xA9', '\x3', '\x2', '\x2', - '\x2', '\x3C1', '\x3C3', '\x5', '\xD0', 'i', '\x2', '\x3C2', '\x3C1', - '\x3', '\x2', '\x2', '\x2', '\x3C2', '\x3C3', '\x3', '\x2', '\x2', '\x2', - '\x3C3', '\x3C5', '\x3', '\x2', '\x2', '\x2', '\x3C4', '\x3C6', '\x5', - '\xDA', 'n', '\x2', '\x3C5', '\x3C4', '\x3', '\x2', '\x2', '\x2', '\x3C5', - '\x3C6', '\x3', '\x2', '\x2', '\x2', '\x3C6', '\x3C7', '\x3', '\x2', '\x2', - '\x2', '\x3C7', '\x3D9', '\a', '#', '\x2', '\x2', '\x3C8', '\x3CA', '\x5', - '\xD0', 'i', '\x2', '\x3C9', '\x3C8', '\x3', '\x2', '\x2', '\x2', '\x3C9', - '\x3CA', '\x3', '\x2', '\x2', '\x2', '\x3CA', '\x3CC', '\x3', '\x2', '\x2', - '\x2', '\x3CB', '\x3CD', '\x5', '\xDA', 'n', '\x2', '\x3CC', '\x3CB', - '\x3', '\x2', '\x2', '\x2', '\x3CC', '\x3CD', '\x3', '\x2', '\x2', '\x2', - '\x3CD', '\x3CE', '\x3', '\x2', '\x2', '\x2', '\x3CE', '\x3CF', '\a', - '#', '\x2', '\x2', '\x3CF', '\x3D9', '\a', '\x80', '\x2', '\x2', '\x3D0', - '\x3D2', '\x5', '\xD0', 'i', '\x2', '\x3D1', '\x3D0', '\x3', '\x2', '\x2', - '\x2', '\x3D1', '\x3D2', '\x3', '\x2', '\x2', '\x2', '\x3D2', '\x3D4', - '\x3', '\x2', '\x2', '\x2', '\x3D3', '\x3D5', '\x5', '\xDA', 'n', '\x2', - '\x3D4', '\x3D3', '\x3', '\x2', '\x2', '\x2', '\x3D4', '\x3D5', '\x3', - '\x2', '\x2', '\x2', '\x3D5', '\x3D6', '\x3', '\x2', '\x2', '\x2', '\x3D6', - '\x3D7', '\a', '#', '\x2', '\x2', '\x3D7', '\x3D9', '\a', '\x82', '\x2', - '\x2', '\x3D8', '\x3C2', '\x3', '\x2', '\x2', '\x2', '\x3D8', '\x3C9', - '\x3', '\x2', '\x2', '\x2', '\x3D8', '\x3D1', '\x3', '\x2', '\x2', '\x2', - '\x3D9', '\xAB', '\x3', '\x2', '\x2', '\x2', '\x3DA', '\x3DC', '\x5', - '\xD0', 'i', '\x2', '\x3DB', '\x3DA', '\x3', '\x2', '\x2', '\x2', '\x3DB', - '\x3DC', '\x3', '\x2', '\x2', '\x2', '\x3DC', '\x3DE', '\x3', '\x2', '\x2', - '\x2', '\x3DD', '\x3DF', '\x5', '\xDA', 'n', '\x2', '\x3DE', '\x3DD', - '\x3', '\x2', '\x2', '\x2', '\x3DE', '\x3DF', '\x3', '\x2', '\x2', '\x2', - '\x3DF', '\x3E0', '\x3', '\x2', '\x2', '\x2', '\x3E0', '\x3E1', '\a', - '$', '\x2', '\x2', '\x3E1', '\xAD', '\x3', '\x2', '\x2', '\x2', '\x3E2', - '\x3E3', '\a', '\x8C', '\x2', '\x2', '\x3E3', '\x3E9', '\a', '\x8D', '\x2', - '\x2', '\x3E4', '\x3E5', '\a', '\x8C', '\x2', '\x2', '\x3E5', '\x3E6', - '\x5', '\xB0', 'Y', '\x2', '\x3E6', '\x3E7', '\a', '\x8D', '\x2', '\x2', - '\x3E7', '\x3E9', '\x3', '\x2', '\x2', '\x2', '\x3E8', '\x3E2', '\x3', - '\x2', '\x2', '\x2', '\x3E8', '\x3E4', '\x3', '\x2', '\x2', '\x2', '\x3E9', - '\xAF', '\x3', '\x2', '\x2', '\x2', '\x3EA', '\x3EF', '\x5', '\xB2', 'Z', - '\x2', '\x3EB', '\x3EC', '\a', '\x84', '\x2', '\x2', '\x3EC', '\x3EE', - '\x5', '\xB2', 'Z', '\x2', '\x3ED', '\x3EB', '\x3', '\x2', '\x2', '\x2', - '\x3EE', '\x3F1', '\x3', '\x2', '\x2', '\x2', '\x3EF', '\x3ED', '\x3', - '\x2', '\x2', '\x2', '\x3EF', '\x3F0', '\x3', '\x2', '\x2', '\x2', '\x3F0', - '\xB1', '\x3', '\x2', '\x2', '\x2', '\x3F1', '\x3EF', '\x3', '\x2', '\x2', - '\x2', '\x3F2', '\x3F4', '\x5', '\xB4', '[', '\x2', '\x3F3', '\x3F2', - '\x3', '\x2', '\x2', '\x2', '\x3F3', '\x3F4', '\x3', '\x2', '\x2', '\x2', - '\x3F4', '\x3F5', '\x3', '\x2', '\x2', '\x2', '\x3F5', '\x3F6', '\x5', - '\xB6', '\\', '\x2', '\x3F6', '\x3F8', '\x5', '\xF2', 'z', '\x2', '\x3F7', - '\x3F9', '\x5', '\xB8', ']', '\x2', '\x3F8', '\x3F7', '\x3', '\x2', '\x2', - '\x2', '\x3F8', '\x3F9', '\x3', '\x2', '\x2', '\x2', '\x3F9', '\x402', - '\x3', '\x2', '\x2', '\x2', '\x3FA', '\x3FC', '\x5', '\xB4', '[', '\x2', - '\x3FB', '\x3FA', '\x3', '\x2', '\x2', '\x2', '\x3FB', '\x3FC', '\x3', - '\x2', '\x2', '\x2', '\x3FC', '\x3FD', '\x3', '\x2', '\x2', '\x2', '\x3FD', - '\x3FE', '\x5', '\xB6', '\\', '\x2', '\x3FE', '\x3FF', '\x5', '\xF2', - 'z', '\x2', '\x3FF', '\x400', '\x5', '\x134', '\x9B', '\x2', '\x400', - '\x402', '\x3', '\x2', '\x2', '\x2', '\x401', '\x3F3', '\x3', '\x2', '\x2', - '\x2', '\x401', '\x3FB', '\x3', '\x2', '\x2', '\x2', '\x402', '\xB3', - '\x3', '\x2', '\x2', '\x2', '\x403', '\x404', '\x5', '\x118', '\x8D', - '\x2', '\x404', '\xB5', '\x3', '\x2', '\x2', '\x2', '\x405', '\x406', - '\x5', '\x118', '\x8D', '\x2', '\x406', '\xB7', '\x3', '\x2', '\x2', '\x2', - '\x407', '\x409', '\a', '~', '\x2', '\x2', '\x408', '\x40A', '\x5', '\xBA', - '^', '\x2', '\x409', '\x408', '\x3', '\x2', '\x2', '\x2', '\x40A', '\x40B', - '\x3', '\x2', '\x2', '\x2', '\x40B', '\x409', '\x3', '\x2', '\x2', '\x2', - '\x40B', '\x40C', '\x3', '\x2', '\x2', '\x2', '\x40C', '\xB9', '\x3', - '\x2', '\x2', '\x2', '\x40D', '\x411', '\a', '\x8C', '\x2', '\x2', '\x40E', - '\x410', '\x5', '\xBC', '_', '\x2', '\x40F', '\x40E', '\x3', '\x2', '\x2', - '\x2', '\x410', '\x413', '\x3', '\x2', '\x2', '\x2', '\x411', '\x40F', - '\x3', '\x2', '\x2', '\x2', '\x411', '\x412', '\x3', '\x2', '\x2', '\x2', - '\x412', '\x414', '\x3', '\x2', '\x2', '\x2', '\x413', '\x411', '\x3', - '\x2', '\x2', '\x2', '\x414', '\x42A', '\a', '\x8D', '\x2', '\x2', '\x415', - '\x419', '\a', '\x8E', '\x2', '\x2', '\x416', '\x418', '\x5', '\xBC', - '_', '\x2', '\x417', '\x416', '\x3', '\x2', '\x2', '\x2', '\x418', '\x41B', - '\x3', '\x2', '\x2', '\x2', '\x419', '\x417', '\x3', '\x2', '\x2', '\x2', - '\x419', '\x41A', '\x3', '\x2', '\x2', '\x2', '\x41A', '\x41C', '\x3', - '\x2', '\x2', '\x2', '\x41B', '\x419', '\x3', '\x2', '\x2', '\x2', '\x41C', - '\x42A', '\a', '\x8F', '\x2', '\x2', '\x41D', '\x421', '\a', '\x90', '\x2', - '\x2', '\x41E', '\x420', '\x5', '\xBC', '_', '\x2', '\x41F', '\x41E', - '\x3', '\x2', '\x2', '\x2', '\x420', '\x423', '\x3', '\x2', '\x2', '\x2', - '\x421', '\x41F', '\x3', '\x2', '\x2', '\x2', '\x421', '\x422', '\x3', - '\x2', '\x2', '\x2', '\x422', '\x424', '\x3', '\x2', '\x2', '\x2', '\x423', - '\x421', '\x3', '\x2', '\x2', '\x2', '\x424', '\x42A', '\a', '\x91', '\x2', - '\x2', '\x425', '\x42A', '\x5', '\x118', '\x8D', '\x2', '\x426', '\x42A', - '\x5', '\x10C', '\x87', '\x2', '\x427', '\x42A', '\x5', '\x13A', '\x9E', - '\x2', '\x428', '\x42A', '\x5', '\xC0', '\x61', '\x2', '\x429', '\x40D', - '\x3', '\x2', '\x2', '\x2', '\x429', '\x415', '\x3', '\x2', '\x2', '\x2', - '\x429', '\x41D', '\x3', '\x2', '\x2', '\x2', '\x429', '\x425', '\x3', - '\x2', '\x2', '\x2', '\x429', '\x426', '\x3', '\x2', '\x2', '\x2', '\x429', - '\x427', '\x3', '\x2', '\x2', '\x2', '\x429', '\x428', '\x3', '\x2', '\x2', - '\x2', '\x42A', '\xBB', '\x3', '\x2', '\x2', '\x2', '\x42B', '\x42E', - '\x5', '\xBA', '^', '\x2', '\x42C', '\x42E', '\x5', '\xBE', '`', '\x2', - '\x42D', '\x42B', '\x3', '\x2', '\x2', '\x2', '\x42D', '\x42C', '\x3', - '\x2', '\x2', '\x2', '\x42E', '\xBD', '\x3', '\x2', '\x2', '\x2', '\x42F', - '\x441', '\a', '\x83', '\x2', '\x2', '\x430', '\x441', '\a', '\x84', '\x2', - '\x2', '\x431', '\x441', '\a', '\x86', '\x2', '\x2', '\x432', '\x441', - '\a', '\x87', '\x2', '\x2', '\x433', '\x441', '\a', '~', '\x2', '\x2', - '\x434', '\x441', '\a', '\x88', '\x2', '\x2', '\x435', '\x441', '\a', - '\x89', '\x2', '\x2', '\x436', '\x441', '\a', '\x8A', '\x2', '\x2', '\x437', - '\x441', '\a', '\x80', '\x2', '\x2', '\x438', '\x441', '\a', '\x8B', '\x2', - '\x2', '\x439', '\x441', '\a', '|', '\x2', '\x2', '\x43A', '\x441', '\a', - '}', '\x2', '\x2', '\x43B', '\x441', '\a', '\x7F', '\x2', '\x2', '\x43C', - '\x441', '\a', '\x82', '\x2', '\x2', '\x43D', '\x441', '\a', '\x85', '\x2', - '\x2', '\x43E', '\x441', '\a', '\x98', '\x2', '\x2', '\x43F', '\x441', - '\x5', '\x130', '\x99', '\x2', '\x440', '\x42F', '\x3', '\x2', '\x2', - '\x2', '\x440', '\x430', '\x3', '\x2', '\x2', '\x2', '\x440', '\x431', - '\x3', '\x2', '\x2', '\x2', '\x440', '\x432', '\x3', '\x2', '\x2', '\x2', - '\x440', '\x433', '\x3', '\x2', '\x2', '\x2', '\x440', '\x434', '\x3', - '\x2', '\x2', '\x2', '\x440', '\x435', '\x3', '\x2', '\x2', '\x2', '\x440', - '\x436', '\x3', '\x2', '\x2', '\x2', '\x440', '\x437', '\x3', '\x2', '\x2', - '\x2', '\x440', '\x438', '\x3', '\x2', '\x2', '\x2', '\x440', '\x439', - '\x3', '\x2', '\x2', '\x2', '\x440', '\x43A', '\x3', '\x2', '\x2', '\x2', - '\x440', '\x43B', '\x3', '\x2', '\x2', '\x2', '\x440', '\x43C', '\x3', - '\x2', '\x2', '\x2', '\x440', '\x43D', '\x3', '\x2', '\x2', '\x2', '\x440', - '\x43E', '\x3', '\x2', '\x2', '\x2', '\x440', '\x43F', '\x3', '\x2', '\x2', - '\x2', '\x441', '\x444', '\x3', '\x2', '\x2', '\x2', '\x442', '\x444', - '\x5', '\x132', '\x9A', '\x2', '\x443', '\x440', '\x3', '\x2', '\x2', - '\x2', '\x443', '\x442', '\x3', '\x2', '\x2', '\x2', '\x444', '\xBF', - '\x3', '\x2', '\x2', '\x2', '\x445', '\x446', '\a', '\x83', '\x2', '\x2', - '\x446', '\x447', '\x5', '\xC2', '\x62', '\x2', '\x447', '\xC1', '\x3', - '\x2', '\x2', '\x2', '\x448', '\x44B', '\a', 'y', '\x2', '\x2', '\x449', - '\x44B', '\x5', '\x136', '\x9C', '\x2', '\x44A', '\x448', '\x3', '\x2', - '\x2', '\x2', '\x44A', '\x449', '\x3', '\x2', '\x2', '\x2', '\x44B', '\xC3', - '\x3', '\x2', '\x2', '\x2', '\x44C', '\x44D', '\a', '\x86', '\x2', '\x2', - '\x44D', '\x44E', '\x5', '\xC8', '\x65', '\x2', '\x44E', '\x44F', '\a', - '\x84', '\x2', '\x2', '\x44F', '\x450', '\x5', '\xC6', '\x64', '\x2', - '\x450', '\x456', '\x3', '\x2', '\x2', '\x2', '\x451', '\x452', '\a', - '\x86', '\x2', '\x2', '\x452', '\x456', '\x5', '\xC8', '\x65', '\x2', - '\x453', '\x454', '\a', '\x86', '\x2', '\x2', '\x454', '\x456', '\x5', - '\xC6', '\x64', '\x2', '\x455', '\x44C', '\x3', '\x2', '\x2', '\x2', '\x455', - '\x451', '\x3', '\x2', '\x2', '\x2', '\x455', '\x453', '\x3', '\x2', '\x2', - '\x2', '\x456', '\xC5', '\x3', '\x2', '\x2', '\x2', '\x457', '\x45D', - '\x5', '\xF8', '}', '\x2', '\x458', '\x459', '\x5', '\xF8', '}', '\x2', - '\x459', '\x45A', '\a', '\x84', '\x2', '\x2', '\x45A', '\x45B', '\x5', - '\xC6', '\x64', '\x2', '\x45B', '\x45D', '\x3', '\x2', '\x2', '\x2', '\x45C', - '\x457', '\x3', '\x2', '\x2', '\x2', '\x45C', '\x458', '\x3', '\x2', '\x2', - '\x2', '\x45D', '\xC7', '\x3', '\x2', '\x2', '\x2', '\x45E', '\x45F', - '\a', '\x6', '\x2', '\x2', '\x45F', '\xC9', '\x3', '\x2', '\x2', '\x2', - '\x460', '\x461', '\a', '\x88', '\x2', '\x2', '\x461', '\x463', '\x5', - '\xCC', 'g', '\x2', '\x462', '\x464', '\x5', '\xCE', 'h', '\x2', '\x463', - '\x462', '\x3', '\x2', '\x2', '\x2', '\x463', '\x464', '\x3', '\x2', '\x2', - '\x2', '\x464', '\xCB', '\x3', '\x2', '\x2', '\x2', '\x465', '\x466', - '\x5', '\xF8', '}', '\x2', '\x466', '\xCD', '\x3', '\x2', '\x2', '\x2', - '\x467', '\x468', '\a', '\x8C', '\x2', '\x2', '\x468', '\x469', '\x5', - '\xD2', 'j', '\x2', '\x469', '\x46A', '\a', '\x8D', '\x2', '\x2', '\x46A', - '\xCF', '\x3', '\x2', '\x2', '\x2', '\x46B', '\x46D', '\x5', '\xCA', '\x66', - '\x2', '\x46C', '\x46B', '\x3', '\x2', '\x2', '\x2', '\x46D', '\x46E', - '\x3', '\x2', '\x2', '\x2', '\x46E', '\x46C', '\x3', '\x2', '\x2', '\x2', - '\x46E', '\x46F', '\x3', '\x2', '\x2', '\x2', '\x46F', '\xD1', '\x3', - '\x2', '\x2', '\x2', '\x470', '\x472', '\x5', '\xD4', 'k', '\x2', '\x471', - '\x470', '\x3', '\x2', '\x2', '\x2', '\x472', '\x475', '\x3', '\x2', '\x2', - '\x2', '\x473', '\x471', '\x3', '\x2', '\x2', '\x2', '\x473', '\x474', - '\x3', '\x2', '\x2', '\x2', '\x474', '\xD3', '\x3', '\x2', '\x2', '\x2', - '\x475', '\x473', '\x3', '\x2', '\x2', '\x2', '\x476', '\x477', '\a', - '\x8C', '\x2', '\x2', '\x477', '\x478', '\x5', '\xD2', 'j', '\x2', '\x478', - '\x479', '\a', '\x8D', '\x2', '\x2', '\x479', '\x487', '\x3', '\x2', '\x2', - '\x2', '\x47A', '\x47B', '\a', '\x8E', '\x2', '\x2', '\x47B', '\x47C', - '\x5', '\xD2', 'j', '\x2', '\x47C', '\x47D', '\a', '\x8F', '\x2', '\x2', - '\x47D', '\x487', '\x3', '\x2', '\x2', '\x2', '\x47E', '\x47F', '\a', - '\x90', '\x2', '\x2', '\x47F', '\x480', '\x5', '\xD2', 'j', '\x2', '\x480', - '\x481', '\a', '\x91', '\x2', '\x2', '\x481', '\x487', '\x3', '\x2', '\x2', - '\x2', '\x482', '\x487', '\x5', '\x118', '\x8D', '\x2', '\x483', '\x487', - '\x5', '\x10C', '\x87', '\x2', '\x484', '\x487', '\x5', '\x13A', '\x9E', - '\x2', '\x485', '\x487', '\x5', '\xD6', 'l', '\x2', '\x486', '\x476', - '\x3', '\x2', '\x2', '\x2', '\x486', '\x47A', '\x3', '\x2', '\x2', '\x2', - '\x486', '\x47E', '\x3', '\x2', '\x2', '\x2', '\x486', '\x482', '\x3', - '\x2', '\x2', '\x2', '\x486', '\x483', '\x3', '\x2', '\x2', '\x2', '\x486', - '\x484', '\x3', '\x2', '\x2', '\x2', '\x486', '\x485', '\x3', '\x2', '\x2', - '\x2', '\x487', '\xD5', '\x3', '\x2', '\x2', '\x2', '\x488', '\x48B', - '\t', '\x4', '\x2', '\x2', '\x489', '\x48B', '\x5', '\x132', '\x9A', '\x2', - '\x48A', '\x488', '\x3', '\x2', '\x2', '\x2', '\x48A', '\x489', '\x3', - '\x2', '\x2', '\x2', '\x48B', '\xD7', '\x3', '\x2', '\x2', '\x2', '\x48C', - '\x4A5', '\a', '\x6', '\x2', '\x2', '\x48D', '\x4A5', '\a', '%', '\x2', - '\x2', '\x48E', '\x4A5', '\a', '&', '\x2', '\x2', '\x48F', '\x4A5', '\a', - '\x10', '\x2', '\x2', '\x490', '\x4A5', '\a', '\x14', '\x2', '\x2', '\x491', - '\x4A5', '\a', '\'', '\x2', '\x2', '\x492', '\x4A5', '\a', '(', '\x2', - '\x2', '\x493', '\x4A5', '\a', ')', '\x2', '\x2', '\x494', '\x4A5', '\a', - '\x13', '\x2', '\x2', '\x495', '\x4A5', '\a', '\x11', '\x2', '\x2', '\x496', - '\x4A5', '\a', '*', '\x2', '\x2', '\x497', '\x4A5', '\a', '+', '\x2', - '\x2', '\x498', '\x4A5', '\a', ',', '\x2', '\x2', '\x499', '\x49A', '\a', - ',', '\x2', '\x2', '\x49A', '\x49B', '\a', '\x8C', '\x2', '\x2', '\x49B', - '\x49C', '\a', '-', '\x2', '\x2', '\x49C', '\x4A5', '\a', '\x8D', '\x2', - '\x2', '\x49D', '\x49E', '\a', ',', '\x2', '\x2', '\x49E', '\x49F', '\a', - '\x8C', '\x2', '\x2', '\x49F', '\x4A0', '\a', '.', '\x2', '\x2', '\x4A0', - '\x4A5', '\a', '\x8D', '\x2', '\x2', '\x4A1', '\x4A5', '\a', '/', '\x2', - '\x2', '\x4A2', '\x4A5', '\x5', '\xDC', 'o', '\x2', '\x4A3', '\x4A5', - '\x5', '\xDE', 'p', '\x2', '\x4A4', '\x48C', '\x3', '\x2', '\x2', '\x2', - '\x4A4', '\x48D', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x48E', '\x3', - '\x2', '\x2', '\x2', '\x4A4', '\x48F', '\x3', '\x2', '\x2', '\x2', '\x4A4', - '\x490', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x491', '\x3', '\x2', '\x2', - '\x2', '\x4A4', '\x492', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x493', - '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x494', '\x3', '\x2', '\x2', '\x2', - '\x4A4', '\x495', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x496', '\x3', - '\x2', '\x2', '\x2', '\x4A4', '\x497', '\x3', '\x2', '\x2', '\x2', '\x4A4', - '\x498', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x499', '\x3', '\x2', '\x2', - '\x2', '\x4A4', '\x49D', '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A1', - '\x3', '\x2', '\x2', '\x2', '\x4A4', '\x4A2', '\x3', '\x2', '\x2', '\x2', - '\x4A4', '\x4A3', '\x3', '\x2', '\x2', '\x2', '\x4A5', '\xD9', '\x3', - '\x2', '\x2', '\x2', '\x4A6', '\x4A8', '\x5', '\xD8', 'm', '\x2', '\x4A7', - '\x4A6', '\x3', '\x2', '\x2', '\x2', '\x4A8', '\x4A9', '\x3', '\x2', '\x2', - '\x2', '\x4A9', '\x4A7', '\x3', '\x2', '\x2', '\x2', '\x4A9', '\x4AA', - '\x3', '\x2', '\x2', '\x2', '\x4AA', '\xDB', '\x3', '\x2', '\x2', '\x2', - '\x4AB', '\x4C5', '\a', '\x30', '\x2', '\x2', '\x4AC', '\x4AD', '\a', - '\x30', '\x2', '\x2', '\x4AD', '\x4AE', '\a', '\x8C', '\x2', '\x2', '\x4AE', - '\x4AF', '\a', '\r', '\x2', '\x2', '\x4AF', '\x4C5', '\a', '\x8D', '\x2', - '\x2', '\x4B0', '\x4C5', '\a', '\x31', '\x2', '\x2', '\x4B1', '\x4B2', - '\a', '\x31', '\x2', '\x2', '\x4B2', '\x4B3', '\a', '\x8C', '\x2', '\x2', - '\x4B3', '\x4B4', '\a', '\r', '\x2', '\x2', '\x4B4', '\x4C5', '\a', '\x8D', - '\x2', '\x2', '\x4B5', '\x4C5', '\a', '\x32', '\x2', '\x2', '\x4B6', '\x4B7', - '\a', '\x32', '\x2', '\x2', '\x4B7', '\x4B8', '\a', '\x8C', '\x2', '\x2', - '\x4B8', '\x4B9', '\a', '\r', '\x2', '\x2', '\x4B9', '\x4C5', '\a', '\x8D', - '\x2', '\x2', '\x4BA', '\x4C5', '\a', '\x33', '\x2', '\x2', '\x4BB', '\x4BC', - '\a', '\x33', '\x2', '\x2', '\x4BC', '\x4BD', '\a', '\x8C', '\x2', '\x2', - '\x4BD', '\x4BE', '\a', '\r', '\x2', '\x2', '\x4BE', '\x4C5', '\a', '\x8D', - '\x2', '\x2', '\x4BF', '\x4C5', '\a', '\x34', '\x2', '\x2', '\x4C0', '\x4C1', - '\a', '\x34', '\x2', '\x2', '\x4C1', '\x4C2', '\a', '\x8C', '\x2', '\x2', - '\x4C2', '\x4C3', '\a', '\r', '\x2', '\x2', '\x4C3', '\x4C5', '\a', '\x8D', - '\x2', '\x2', '\x4C4', '\x4AB', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4AC', - '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4B0', '\x3', '\x2', '\x2', '\x2', - '\x4C4', '\x4B1', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4B5', '\x3', - '\x2', '\x2', '\x2', '\x4C4', '\x4B6', '\x3', '\x2', '\x2', '\x2', '\x4C4', - '\x4BA', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4BB', '\x3', '\x2', '\x2', - '\x2', '\x4C4', '\x4BF', '\x3', '\x2', '\x2', '\x2', '\x4C4', '\x4C0', - '\x3', '\x2', '\x2', '\x2', '\x4C5', '\xDD', '\x3', '\x2', '\x2', '\x2', - '\x4C6', '\x4C7', '\t', '\x5', '\x2', '\x2', '\x4C7', '\xDF', '\x3', '\x2', - '\x2', '\x2', '\x4C8', '\x4C9', '\b', 'q', '\x1', '\x2', '\x4C9', '\x4CB', - '\x5', '\xE2', 'r', '\x2', '\x4CA', '\x4CC', '\x5', '\xF2', 'z', '\x2', - '\x4CB', '\x4CA', '\x3', '\x2', '\x2', '\x2', '\x4CB', '\x4CC', '\x3', - '\x2', '\x2', '\x2', '\x4CC', '\x4D4', '\x3', '\x2', '\x2', '\x2', '\x4CD', - '\x4CF', '\x5', '\xE4', 's', '\x2', '\x4CE', '\x4D0', '\x5', '\xF2', 'z', - '\x2', '\x4CF', '\x4CE', '\x3', '\x2', '\x2', '\x2', '\x4CF', '\x4D0', - '\x3', '\x2', '\x2', '\x2', '\x4D0', '\x4D4', '\x3', '\x2', '\x2', '\x2', - '\x4D1', '\x4D2', '\a', '\x37', '\x2', '\x2', '\x4D2', '\x4D4', '\x5', - '\xF0', 'y', '\x2', '\x4D3', '\x4C8', '\x3', '\x2', '\x2', '\x2', '\x4D3', - '\x4CD', '\x3', '\x2', '\x2', '\x2', '\x4D3', '\x4D1', '\x3', '\x2', '\x2', - '\x2', '\x4D4', '\x4DA', '\x3', '\x2', '\x2', '\x2', '\x4D5', '\x4D6', - '\f', '\x3', '\x2', '\x2', '\x4D6', '\x4D7', '\a', '\x38', '\x2', '\x2', - '\x4D7', '\x4D9', '\x5', '\xF0', 'y', '\x2', '\x4D8', '\x4D5', '\x3', - '\x2', '\x2', '\x2', '\x4D9', '\x4DC', '\x3', '\x2', '\x2', '\x2', '\x4DA', - '\x4D8', '\x3', '\x2', '\x2', '\x2', '\x4DA', '\x4DB', '\x3', '\x2', '\x2', - '\x2', '\x4DB', '\xE1', '\x3', '\x2', '\x2', '\x2', '\x4DC', '\x4DA', - '\x3', '\x2', '\x2', '\x2', '\x4DD', '\x4DE', '\a', '\x8B', '\x2', '\x2', - '\x4DE', '\xE3', '\x3', '\x2', '\x2', '\x2', '\x4DF', '\x4E0', '\x5', - '\xC2', '\x62', '\x2', '\x4E0', '\xE5', '\x3', '\x2', '\x2', '\x2', '\x4E1', - '\x4E3', '\x5', '\xD0', 'i', '\x2', '\x4E2', '\x4E1', '\x3', '\x2', '\x2', - '\x2', '\x4E2', '\x4E3', '\x3', '\x2', '\x2', '\x2', '\x4E3', '\x4E4', - '\x3', '\x2', '\x2', '\x2', '\x4E4', '\x4E6', '\x5', '\xE8', 'u', '\x2', - '\x4E5', '\x4E7', '\a', '!', '\x2', '\x2', '\x4E6', '\x4E5', '\x3', '\x2', - '\x2', '\x2', '\x4E6', '\x4E7', '\x3', '\x2', '\x2', '\x2', '\x4E7', '\x4E8', - '\x3', '\x2', '\x2', '\x2', '\x4E8', '\x4E9', '\x5', '\x132', '\x9A', - '\x2', '\x4E9', '\x4EA', '\x5', '\xF0', 'y', '\x2', '\x4EA', '\x4F4', - '\x3', '\x2', '\x2', '\x2', '\x4EB', '\x4ED', '\x5', '\xD0', 'i', '\x2', - '\x4EC', '\x4EB', '\x3', '\x2', '\x2', '\x2', '\x4EC', '\x4ED', '\x3', - '\x2', '\x2', '\x2', '\x4ED', '\x4EE', '\x3', '\x2', '\x2', '\x2', '\x4EE', - '\x4EF', '\x5', '\xE8', 'u', '\x2', '\x4EF', '\x4F0', '\a', '\"', '\x2', - '\x2', '\x4F0', '\x4F1', '\x5', '\x132', '\x9A', '\x2', '\x4F1', '\x4F2', - '\x5', '\xF0', 'y', '\x2', '\x4F2', '\x4F4', '\x3', '\x2', '\x2', '\x2', - '\x4F3', '\x4E2', '\x3', '\x2', '\x2', '\x2', '\x4F3', '\x4EC', '\x3', - '\x2', '\x2', '\x2', '\x4F4', '\xE7', '\x3', '\x2', '\x2', '\x2', '\x4F5', - '\x4F6', '\a', '\x8C', '\x2', '\x2', '\x4F6', '\x4FF', '\a', '\x8D', '\x2', - '\x2', '\x4F7', '\x4F8', '\a', '\x8C', '\x2', '\x2', '\x4F8', '\x4FA', - '\x5', '\xEA', 'v', '\x2', '\x4F9', '\x4FB', '\x5', '\x134', '\x9B', '\x2', - '\x4FA', '\x4F9', '\x3', '\x2', '\x2', '\x2', '\x4FA', '\x4FB', '\x3', - '\x2', '\x2', '\x2', '\x4FB', '\x4FC', '\x3', '\x2', '\x2', '\x2', '\x4FC', - '\x4FD', '\a', '\x8D', '\x2', '\x2', '\x4FD', '\x4FF', '\x3', '\x2', '\x2', - '\x2', '\x4FE', '\x4F5', '\x3', '\x2', '\x2', '\x2', '\x4FE', '\x4F7', - '\x3', '\x2', '\x2', '\x2', '\x4FF', '\xE9', '\x3', '\x2', '\x2', '\x2', - '\x500', '\x506', '\x5', '\xEC', 'w', '\x2', '\x501', '\x502', '\x5', - '\xEC', 'w', '\x2', '\x502', '\x503', '\a', '\x84', '\x2', '\x2', '\x503', - '\x504', '\x5', '\xEA', 'v', '\x2', '\x504', '\x506', '\x3', '\x2', '\x2', - '\x2', '\x505', '\x500', '\x3', '\x2', '\x2', '\x2', '\x505', '\x501', - '\x3', '\x2', '\x2', '\x2', '\x506', '\xEB', '\x3', '\x2', '\x2', '\x2', - '\x507', '\x509', '\x5', '\xD0', 'i', '\x2', '\x508', '\x507', '\x3', - '\x2', '\x2', '\x2', '\x508', '\x509', '\x3', '\x2', '\x2', '\x2', '\x509', - '\x50B', '\x3', '\x2', '\x2', '\x2', '\x50A', '\x50C', '\x5', '\xF6', - '|', '\x2', '\x50B', '\x50A', '\x3', '\x2', '\x2', '\x2', '\x50B', '\x50C', - '\x3', '\x2', '\x2', '\x2', '\x50C', '\x50D', '\x3', '\x2', '\x2', '\x2', - '\x50D', '\x512', '\x5', '\xF0', 'y', '\x2', '\x50E', '\x50F', '\x5', - '\xEE', 'x', '\x2', '\x50F', '\x510', '\x5', '\xF2', 'z', '\x2', '\x510', - '\x512', '\x3', '\x2', '\x2', '\x2', '\x511', '\x508', '\x3', '\x2', '\x2', - '\x2', '\x511', '\x50E', '\x3', '\x2', '\x2', '\x2', '\x512', '\xED', - '\x3', '\x2', '\x2', '\x2', '\x513', '\x518', '\x5', '\x118', '\x8D', - '\x2', '\x514', '\x515', '\x5', '\x118', '\x8D', '\x2', '\x515', '\x516', - '\x5', '\x118', '\x8D', '\x2', '\x516', '\x518', '\x3', '\x2', '\x2', - '\x2', '\x517', '\x513', '\x3', '\x2', '\x2', '\x2', '\x517', '\x514', - '\x3', '\x2', '\x2', '\x2', '\x518', '\xEF', '\x3', '\x2', '\x2', '\x2', - '\x519', '\x51A', '\b', 'y', '\x1', '\x2', '\x51A', '\x529', '\x5', '\x104', - '\x83', '\x2', '\x51B', '\x529', '\x5', '\x106', '\x84', '\x2', '\x51C', - '\x529', '\x5', '\xE6', 't', '\x2', '\x51D', '\x529', '\x5', '\xF8', '}', - '\x2', '\x51E', '\x529', '\x5', '\xFC', '\x7F', '\x2', '\x51F', '\x529', - '\x5', '\x108', '\x85', '\x2', '\x520', '\x521', '\x5', '\xF4', '{', '\x2', - '\x521', '\x522', '\x5', '\xF0', 'y', '\x6', '\x522', '\x529', '\x3', - '\x2', '\x2', '\x2', '\x523', '\x529', '\a', ';', '\x2', '\x2', '\x524', - '\x529', '\a', '<', '\x2', '\x2', '\x525', '\x526', '\a', '<', '\x2', - '\x2', '\x526', '\x527', '\a', '\x83', '\x2', '\x2', '\x527', '\x529', - '\x5', '\xF8', '}', '\x2', '\x528', '\x519', '\x3', '\x2', '\x2', '\x2', - '\x528', '\x51B', '\x3', '\x2', '\x2', '\x2', '\x528', '\x51C', '\x3', - '\x2', '\x2', '\x2', '\x528', '\x51D', '\x3', '\x2', '\x2', '\x2', '\x528', - '\x51E', '\x3', '\x2', '\x2', '\x2', '\x528', '\x51F', '\x3', '\x2', '\x2', - '\x2', '\x528', '\x520', '\x3', '\x2', '\x2', '\x2', '\x528', '\x523', - '\x3', '\x2', '\x2', '\x2', '\x528', '\x524', '\x3', '\x2', '\x2', '\x2', - '\x528', '\x525', '\x3', '\x2', '\x2', '\x2', '\x529', '\x536', '\x3', - '\x2', '\x2', '\x2', '\x52A', '\x52B', '\f', '\v', '\x2', '\x2', '\x52B', - '\x535', '\a', '\x80', '\x2', '\x2', '\x52C', '\x52D', '\f', '\n', '\x2', - '\x2', '\x52D', '\x535', '\a', '\x82', '\x2', '\x2', '\x52E', '\x52F', - '\f', '\b', '\x2', '\x2', '\x52F', '\x530', '\a', '\x83', '\x2', '\x2', - '\x530', '\x535', '\a', '\x39', '\x2', '\x2', '\x531', '\x532', '\f', - '\a', '\x2', '\x2', '\x532', '\x533', '\a', '\x83', '\x2', '\x2', '\x533', - '\x535', '\a', ':', '\x2', '\x2', '\x534', '\x52A', '\x3', '\x2', '\x2', - '\x2', '\x534', '\x52C', '\x3', '\x2', '\x2', '\x2', '\x534', '\x52E', - '\x3', '\x2', '\x2', '\x2', '\x534', '\x531', '\x3', '\x2', '\x2', '\x2', - '\x535', '\x538', '\x3', '\x2', '\x2', '\x2', '\x536', '\x534', '\x3', - '\x2', '\x2', '\x2', '\x536', '\x537', '\x3', '\x2', '\x2', '\x2', '\x537', - '\xF1', '\x3', '\x2', '\x2', '\x2', '\x538', '\x536', '\x3', '\x2', '\x2', - '\x2', '\x539', '\x53B', '\a', '\x86', '\x2', '\x2', '\x53A', '\x53C', - '\x5', '\xD0', 'i', '\x2', '\x53B', '\x53A', '\x3', '\x2', '\x2', '\x2', - '\x53B', '\x53C', '\x3', '\x2', '\x2', '\x2', '\x53C', '\x53E', '\x3', - '\x2', '\x2', '\x2', '\x53D', '\x53F', '\x5', '\xF6', '|', '\x2', '\x53E', - '\x53D', '\x3', '\x2', '\x2', '\x2', '\x53E', '\x53F', '\x3', '\x2', '\x2', - '\x2', '\x53F', '\x540', '\x3', '\x2', '\x2', '\x2', '\x540', '\x541', - '\x5', '\xF0', 'y', '\x2', '\x541', '\xF3', '\x3', '\x2', '\x2', '\x2', - '\x542', '\x543', '\a', '=', '\x2', '\x2', '\x543', '\xF5', '\x3', '\x2', - '\x2', '\x2', '\x544', '\x545', '\a', '>', '\x2', '\x2', '\x545', '\xF7', - '\x3', '\x2', '\x2', '\x2', '\x546', '\x548', '\x5', '\xFA', '~', '\x2', - '\x547', '\x549', '\x5', '\x12A', '\x96', '\x2', '\x548', '\x547', '\x3', - '\x2', '\x2', '\x2', '\x548', '\x549', '\x3', '\x2', '\x2', '\x2', '\x549', - '\x54C', '\x3', '\x2', '\x2', '\x2', '\x54A', '\x54B', '\a', '\x83', '\x2', - '\x2', '\x54B', '\x54D', '\x5', '\xF8', '}', '\x2', '\x54C', '\x54A', - '\x3', '\x2', '\x2', '\x2', '\x54C', '\x54D', '\x3', '\x2', '\x2', '\x2', - '\x54D', '\xF9', '\x3', '\x2', '\x2', '\x2', '\x54E', '\x54F', '\x5', - '\xC2', '\x62', '\x2', '\x54F', '\xFB', '\x3', '\x2', '\x2', '\x2', '\x550', - '\x552', '\a', '\x8C', '\x2', '\x2', '\x551', '\x553', '\x5', '\xFE', - '\x80', '\x2', '\x552', '\x551', '\x3', '\x2', '\x2', '\x2', '\x552', - '\x553', '\x3', '\x2', '\x2', '\x2', '\x553', '\x554', '\x3', '\x2', '\x2', - '\x2', '\x554', '\x555', '\a', '\x8D', '\x2', '\x2', '\x555', '\xFD', - '\x3', '\x2', '\x2', '\x2', '\x556', '\x55C', '\x5', '\x100', '\x81', - '\x2', '\x557', '\x558', '\x5', '\x100', '\x81', '\x2', '\x558', '\x559', - '\a', '\x84', '\x2', '\x2', '\x559', '\x55A', '\x5', '\xFE', '\x80', '\x2', - '\x55A', '\x55C', '\x3', '\x2', '\x2', '\x2', '\x55B', '\x556', '\x3', - '\x2', '\x2', '\x2', '\x55B', '\x557', '\x3', '\x2', '\x2', '\x2', '\x55C', - '\xFF', '\x3', '\x2', '\x2', '\x2', '\x55D', '\x55E', '\x5', '\x102', - '\x82', '\x2', '\x55E', '\x55F', '\x5', '\xF2', 'z', '\x2', '\x55F', '\x562', - '\x3', '\x2', '\x2', '\x2', '\x560', '\x562', '\x5', '\xF0', 'y', '\x2', - '\x561', '\x55D', '\x3', '\x2', '\x2', '\x2', '\x561', '\x560', '\x3', - '\x2', '\x2', '\x2', '\x562', '\x101', '\x3', '\x2', '\x2', '\x2', '\x563', - '\x564', '\x5', '\x118', '\x8D', '\x2', '\x564', '\x103', '\x3', '\x2', - '\x2', '\x2', '\x565', '\x566', '\a', '\x8E', '\x2', '\x2', '\x566', '\x567', - '\x5', '\xF0', 'y', '\x2', '\x567', '\x568', '\a', '\x8F', '\x2', '\x2', - '\x568', '\x105', '\x3', '\x2', '\x2', '\x2', '\x569', '\x56A', '\a', - '\x8E', '\x2', '\x2', '\x56A', '\x56B', '\x5', '\xF0', 'y', '\x2', '\x56B', - '\x56C', '\a', '\x86', '\x2', '\x2', '\x56C', '\x56D', '\x5', '\xF0', - 'y', '\x2', '\x56D', '\x56E', '\a', '\x8F', '\x2', '\x2', '\x56E', '\x107', - '\x3', '\x2', '\x2', '\x2', '\x56F', '\x572', '\x5', '\x10A', '\x86', - '\x2', '\x570', '\x571', '\a', '\x7F', '\x2', '\x2', '\x571', '\x573', - '\x5', '\x10A', '\x86', '\x2', '\x572', '\x570', '\x3', '\x2', '\x2', - '\x2', '\x573', '\x574', '\x3', '\x2', '\x2', '\x2', '\x574', '\x572', - '\x3', '\x2', '\x2', '\x2', '\x574', '\x575', '\x3', '\x2', '\x2', '\x2', - '\x575', '\x109', '\x3', '\x2', '\x2', '\x2', '\x576', '\x577', '\x5', - '\xF8', '}', '\x2', '\x577', '\x10B', '\x3', '\x2', '\x2', '\x2', '\x578', - '\x57D', '\x5', '\x112', '\x8A', '\x2', '\x579', '\x57D', '\x5', '\x116', - '\x8C', '\x2', '\x57A', '\x57D', '\x5', '\x110', '\x89', '\x2', '\x57B', - '\x57D', '\x5', '\x10E', '\x88', '\x2', '\x57C', '\x578', '\x3', '\x2', - '\x2', '\x2', '\x57C', '\x579', '\x3', '\x2', '\x2', '\x2', '\x57C', '\x57A', - '\x3', '\x2', '\x2', '\x2', '\x57C', '\x57B', '\x3', '\x2', '\x2', '\x2', - '\x57D', '\x10D', '\x3', '\x2', '\x2', '\x2', '\x57E', '\x57F', '\a', - '?', '\x2', '\x2', '\x57F', '\x10F', '\x3', '\x2', '\x2', '\x2', '\x580', - '\x581', '\t', '\x6', '\x2', '\x2', '\x581', '\x111', '\x3', '\x2', '\x2', - '\x2', '\x582', '\x584', '\t', '\a', '\x2', '\x2', '\x583', '\x582', '\x3', - '\x2', '\x2', '\x2', '\x583', '\x584', '\x3', '\x2', '\x2', '\x2', '\x584', - '\x585', '\x3', '\x2', '\x2', '\x2', '\x585', '\x586', '\x5', '\x114', - '\x8B', '\x2', '\x586', '\x113', '\x3', '\x2', '\x2', '\x2', '\x587', - '\x588', '\t', '\b', '\x2', '\x2', '\x588', '\x115', '\x3', '\x2', '\x2', - '\x2', '\x589', '\x58A', '\a', 'x', '\x2', '\x2', '\x58A', '\x117', '\x3', - '\x2', '\x2', '\x2', '\x58B', '\x58E', '\a', 'y', '\x2', '\x2', '\x58C', - '\x58E', '\x5', '\x138', '\x9D', '\x2', '\x58D', '\x58B', '\x3', '\x2', - '\x2', '\x2', '\x58D', '\x58C', '\x3', '\x2', '\x2', '\x2', '\x58E', '\x119', - '\x3', '\x2', '\x2', '\x2', '\x58F', '\x590', '\a', '\x81', '\x2', '\x2', - '\x590', '\x591', '\x5', '\x11C', '\x8F', '\x2', '\x591', '\x592', '\x5', - '\x130', '\x99', '\x2', '\x592', '\x11B', '\x3', '\x2', '\x2', '\x2', - '\x593', '\x598', '\x5', '\x11E', '\x90', '\x2', '\x594', '\x595', '\a', - '\x84', '\x2', '\x2', '\x595', '\x597', '\x5', '\x11E', '\x90', '\x2', - '\x596', '\x594', '\x3', '\x2', '\x2', '\x2', '\x597', '\x59A', '\x3', - '\x2', '\x2', '\x2', '\x598', '\x596', '\x3', '\x2', '\x2', '\x2', '\x598', - '\x599', '\x3', '\x2', '\x2', '\x2', '\x599', '\x11D', '\x3', '\x2', '\x2', - '\x2', '\x59A', '\x598', '\x3', '\x2', '\x2', '\x2', '\x59B', '\x5A5', - '\x5', '\xFA', '~', '\x2', '\x59C', '\x59D', '\x5', '\xFA', '~', '\x2', - '\x59D', '\x59E', '\a', '\x86', '\x2', '\x2', '\x59E', '\x59F', '\x5', - '\xF8', '}', '\x2', '\x59F', '\x5A5', '\x3', '\x2', '\x2', '\x2', '\x5A0', - '\x5A1', '\x5', '\xFA', '~', '\x2', '\x5A1', '\x5A2', '\a', '\x86', '\x2', - '\x2', '\x5A2', '\x5A3', '\x5', '\x108', '\x85', '\x2', '\x5A3', '\x5A5', - '\x3', '\x2', '\x2', '\x2', '\x5A4', '\x59B', '\x3', '\x2', '\x2', '\x2', - '\x5A4', '\x59C', '\x3', '\x2', '\x2', '\x2', '\x5A4', '\x5A0', '\x3', - '\x2', '\x2', '\x2', '\x5A5', '\x11F', '\x3', '\x2', '\x2', '\x2', '\x5A6', - '\x5A7', '\a', '\x42', '\x2', '\x2', '\x5A7', '\x5A8', '\x5', '\x122', - '\x92', '\x2', '\x5A8', '\x121', '\x3', '\x2', '\x2', '\x2', '\x5A9', - '\x5AE', '\x5', '\x124', '\x93', '\x2', '\x5AA', '\x5AB', '\a', '\x84', - '\x2', '\x2', '\x5AB', '\x5AD', '\x5', '\x124', '\x93', '\x2', '\x5AC', - '\x5AA', '\x3', '\x2', '\x2', '\x2', '\x5AD', '\x5B0', '\x3', '\x2', '\x2', - '\x2', '\x5AE', '\x5AC', '\x3', '\x2', '\x2', '\x2', '\x5AE', '\x5AF', - '\x3', '\x2', '\x2', '\x2', '\x5AF', '\x123', '\x3', '\x2', '\x2', '\x2', - '\x5B0', '\x5AE', '\x3', '\x2', '\x2', '\x2', '\x5B1', '\x5B4', '\x5', - '\x126', '\x94', '\x2', '\x5B2', '\x5B4', '\x5', '\x128', '\x95', '\x2', - '\x5B3', '\x5B1', '\x3', '\x2', '\x2', '\x2', '\x5B3', '\x5B2', '\x3', - '\x2', '\x2', '\x2', '\x5B4', '\x125', '\x3', '\x2', '\x2', '\x2', '\x5B5', - '\x5B6', '\x5', '\xF8', '}', '\x2', '\x5B6', '\x5B7', '\a', '\x86', '\x2', - '\x2', '\x5B7', '\x5B8', '\x5', '\xF8', '}', '\x2', '\x5B8', '\x5BE', - '\x3', '\x2', '\x2', '\x2', '\x5B9', '\x5BA', '\x5', '\xF8', '}', '\x2', - '\x5BA', '\x5BB', '\a', '\x86', '\x2', '\x2', '\x5BB', '\x5BC', '\x5', - '\x108', '\x85', '\x2', '\x5BC', '\x5BE', '\x3', '\x2', '\x2', '\x2', - '\x5BD', '\x5B5', '\x3', '\x2', '\x2', '\x2', '\x5BD', '\x5B9', '\x3', - '\x2', '\x2', '\x2', '\x5BE', '\x127', '\x3', '\x2', '\x2', '\x2', '\x5BF', - '\x5C0', '\x5', '\xF8', '}', '\x2', '\x5C0', '\x5C1', '\x5', '\x13A', - '\x9E', '\x2', '\x5C1', '\x5C2', '\x5', '\xF0', 'y', '\x2', '\x5C2', '\x129', - '\x3', '\x2', '\x2', '\x2', '\x5C3', '\x5C4', '\a', '\x81', '\x2', '\x2', - '\x5C4', '\x5C5', '\x5', '\x12C', '\x97', '\x2', '\x5C5', '\x5C6', '\x5', - '\x130', '\x99', '\x2', '\x5C6', '\x12B', '\x3', '\x2', '\x2', '\x2', - '\x5C7', '\x5CC', '\x5', '\x12E', '\x98', '\x2', '\x5C8', '\x5C9', '\a', - '\x84', '\x2', '\x2', '\x5C9', '\x5CB', '\x5', '\x12E', '\x98', '\x2', - '\x5CA', '\x5C8', '\x3', '\x2', '\x2', '\x2', '\x5CB', '\x5CE', '\x3', - '\x2', '\x2', '\x2', '\x5CC', '\x5CA', '\x3', '\x2', '\x2', '\x2', '\x5CC', - '\x5CD', '\x3', '\x2', '\x2', '\x2', '\x5CD', '\x12D', '\x3', '\x2', '\x2', - '\x2', '\x5CE', '\x5CC', '\x3', '\x2', '\x2', '\x2', '\x5CF', '\x5D0', - '\x5', '\xF0', 'y', '\x2', '\x5D0', '\x12F', '\x3', '\x2', '\x2', '\x2', - '\x5D1', '\x5D2', '\a', '\x43', '\x2', '\x2', '\x5D2', '\x131', '\x3', - '\x2', '\x2', '\x2', '\x5D3', '\x5D4', '\a', '\x44', '\x2', '\x2', '\x5D4', - '\x133', '\x3', '\x2', '\x2', '\x2', '\x5D5', '\x5D6', '\a', '\x45', '\x2', - '\x2', '\x5D6', '\x135', '\x3', '\x2', '\x2', '\x2', '\x5D7', '\x5D8', - '\t', '\t', '\x2', '\x2', '\x5D8', '\x137', '\x3', '\x2', '\x2', '\x2', - '\x5D9', '\x5DA', '\t', '\n', '\x2', '\x2', '\x5DA', '\x139', '\x3', '\x2', - '\x2', '\x2', '\x5DB', '\x5DE', '\x5', '\x13C', '\x9F', '\x2', '\x5DC', - '\x5DE', '\a', '\x93', '\x2', '\x2', '\x5DD', '\x5DB', '\x3', '\x2', '\x2', - '\x2', '\x5DD', '\x5DC', '\x3', '\x2', '\x2', '\x2', '\x5DE', '\x13B', - '\x3', '\x2', '\x2', '\x2', '\x5DF', '\x600', '\a', '\x43', '\x2', '\x2', - '\x5E0', '\x5E1', '\a', '\x43', '\x2', '\x2', '\x5E1', '\x600', '\a', - '\x43', '\x2', '\x2', '\x5E2', '\x5E3', '\a', '\x43', '\x2', '\x2', '\x5E3', - '\x5E4', '\a', '\x43', '\x2', '\x2', '\x5E4', '\x600', '\a', '\x43', '\x2', - '\x2', '\x5E5', '\x5E6', '\a', '\x43', '\x2', '\x2', '\x5E6', '\x5E7', - '\a', '\x43', '\x2', '\x2', '\x5E7', '\x5E8', '\a', '\x43', '\x2', '\x2', - '\x5E8', '\x5E9', '\a', '\x43', '\x2', '\x2', '\x5E9', '\x600', '\a', - '\x43', '\x2', '\x2', '\x5EA', '\x5EB', '\a', '\x43', '\x2', '\x2', '\x5EB', - '\x5EC', '\a', '\x43', '\x2', '\x2', '\x5EC', '\x5ED', '\a', '\x43', '\x2', - '\x2', '\x5ED', '\x5EE', '\a', '\x43', '\x2', '\x2', '\x5EE', '\x5EF', - '\a', '\x43', '\x2', '\x2', '\x5EF', '\x600', '\a', '\x43', '\x2', '\x2', - '\x5F0', '\x5F1', '\a', '\x43', '\x2', '\x2', '\x5F1', '\x5F2', '\a', - '\x43', '\x2', '\x2', '\x5F2', '\x5F3', '\a', '\x43', '\x2', '\x2', '\x5F3', - '\x5F4', '\a', '\x43', '\x2', '\x2', '\x5F4', '\x5F5', '\a', '\x43', '\x2', - '\x2', '\x5F5', '\x5F6', '\a', '\x43', '\x2', '\x2', '\x5F6', '\x600', - '\a', '\x43', '\x2', '\x2', '\x5F7', '\x5F8', '\a', '\x43', '\x2', '\x2', - '\x5F8', '\x5F9', '\a', '\x43', '\x2', '\x2', '\x5F9', '\x5FA', '\a', - '\x43', '\x2', '\x2', '\x5FA', '\x5FB', '\a', '\x43', '\x2', '\x2', '\x5FB', - '\x5FC', '\a', '\x43', '\x2', '\x2', '\x5FC', '\x5FD', '\a', '\x43', '\x2', - '\x2', '\x5FD', '\x5FE', '\a', '\x43', '\x2', '\x2', '\x5FE', '\x600', - '\a', '\x43', '\x2', '\x2', '\x5FF', '\x5DF', '\x3', '\x2', '\x2', '\x2', - '\x5FF', '\x5E0', '\x3', '\x2', '\x2', '\x2', '\x5FF', '\x5E2', '\x3', - '\x2', '\x2', '\x2', '\x5FF', '\x5E5', '\x3', '\x2', '\x2', '\x2', '\x5FF', - '\x5EA', '\x3', '\x2', '\x2', '\x2', '\x5FF', '\x5F0', '\x3', '\x2', '\x2', - '\x2', '\x5FF', '\x5F7', '\x3', '\x2', '\x2', '\x2', '\x600', '\x13D', - '\x3', '\x2', '\x2', '\x2', '\xBF', '\x141', '\x147', '\x156', '\x165', - '\x168', '\x16C', '\x177', '\x182', '\x186', '\x189', '\x18D', '\x190', - '\x193', '\x198', '\x19D', '\x19F', '\x1B5', '\x1B8', '\x1BB', '\x1BF', - '\x1C2', '\x1C5', '\x1C9', '\x1CC', '\x1D3', '\x1D8', '\x1DB', '\x1E0', - '\x1EA', '\x1ED', '\x1F1', '\x1F4', '\x1F7', '\x1FA', '\x1FF', '\x202', - '\x205', '\x209', '\x20F', '\x213', '\x216', '\x219', '\x223', '\x227', - '\x230', '\x234', '\x23C', '\x240', '\x243', '\x24D', '\x251', '\x259', - '\x25C', '\x25F', '\x264', '\x267', '\x26A', '\x274', '\x27C', '\x27F', - '\x282', '\x287', '\x28A', '\x28D', '\x292', '\x296', '\x29B', '\x29E', - '\x2A1', '\x2A5', '\x2AD', '\x2B7', '\x2BA', '\x2BF', '\x2C9', '\x2D6', - '\x2DB', '\x2E9', '\x2F4', '\x2FC', '\x304', '\x315', '\x31B', '\x31E', - '\x323', '\x328', '\x32B', '\x332', '\x338', '\x346', '\x349', '\x34C', - '\x353', '\x358', '\x35B', '\x360', '\x363', '\x366', '\x36B', '\x36F', - '\x372', '\x375', '\x378', '\x37E', '\x384', '\x38D', '\x390', '\x393', - '\x397', '\x39B', '\x39D', '\x3A7', '\x3AD', '\x3B1', '\x3B4', '\x3B8', - '\x3BD', '\x3BF', '\x3C2', '\x3C5', '\x3C9', '\x3CC', '\x3D1', '\x3D4', - '\x3D8', '\x3DB', '\x3DE', '\x3E8', '\x3EF', '\x3F3', '\x3F8', '\x3FB', - '\x401', '\x40B', '\x411', '\x419', '\x421', '\x429', '\x42D', '\x440', - '\x443', '\x44A', '\x455', '\x45C', '\x463', '\x46E', '\x473', '\x486', - '\x48A', '\x4A4', '\x4A9', '\x4C4', '\x4CB', '\x4CF', '\x4D3', '\x4DA', - '\x4E2', '\x4E6', '\x4EC', '\x4F3', '\x4FA', '\x4FE', '\x505', '\x508', - '\x50B', '\x511', '\x517', '\x528', '\x534', '\x536', '\x53B', '\x53E', - '\x548', '\x54C', '\x552', '\x55B', '\x561', '\x574', '\x57C', '\x583', - '\x58D', '\x598', '\x5A4', '\x5AE', '\x5B3', '\x5BD', '\x5CC', '\x5DD', - '\x5FF', - }; - - public static readonly ATN _ATN = - new ATNDeserializer().Deserialize(_serializedATN); - - -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs b/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs deleted file mode 100644 index 8dd397dabbbe..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/IModuleLoader.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Linq; -using SwiftReflector.TypeMapping; - -namespace SwiftReflector.SwiftInterfaceReflector -{ - public interface IModuleLoader - { - bool Load(string moduleName, TypeDatabase into); - } - - // this is only useful for tests, really. - public class NoLoadLoader : IModuleLoader - { - public NoLoadLoader() - { - } - - public bool Load(string moduleName, TypeDatabase into) - { - if (moduleName == "_Concurrency") - return true; - // only returns true is the module is already loaded - return into.ModuleNames.Contains(moduleName); - } - } -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs b/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs deleted file mode 100644 index 69d54e72a7a4..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/ObjCSelectorFactory.cs +++ /dev/null @@ -1,345 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Xml.Linq; -using SyntaxDynamo; -using System.Linq; -using System.Text; - -namespace SwiftReflector.SwiftInterfaceReflector -{ - public class ObjCSelectorFactory - { - XElement funcElement; - - static string[] prepositions = new string[] { - "above", "after", "along", "alongside", "as", "at", - "before", "below", "by", "following", "for", "from", - "given", "in", "including", "inside", "into", "matching", - "of", "on", "passing", "preceding", "since", "to", - "until", "using", "via", "when", "with", "within" - }; - - static string[] pluralSuffixes = new string[] { - "s", "es", "ies" - }; - - public ObjCSelectorFactory(XElement funcElement) - { - this.funcElement = Exceptions.ThrowOnNull(funcElement, nameof(funcElement)); - } - - public string Generate() - { - // it's in an @objc attribute - var providedSelector = ProvidedObjCSelector(); - if (!String.IsNullOrEmpty(providedSelector)) - return providedSelector; - - if (IsDeInit()) - return "dealloc"; - - var argNames = GetArgumentNames(); - - var baseName = IsInit() ? "init" : - (IsProperty() ? PropertyName() : FunctionName()); - - if (IsSetter()) - { - return SetterSelector(baseName); - } - - if (IsGetter()) - { - return GetterSelector(baseName); - } - - if (IsSubscriptGetter()) - { - return "objectAtIndexedSubscript:"; - } - - if (IsSubscriptSetter()) - { - return "setObject:atIndexedSubscript:"; - } - - if (IsInit() && argNames.Count == 1 && IsObjCZeroParameterWithLongSelector()) - { - var firstName = argNames[0]; - var sb = new StringBuilder(); - sb.Append("init"); - if (!IsPreposition(FirstWord(firstName))) - sb.Append("With"); - sb.Append(CapitalizeFirstLetter(firstName)); - return sb.ToString(); - } - - // at this point, the Apple code needs to know if there are - // foreign async or foreign error conventions. - // The definition of this is opaque enough that it's not clear - // what the conditions are for this predicate, so we're going to - // pretend it doesn't exist for now. - - var asyncConvention = false; - var errorConvention = false; - - var numSelectorPieces = argNames.Count + (asyncConvention ? 1 : 0) - + (errorConvention ? 1 : 0); - - if (numSelectorPieces == 0) - return baseName; - - if (numSelectorPieces == 1 && argNames.Count == 1 && argNames[0] == "_") - return baseName; - - var argIndex = 0; - var selector = new StringBuilder(); - for (var piece = 0; piece != numSelectorPieces; ++piece) - { - if (piece > 0) - { - if (asyncConvention) - { - selector.Append("completionHandler:"); - continue; - } - - // If we have an error convention that inserts an error parameter - // here, add "error". - if (errorConvention) - { - selector.Append("error:"); - continue; - } - - // Selector pieces beyond the first are simple. - selector.Append(argNames[argIndex++]).Append('.'); - continue; - } - var firstPiece = baseName; - var scratch = new StringBuilder(); - scratch.Append(firstPiece); - if (asyncConvention) - { - // The completion handler is first; append "WithCompletionHandler". - scratch.Append("WithCompletionHandler"); - firstPiece = scratch.ToString(); - } - else if (errorConvention) - { - scratch.Append("AndReturnError"); - firstPiece = scratch.ToString(); - } - else if (argNames[argIndex] != "_" && argNames[argIndex] != "") - { - // If the first argument name doesn't start with a preposition, and the - // method name doesn't end with a preposition, add "with". - var firstName = argNames[argIndex++]; - if (!IsPreposition(FirstWord(firstName)) && - !IsPreposition(LastWord(firstPiece))) - { - scratch.Append("With"); - } - scratch.Append(CapitalizeFirstLetter(firstName)); - firstPiece = scratch.ToString(); - } - else - { - ++argIndex; - } - - selector.Append(firstPiece); - if (argNames.Count > 0) - selector.Append(':'); - } - return selector.ToString(); - } - - List GetArgumentNames() - { - var parameterList = funcElement.Descendants(SwiftInterfaceReflector.kParameterList).Last(); - var parameters = parameterList.Descendants(SwiftInterfaceReflector.kParameter).Select( - p => - { - var publicName = p.Attribute(SwiftInterfaceReflector.kPublicName)?.Value; - var privateName = p.Attribute(SwiftInterfaceReflector.kPrivateName).Value; - return String.IsNullOrEmpty(publicName) ? privateName : publicName; - }); - return parameters.ToList(); - } - - string ProvidedObjCSelector() - { - //< attributes > - // < attribute name = "objc" /> - - // - // find the first objc attribute - - var elem = funcElement.Descendants(SwiftInterfaceReflector.kAttribute) - .FirstOrDefault(el => el.Attribute(SwiftInterfaceReflector.kName)?.Value == SwiftInterfaceReflector.kObjC); - if (elem == null) - return null; - var parameters = elem.Descendants(SwiftInterfaceReflector.kAttributeParameter); - if (parameters == null) - return null; - var sb = new StringBuilder(); - foreach (var piece in parameters) - { - sb.Append(piece.Attribute(SwiftInterfaceReflector.kValue)?.Value ?? ""); - } - return sb.ToString(); - } - - string GetterSelector(string baseName) - { - return baseName; - } - - string SetterSelector(string baseName) - { - return $"set{CapitalizeFirstLetter(baseName)}:"; - } - - string CapitalizeFirstLetter(string baseName) - { - if (Char.IsLower(baseName[0])) - { - return Char.ToUpper(baseName[0]) + baseName.Substring(1); - } - return baseName; - } - - bool IsObjCZeroParameterWithLongSelector() - { - var parameterList = funcElement.Descendants(SwiftInterfaceReflector.kParameterList).Last(); - var onlyParameter = parameterList.Descendants(SwiftInterfaceReflector.kParameter).FirstOrDefault(); - if (onlyParameter == null) - return false; - return onlyParameter.Attribute(SwiftInterfaceReflector.kType)?.Value == "()"; - } - - bool IsDeInit() - { - return FunctionName() == SwiftInterfaceReflector.kDotDtor; - } - - bool IsInit() - { - return FunctionName() == SwiftInterfaceReflector.kDotCtor; - } - - bool IsProperty() - { - return funcElement.Attribute(SwiftInterfaceReflector.kIsProperty)?.Value == "true"; - } - - string PropertyName() - { - return FunctionName().Substring("get_".Length); - } - - bool IsGetter() - { - var funcName = FunctionName(); - return IsProperty() && funcName.StartsWith("get_", StringComparison.Ordinal) && - funcName != SwiftInterfaceReflector.kGetSubscript; - } - - bool IsSetter() - { - var funcName = FunctionName(); - return IsProperty() && funcName.StartsWith("set_", StringComparison.Ordinal) && - funcName != SwiftInterfaceReflector.kSetSubscript; - } - - bool IsSubscriptGetter() - { - return FunctionName() == SwiftInterfaceReflector.kGetSubscript; - } - - bool IsSubscriptSetter() - { - return FunctionName() == SwiftInterfaceReflector.kSetSubscript; - } - - static bool IsPreposition(string s) - { - return prepositions.Contains(s); - } - - static bool IsPluralSuffix(string s) - { - return pluralSuffixes.Contains(s); - } - - string FunctionName() - { - return funcElement.Attribute(SwiftInterfaceReflector.kName)?.Value; - } - - IEnumerable Words(string src) - { - if (String.IsNullOrEmpty(src)) - yield break; - var length = src.Length; - var start = 0; - - while (start < length) - { - if (src[start] == '_') - { - start++; - yield return "_"; - continue; - } - var i = start; - while (i < length && Char.IsUpper(src[i])) - i++; - if (i - start > 1) - { - var endOfNext = i; - while (endOfNext < length && Char.IsLower(src[endOfNext])) - endOfNext++; - if (i == length || IsPluralSuffix(src.Substring(i, endOfNext - i)) - && src.Substring(i, endOfNext - i).EndsWith("Is", StringComparison.Ordinal)) - { - var word = src.Substring(start, endOfNext - start); - start = endOfNext; - yield return word; - continue; - } - else - { - if (Char.IsLower(src[i])) - i--; - var word = src.Substring(start, i - start); - start = i; - yield return word; - continue; - } - } - - while (i < length && !Char.IsUpper(src[i]) && src[i] != '_') - i++; - var thisword = src.Substring(start, i - start); - start = i; - yield return thisword; - } - yield break; - } - - string FirstWord(string src) - { - return Words(src).FirstOrDefault() ?? ""; - } - - string LastWord(string src) - { - return Words(src).LastOrDefault() ?? ""; - } - } -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs b/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs deleted file mode 100644 index e438f0077e4c..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/ParseException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -namespace SwiftReflector.SwiftInterfaceReflector -{ - public class ParseException : Exception - { - public ParseException() - { - } - - public ParseException(string message) - : base(message) - { - } - - public ParseException(string message, Exception inner) - : base(message, inner) - { - } - } -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs b/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs deleted file mode 100644 index bfe3d037307e..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/SwiftInterfaceReflector.cs +++ /dev/null @@ -1,2468 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Linq; -using Antlr4.Runtime; -using Antlr4.Runtime.Misc; -using Antlr4.Runtime.Tree; -using static SwiftInterfaceParser; -using System.Text; -using SyntaxDynamo; -using SwiftReflector.TypeMapping; -using SwiftReflector.SwiftXmlReflection; -using System.Threading.Tasks; -using System.Threading; - -namespace SwiftReflector.SwiftInterfaceReflector -{ - public class SwiftInterfaceReflector : SwiftInterfaceBaseListener - { - // swift-interface-format-version: 1.0 - const string kSwiftInterfaceFormatVersion = "// swift-interface-format-version:"; - // swift-compiler-version: Apple Swift version 5.3 (swiftlang-1200.0.29.2 clang-1200.0.30.1) - const string kSwiftCompilerVersion = "// swift-compiler-version: "; - // swift-module-flags: -target x86_64-apple-macosx10.9 -enable-objc-interop -ena - const string kSwiftModuleFlags = "// swift-module-flags:"; - - internal const string kModuleName = "module-name"; - internal const string kTarget = "target"; - internal const string kIgnore = "IGNORE"; - internal const string kInheritanceKind = "inheritanceKind"; - internal const string kModule = "module"; - internal const string kFunc = "func"; - internal const string kType = "type"; - internal const string kName = "name"; - internal const string kFinal = "final"; - internal const string kPublic = "public"; - internal const string kPrivate = "private"; - internal const string kInternal = "internal"; - internal const string kOpen = "open"; - internal const string kPublicCap = "Public"; - internal const string kPrivateCap = "Private"; - internal const string kInternalCap = "Internal"; - internal const string kOpenCap = "Open"; - internal const string kFilePrivate = "fileprivate"; - internal const string kStatic = "static"; - internal const string kIsStatic = "isStatic"; - internal const string kOptional = "optional"; - internal const string kObjC = "objc"; - internal const string kExtension = "extension"; - internal const string kProtocol = "protocol"; - internal const string kClass = "class"; - internal const string kInnerClasses = "innerclasses"; - internal const string kStruct = "struct"; - internal const string kInnerStructs = "innerstructs"; - internal const string kEnum = "enum"; - internal const string kInnerEnums = "innerenums"; - internal const string kMutating = "mutating"; - internal const string kRequired = "required"; - internal const string kAssociatedTypes = "associatedtypes"; - internal const string kAssociatedType = "associatedtype"; - internal const string kDefaultType = "defaulttype"; - internal const string kConformingProtocols = "conformingprotocols"; - internal const string kConformingProtocol = "conformingprotocol"; - internal const string kMembers = "members"; - internal const string kConvenience = "convenience"; - internal const string kParameterLists = "parameterlists"; - internal const string kParameterList = "parameterlist"; - internal const string kParameter = "parameter"; - internal const string kParam = "param"; - internal const string kGenericParameters = "genericparameters"; - internal const string kWhere = "where"; - internal const string kRelationship = "relationship"; - internal const string kEquals = "equals"; - internal const string kInherits = "inherits"; - internal const string kInherit = "inherit"; - internal const string kIndex = "index"; - internal const string kGetSubscript = "get_subscript"; - internal const string kSetSubscript = "set_subscript"; - internal const string kOperator = "operator"; - internal const string kLittlePrefix = "prefix"; - internal const string kLittlePostfix = "postfix"; - internal const string kPrefix = "Prefix"; - internal const string kPostfix = "Postfix"; - internal const string kInfix = "Infix"; - internal const string kDotCtor = ".ctor"; - internal const string kDotDtor = ".dtor"; - internal const string kNewValue = "newValue"; - internal const string kOperatorKind = "operatorKind"; - internal const string kPublicName = "publicName"; - internal const string kPrivateName = "privateName"; - internal const string kKind = "kind"; - internal const string kNone = "None"; - internal const string kLittleUnknown = "unknown"; - internal const string kUnknown = "Unknown"; - internal const string kOnType = "onType"; - internal const string kAccessibility = "accessibility"; - internal const string kIsVariadic = "isVariadic"; - internal const string kTypeDeclaration = "typedeclaration"; - internal const string kIsAsync = "isAsync"; - internal const string kProperty = "property"; - internal const string kIsProperty = "isProperty"; - internal const string kStorage = "storage"; - internal const string kComputed = "Computed"; - internal const string kEscaping = "escaping"; - internal const string kAutoClosure = "autoclosure"; - internal const string kAttributes = "attributes"; - internal const string kAttribute = "attribute"; - internal const string kAttributeParameterList = "attributeparameterlist"; - internal const string kAttributeParameter = "attributeparameter"; - internal const string kLabel = "Label"; - internal const string kLiteral = "Literal"; - internal const string kSeparator = "Separator"; - internal const string kSublist = "Sublist"; - internal const string kValue = "Value"; - internal const string kObjCSelector = "objcSelector"; - internal const string kDeprecated = "deprecated"; - internal const string kUnavailable = "unavailable"; - internal const string kAvailable = "available"; - internal const string kIntroduced = "introduced"; - internal const string kObsoleted = "obsoleted"; - internal const string kElements = "elements"; - internal const string kElement = "element"; - internal const string kIntValue = "intValue"; - internal const string kRawType = "rawType"; - internal const string kRawValue = "RawValue"; - internal const string kTypeAliases = "typealiases"; - internal const string kTypeAlias = "typealias"; - internal const string kSuperclass = "superclass"; - - Stack currentElement = new Stack(); - Version interfaceVersion; - Version compilerVersion; - - List importModules = new List(); - List operators = new List(); - List> functions = new List>(); - List extensions = new List(); - Dictionary moduleFlags = new Dictionary(); - List nominalTypes = new List(); - List classes = new List(); - List associatedTypesWithConformance = new List(); - List unknownInheritance = new List(); - List typeAliasMap = new List(); - string moduleName; - TypeDatabase typeDatabase; - IModuleLoader moduleLoader; - ICharStream inputStream; - - public SwiftInterfaceReflector(TypeDatabase typeDatabase, IModuleLoader moduleLoader) - { - this.typeDatabase = typeDatabase; - this.moduleLoader = moduleLoader; - } - - public async Task ReflectAsync(string inFile, Stream outStm) - { - Exceptions.ThrowOnNull(inFile, nameof(inFile)); - Exceptions.ThrowOnNull(outStm, nameof(outStm)); - - - await Task.Run(() => - { - var xDocument = Reflect(inFile); - xDocument.Save(outStm); - currentElement.Clear(); - }); - } - - public void Reflect(string inFile, Stream outStm) - { - Exceptions.ThrowOnNull(inFile, nameof(inFile)); - Exceptions.ThrowOnNull(outStm, nameof(outStm)); - - var xDocument = Reflect(inFile); - - xDocument.Save(outStm); - currentElement.Clear(); - } - - public async Task ReflectAsync(string inFile) - { - return await Task.Run(() => - { - return Reflect(inFile); - }); - } - - public XDocument Reflect(string inFile) - { - // try { - Exceptions.ThrowOnNull(inFile, nameof(inFile)); - - if (!File.Exists(inFile)) - throw new ParseException($"Input file {inFile} not found"); - - - var fileName = Path.GetFileName(inFile); - moduleName = fileName.Split('.')[0]; - - var module = new XElement(kModule); - currentElement.Push(module); - - var desugarer = new SyntaxDesugaringParser(inFile); - var desugaredResult = desugarer.Desugar(); - inputStream = CharStreams.fromString(desugaredResult); - - var lexer = new SwiftInterfaceLexer(inputStream); - var tokenStream = new CommonTokenStream(lexer); - var parser = new SwiftInterfaceParser(tokenStream); - var walker = new ParseTreeWalker(); - walker.Walk(this, parser.swiftinterface()); - - if (currentElement.Count != 1) - throw new ParseException("At end of parse, stack should contain precisely one element"); - - if (module != currentElement.Peek()) - throw new ParseException("Expected the final element to be the initial module"); - - // LoadReferencedModules (); - - // PatchPossibleOperators (); - // PatchExtensionShortNames (); - // PatchExtensionSelfArgs (); - // PatchPossibleBadInheritance (); - // PatchAssociatedTypeConformance (); - - if (typeAliasMap.Count > 0) - { - module.Add(new XElement(kTypeAliases, typeAliasMap.ToArray())); - } - - module.Add(new XAttribute(kName, moduleName)); - SetLanguageVersion(module); - - var tlElement = new XElement("xamreflect", new XAttribute("version", "1.0"), - new XElement("modulelist", module)); - var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), tlElement); - return xDocument; - // } catch (ParseException parseException) { - // throw; - // } catch (Exception e) { - // throw new ParseException ($"Unknown error parsing {inFile}: {e.Message}", e.InnerException); - // } - } - - public override void EnterComment([NotNull] CommentContext context) - { - var commentText = context.GetText(); - InterpretCommentText(commentText); - } - - public override void EnterClass_declaration([NotNull] Class_declarationContext context) - { - var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: false); - var attributes = GatherAttributes(context.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isObjC = AttributesContains(context.attributes(), kObjC); - var accessibility = ToAccess(context.access_level_modifier()); - var isFinal = context.final_clause() != null || accessibility != kOpenCap; - var typeDecl = ToTypeDeclaration(kClass, UnTick(context.class_name().GetText()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), false); - if (generics != null) - typeDecl.Add(generics); - currentElement.Push(typeDecl); - } - - public override void ExitClass_declaration([NotNull] Class_declarationContext context) - { - var classElem = currentElement.Pop(); - var givenClassName = classElem.Attribute(kName).Value; - var actualClassName = UnTick(context.class_name().GetText()); - if (givenClassName != actualClassName) - throw new ParseException($"class name mismatch on exit declaration: expected {actualClassName} but got {givenClassName}"); - AddClassToCurrentElement(classElem); - } - - public override void EnterStruct_declaration([NotNull] Struct_declarationContext context) - { - var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); - var attributes = GatherAttributes(context.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isFinal = true; // structs are always final - var isObjC = AttributesContains(context.attributes(), kObjC); - var accessibility = ToAccess(context.access_level_modifier()); - var typeDecl = ToTypeDeclaration(kStruct, UnTick(context.struct_name().GetText()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), false); - if (generics != null) - typeDecl.Add(generics); - currentElement.Push(typeDecl); - } - - public override void ExitStruct_declaration([NotNull] Struct_declarationContext context) - { - var structElem = currentElement.Pop(); - var givenStructName = structElem.Attribute(kName).Value; - var actualStructName = UnTick(context.struct_name().GetText()); - if (givenStructName != actualStructName) - throw new ParseException($"struct name mismatch on exit declaration: expected {actualStructName} but got {givenStructName}"); - AddStructToCurrentElement(structElem); - } - - public override void EnterEnum_declaration([NotNull] Enum_declarationContext context) - { - var inheritanceClause = context.union_style_enum()?.type_inheritance_clause() ?? - context.raw_value_style_enum()?.type_inheritance_clause(); - var inheritance = GatherInheritance(inheritanceClause, forceProtocolInheritance: true, removeNonProtocols: true); - var attributes = GatherAttributes(context.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isFinal = true; // enums are always final - var isObjC = AttributesContains(context.attributes(), kObjC); - var accessibility = ToAccess(context.access_level_modifier()); - var typeDecl = ToTypeDeclaration(kEnum, EnumName(context), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - var generics = HandleGenerics(EnumGenericParameters(context), EnumGenericWhere(context), false); - if (generics != null) - typeDecl.Add(generics); - currentElement.Push(typeDecl); - } - - public override void ExitEnum_declaration([NotNull] Enum_declarationContext context) - { - var enumElem = currentElement.Pop(); - var givenEnumName = enumElem.Attribute(kName).Value; - var actualEnumName = EnumName(context); - if (givenEnumName != actualEnumName) - throw new ParseException($"enum name mismatch on exit declaration: expected {actualEnumName} but got {givenEnumName}"); - - var rawType = GetEnumRawType(context); - if (rawType != null) - enumElem.Add(rawType); - - AddEnumToCurrentElement(enumElem); - } - - static string EnumName(Enum_declarationContext context) - { - return UnTick(context.union_style_enum() != null ? - context.union_style_enum().enum_name().GetText() : - context.raw_value_style_enum().enum_name().GetText()); - } - - XAttribute GetEnumRawType(Enum_declarationContext context) - { - var alias = EnumTypeAliases(context).FirstOrDefault(ta => ta.typealias_name().GetText() == kRawValue); - if (alias == null) - return null; - var rawType = TypeText(alias.typealias_assignment().type()); - return new XAttribute(kRawType, rawType); - } - - IEnumerable EnumTypeAliases(Enum_declarationContext context) - { - if (context.union_style_enum() != null) - return UnionTypeAliases(context.union_style_enum()); - else - return RawTypeAliases(context.raw_value_style_enum()); - } - - IEnumerable UnionTypeAliases(Union_style_enumContext context) - { - var members = context.union_style_enum_members(); - while (members != null) - { - if (members.union_style_enum_member() != null) - { - var member = members.union_style_enum_member(); - if (member.nominal_declaration()?.typealias_declaration() != null) - yield return member.nominal_declaration().typealias_declaration(); - } - members = members.union_style_enum_members(); - } - yield break; - } - - IEnumerable RawTypeAliases(Raw_value_style_enumContext context) - { - var members = context.raw_value_style_enum_members(); - while (members != null) - { - if (members.raw_value_style_enum_member() != null) - { - var member = members.raw_value_style_enum_member(); - if (member.nominal_declaration()?.typealias_declaration() != null) - yield return member.nominal_declaration().typealias_declaration(); - } - members = members.raw_value_style_enum_members(); - } - yield break; - } - - public override void EnterRaw_value_style_enum_case_clause([NotNull] Raw_value_style_enum_case_clauseContext context) - { - var enumElements = new XElement(kElements); - foreach (var enumCase in RawCases(context.raw_value_style_enum_case_list())) - { - var enumElement = ToRawEnumElement(enumCase); - enumElements.Add(enumElement); - } - AddEnumNonEmptyElements(enumElements); - } - - public override void EnterUnion_style_enum_case_clause([NotNull] Union_style_enum_case_clauseContext context) - { - var enumElements = new XElement(kElements); - foreach (var enumCase in UnionCases(context.union_style_enum_case_list())) - { - var enumElement = ToUnionEnumElement(enumCase); - enumElements.Add(enumElement); - } - AddEnumNonEmptyElements(enumElements); - } - - void AddEnumNonEmptyElements(XElement enumElements) - { - if (enumElements.HasElements) - { - var currentEnum = currentElement.Peek(); - if (currentEnum.Attribute(kKind)?.Value != kEnum) - throw new ParseException("Current element needs to be an enum"); - - var existingElements = currentEnum.Element(kElements); - if (existingElements != null) - { - foreach (var elem in enumElements.Elements()) - { - existingElements.Add(elem); - } - } - else - { - currentEnum.Add(enumElements); - } - } - } - - IEnumerable RawCases(Raw_value_style_enum_case_listContext context) - { - while (context != null) - { - if (context.raw_value_style_enum_case() != null) - { - yield return context.raw_value_style_enum_case(); - } - context = context.raw_value_style_enum_case_list(); - } - yield break; - } - - XElement ToRawEnumElement(Raw_value_style_enum_caseContext context) - { - var enumElem = new XElement(kElement, new XAttribute(kName, UnTick(context.enum_case_name().GetText()))); - var value = context.raw_value_assignment(); - if (value != null) - enumElem.Add(new XAttribute(kIntValue, value.raw_value_literal().GetText())); - return enumElem; - } - - IEnumerable UnionCases(Union_style_enum_case_listContext context) - { - while (context != null) - { - if (context.union_style_enum_case() != null) - { - yield return context.union_style_enum_case(); - } - context = context.union_style_enum_case_list(); - } - yield break; - } - - XElement ToUnionEnumElement(Union_style_enum_caseContext context) - { - var enumElement = new XElement(kElement, new XAttribute(kName, UnTick(context.enum_case_name().GetText()))); - if (context.tuple_type() != null) - { - var tupString = TypeText(context.tuple_type()); - // special casing: - // the type of a union case is a tuple, but we special case - // unit tuples to be just the type of the unit - // which may be something like ((((((())))))) - // in which case we want to let it come through as is. - // a unit tuple may also have a type label which we don't care - // about so make that go away too. - - if (tupString.IndexOf(',') < 0 && tupString.IndexOf(':') < 0) - { - var pastLastOpen = tupString.LastIndexOf('(') + 1; - var firstClosed = tupString.IndexOf(')'); - if (pastLastOpen != firstClosed) - { - tupString = tupString.Substring(pastLastOpen, firstClosed - pastLastOpen); - var colonIndex = tupString.IndexOf(':'); - if (colonIndex >= 0) - { - tupString = tupString.Substring(colonIndex + 1); - } - } - } - enumElement.Add(new XAttribute(kType, tupString)); - } - return enumElement; - } - - public override void EnterProtocol_declaration([NotNull] Protocol_declarationContext context) - { - var inheritance = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); - var attributes = GatherAttributes(context.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isFinal = true; // protocols don't have final - var isObjC = AttributesContains(context.attributes(), kObjC); - var accessibility = ToAccess(context.access_level_modifier()); - var typeDecl = ToTypeDeclaration(kProtocol, UnTick(context.protocol_name().GetText()), - accessibility, isObjC, isFinal, isDeprecated, isUnavailable, inheritance, generics: null, - attributes); - currentElement.Push(typeDecl); - } - - public override void ExitProtocol_declaration([NotNull] Protocol_declarationContext context) - { - var protocolElem = currentElement.Pop(); - var givenProtocolName = protocolElem.Attribute(kName).Value; - var actualProtocolName = UnTick(context.protocol_name().GetText()); - if (givenProtocolName != actualProtocolName) - throw new ParseException($"protocol name mismatch on exit declaration: expected {actualProtocolName} but got {givenProtocolName}"); - if (currentElement.Peek().Name != kModule) - throw new ParseException($"Expected a module on the element stack but found {currentElement.Peek()}"); - currentElement.Peek().Add(protocolElem); - } - - public override void EnterProtocol_associated_type_declaration([NotNull] Protocol_associated_type_declarationContext context) - { - var conformingProtocols = GatherConformingProtocols(context.type_inheritance_clause()); - var defaultDefn = TypeText(context.typealias_assignment()?.type()); - var assocType = new XElement(kAssociatedType, - new XAttribute(kName, UnTick(context.typealias_name().GetText()))); - if (defaultDefn != null) - assocType.Add(new XAttribute(kDefaultType, UnTick(defaultDefn))); - if (conformingProtocols != null && conformingProtocols.Count > 0) - { - var confomingElem = new XElement(kConformingProtocols, conformingProtocols.ToArray()); - assocType.Add(confomingElem); - associatedTypesWithConformance.Add(assocType); - } - AddAssociatedTypeToCurrentElement(assocType); - } - - List GatherConformingProtocols(Type_inheritance_clauseContext context) - { - if (context == null) - return null; - var elems = new List(); - if (context.class_requirement() != null) - { - // not sure what to do here - // this is just the keyword 'class' - } - var inheritance = context.type_inheritance_list(); - while (inheritance != null) - { - var elem = inheritance.GetText(); - var name = TypeText(inheritance.type_identifier()); - if (name != null) - elems.Add(new XElement(kConformingProtocol, new XAttribute(kName, UnTick(name)))); - inheritance = inheritance.type_inheritance_list(); - } - return elems; - } - - static Generic_parameter_clauseContext EnumGenericParameters(Enum_declarationContext context) - { - return context.union_style_enum()?.generic_parameter_clause() ?? - context.raw_value_style_enum()?.generic_parameter_clause(); - } - - static Generic_where_clauseContext EnumGenericWhere(Enum_declarationContext context) - { - return context.union_style_enum()?.generic_where_clause() ?? - context.raw_value_style_enum()?.generic_where_clause(); - } - - public override void EnterFunction_declaration([NotNull] Function_declarationContext context) - { - var head = context.function_head(); - var signature = context.function_signature(); - - var name = UnTick(context.function_name().GetText()); - var returnType = signature.function_result() != null ? TypeText(signature.function_result().type()) : "()"; - var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); - var isStatic = IsStaticOrClass(head.declaration_modifiers()); - var hasThrows = signature.throws_clause() != null || signature.rethrows_clause() != null; - var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); - var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); - var isConvenienceInit = false; - var operatorKind = kNone; - var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); - var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); - var isProperty = false; - var attributes = GatherAttributes(head.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isAsync = signature.async_clause() != null; - var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync, attributes); - var generics = HandleGenerics(context.generic_parameter_clause(), context.generic_where_clause(), true); - if (generics != null) - functionDecl.Add(generics); - - - functions.Add(new Tuple(context, functionDecl)); - currentElement.Push(functionDecl); - } - - public override void ExitFunction_declaration([NotNull] Function_declarationContext context) - { - ExitFunctionWithName(UnTick(context.function_name().GetText())); - } - - void ExitFunctionWithName(string expectedName) - { - var functionDecl = currentElement.Pop(); - if (functionDecl.Name != kFunc) - throw new ParseException($"Expected a func node but got a {functionDecl.Name}"); - var givenName = functionDecl.Attribute(kName); - if (givenName == null) - throw new ParseException("func node doesn't have a name element"); - if (givenName.Value != expectedName) - throw new ParseException($"Expected a func node with name {expectedName} but got {givenName.Value}"); - - AddObjCSelector(functionDecl); - - AddElementToParentMembers(functionDecl); - } - - void AddObjCSelector(XElement functionDecl) - { - var selectorFactory = new ObjCSelectorFactory(functionDecl); - var selector = selectorFactory.Generate(); - if (!String.IsNullOrEmpty(selector)) - { - functionDecl.Add(new XAttribute(kObjCSelector, selector)); - } - } - - XElement PeekAsFunction() - { - var functionDecl = currentElement.Peek(); - if (functionDecl.Name != kFunc) - throw new ParseException($"Expected a func node but got a {functionDecl.Name}"); - return functionDecl; - } - - void AddElementToParentMembers(XElement elem) - { - var parent = currentElement.Peek(); - if (parent.Name == kModule) - { - parent.Add(elem); - return; - } - var memberElem = GetOrCreate(parent, kMembers); - memberElem.Add(elem); - } - - bool IsInInstance() - { - var parent = currentElement.Peek(); - return parent.Name != kModule; - } - - bool HasObjCElement(XElement elem) - { - var objcAttr = elem.Descendants() - .FirstOrDefault(el => el.Name == kAttribute && el.Attribute("name")?.Value == kObjC); - return objcAttr != null; - } - - public override void EnterInitializer_declaration([NotNull] Initializer_declarationContext context) - { - var head = context.initializer_head(); - - var name = kDotCtor; - - // may be optional, otherwise return type is the instance type - var returnType = GetInstanceName() + (head.OpQuestion() != null ? "?" : ""); - var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); - var isStatic = true; - var hasThrows = context.throws_clause() != null || context.rethrows_clause() != null; - var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); - var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); - var isConvenienceInit = ModifiersContains(head.declaration_modifiers(), kConvenience); - var operatorKind = kNone; - var attributes = GatherAttributes(head.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); - var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); - var isProperty = false; - var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, - isAsync: false, attributes); - currentElement.Push(functionDecl); - } - - public override void ExitInitializer_declaration([NotNull] Initializer_declarationContext context) - { - ExitFunctionWithName(kDotCtor); - } - - public override void EnterDeinitializer_declaration([NotNull] Deinitializer_declarationContext context) - { - var name = kDotDtor; - var returnType = "()"; - // this might have to be forced to public, otherwise deinit is always internal, which it - // decidedly is NOT. - var accessibility = kPublic; - var isStatic = false; - var hasThrows = false; - var isFinal = ModifiersContains(context.declaration_modifiers(), kFinal); - var isOptional = ModifiersContains(context.declaration_modifiers(), kOptional); - var isConvenienceInit = false; - var operatorKind = kNone; - var attributes = GatherAttributes(context.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isMutating = ModifiersContains(context.declaration_modifiers(), kMutating); - var isRequired = ModifiersContains(context.declaration_modifiers(), kRequired); - var isProperty = false; - var functionDecl = ToFunctionDeclaration(name, returnType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit, objCSelector: null, operatorKind, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - // always has two parameter lists: (instance)() - currentElement.Push(functionDecl); - var parameterLists = new XElement(kParameterLists, MakeInstanceParameterList()); - currentElement.Pop(); - - parameterLists.Add(new XElement(kParameterList, new XAttribute(kIndex, "1"))); - functionDecl.Add(parameterLists); - - currentElement.Push(functionDecl); - } - - public override void ExitDeinitializer_declaration([NotNull] Deinitializer_declarationContext context) - { - ExitFunctionWithName(kDotDtor); - } - - public override void EnterSubscript_declaration([NotNull] Subscript_declarationContext context) - { - // subscripts are...funny. - // They have one parameter list but expand out to two function declarations - // To handle this, we process the parameter list here for the getter - // If there's a setter, we make one of those too. - // Then since we're effectively done, we push a special XElement on the stack - // named IGNORE which will make the parameter list event handler exit. - // On ExitSubscript_declaration, we remove the IGNORE tag - - var head = context.subscript_head(); - var resultType = TypeText(context.subscript_result().type()); - var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); - var attributes = GatherAttributes(head.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isStatic = false; - var hasThrows = false; - var isAsync = HasAsync(context.getter_setter_keyword_block()?.getter_keyword_clause()); - var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); - var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); - var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); - var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); - var isProperty = true; - - var getParamList = MakeParameterList(head.parameter_clause().parameter_list(), 1, true); - var getFunc = ToFunctionDeclaration(kGetSubscript, resultType, accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); - - currentElement.Push(getFunc); - var getParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), getParamList); - currentElement.Pop(); - - getFunc.Add(getParamLists); - AddObjCSelector(getFunc); - - AddElementToParentMembers(getFunc); - - var setParamList = context.getter_setter_keyword_block()?.setter_keyword_clause() != null - ? MakeParameterList(head.parameter_clause().parameter_list(), 1, true, startIndex: 1) : null; - - - if (setParamList != null) - { - var index = 0; - var parmName = context.getter_setter_keyword_block().setter_keyword_clause().new_value_name()?.GetText() - ?? kNewValue; - var newValueParam = new XElement(kParameter, new XAttribute(nameof(index), index.ToString()), - new XAttribute(kType, resultType), new XAttribute(kPublicName, ""), - new XAttribute(kPrivateName, parmName), new XAttribute(kIsVariadic, false)); - setParamList.AddFirst(newValueParam); - - var setFunc = ToFunctionDeclaration(kSetSubscript, "()", accessibility, isStatic, hasThrows, - isFinal, isOptional, isConvenienceInit: false, objCSelector: null, kNone, - isDeprecated, isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - currentElement.Push(setFunc); - var setParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), setParamList); - currentElement.Pop(); - - setFunc.Add(setParamLists); - AddObjCSelector(setFunc); - AddElementToParentMembers(setFunc); - } - - // this makes the subscript parameter list get ignored because we already handled it. - PushIgnore(); - } - - public override void ExitSubscript_declaration([NotNull] Subscript_declarationContext context) - { - PopIgnore(); - } - - string TypeText(ParserRuleContext ty) - { - return SyntaxDesugaringParser.TypeText(inputStream, ty); - } - - public override void EnterVariable_declaration([NotNull] Variable_declarationContext context) - { - var head = context.variable_declaration_head(); - var accessibility = AccessibilityFromModifiers(head.declaration_modifiers()); - var attributes = GatherAttributes(head.attributes()); - var isDeprecated = CheckForDeprecated(attributes); - var isUnavailable = CheckForUnavailable(attributes); - var isStatic = ModifiersContains(head.declaration_modifiers(), kStatic); - var isFinal = ModifiersContains(head.declaration_modifiers(), kFinal); - var isLet = head.let_clause() != null; - var isOptional = ModifiersContains(head.declaration_modifiers(), kOptional); - var isMutating = ModifiersContains(head.declaration_modifiers(), kMutating); - var isRequired = ModifiersContains(head.declaration_modifiers(), kRequired); - var isProperty = true; - - foreach (var tail in context.variable_declaration_tail()) - { - var name = UnTick(tail.variable_name().GetText()); - var resultType = TypeText(tail.type_annotation().type()); - var hasThrows = false; - var isAsync = HasAsync(tail.getter_setter_keyword_block()?.getter_keyword_clause()); - - var getParamList = new XElement(kParameterList, new XAttribute(kIndex, "1")); - var getFunc = ToFunctionDeclaration("get_" + name, - resultType, accessibility, isStatic, hasThrows, isFinal, isOptional, - isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, - isUnavailable, isMutating, isRequired, isProperty, isAsync: isAsync, attributes); - - currentElement.Push(getFunc); - var getParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), getParamList); - currentElement.Pop(); - getFunc.Add(getParamLists); - AddElementToParentMembers(getFunc); - AddObjCSelector(getFunc); - - var setParamList = HasSetter(tail, isLet) ? - new XElement(kParameterList, new XAttribute(kIndex, "1")) : null; - - if (setParamList != null) - { - var parmName = tail.getter_setter_keyword_block()?.setter_keyword_clause().new_value_name()?.GetText() - ?? kNewValue; - var setterType = EscapePossibleClosureType(resultType); - var newValueParam = new XElement(kParameter, new XAttribute(kIndex, "0"), - new XAttribute(kType, setterType), new XAttribute(kPublicName, parmName), - new XAttribute(kPrivateName, parmName), new XAttribute(kIsVariadic, false)); - setParamList.Add(newValueParam); - var setFunc = ToFunctionDeclaration("set_" + name, - "()", accessibility, isStatic, hasThrows, isFinal, isOptional, - isConvenienceInit: false, objCSelector: null, operatorKind: kNone, isDeprecated, - isUnavailable, isMutating, isRequired, isProperty, isAsync: false, attributes); - - currentElement.Push(setFunc); - var setParamLists = new XElement(kParameterLists, MakeInstanceParameterList(), setParamList); - currentElement.Pop(); - - setFunc.Add(setParamLists); - AddElementToParentMembers(setFunc); - AddObjCSelector(setFunc); - } - - var prop = new XElement(kProperty, new XAttribute(kName, name), - new XAttribute(nameof(accessibility), accessibility), - new XAttribute(kType, resultType), - new XAttribute(kStorage, kComputed), - new XAttribute(nameof(isStatic), XmlBool(isStatic)), - new XAttribute(nameof(isLet), XmlBool(isLet)), - new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated)), - new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable)), - new XAttribute(nameof(isOptional), XmlBool(isOptional))); - AddElementToParentMembers(prop); - } - - PushIgnore(); - } - - bool HasSetter(Variable_declaration_tailContext context, bool isLet) - { - // conditions for having a setter: - // defaultInitializer and getter_setter_keyword are both null (public var foo: Type) - // defaultInitializer is not null (public var foo: Type = initialValue) - // getter_setter_keyword_block is non-null and the getter_setter_keyword_block - // has a non-null setter_keyword_clause (public var foo:Type { get; set; }, public foo: Type { set } - - var defaultInitializer = context.defaultInitializer(); - var gettersetter = context.getter_setter_keyword_block(); - - return !isLet && ((defaultInitializer == null && gettersetter == null) || - defaultInitializer != null || - gettersetter?.setter_keyword_clause() != null); - } - - public override void EnterExtension_declaration([NotNull] Extension_declarationContext context) - { - var onType = UnTick(TypeText(context.type_identifier())); - var inherits = GatherInheritance(context.type_inheritance_clause(), forceProtocolInheritance: true); - // why, you say, why put a kKind tag into an extension? - // The reason is simple: this is a hack. Most of the contents - // of an extension are the same as a class and as a result we can - // pretend that it's a class and everything will work to fill it out - // using the class/struct/enum code for members. - var extensionElem = new XElement(kExtension, - new XAttribute(nameof(onType), onType), - new XAttribute(kKind, kClass)); - if (inherits?.Count > 0) - extensionElem.Add(new XElement(nameof(inherits), inherits.ToArray())); - currentElement.Push(extensionElem); - extensions.Add(extensionElem); - } - - public override void ExitExtension_declaration([NotNull] Extension_declarationContext context) - { - var extensionElem = currentElement.Pop(); - var onType = extensionElem.Attribute(kOnType); - var givenOnType = onType.Value; - var actualOnType = UnTick(TypeText(context.type_identifier())); - if (givenOnType != actualOnType) - throw new Exception($"extension type mismatch on exit declaration: expected {actualOnType} but got {givenOnType}"); - // remove the kKind attribute - you've done your job. - extensionElem.Attribute(kKind)?.Remove(); - - currentElement.Peek().Add(extensionElem); - } - - public override void ExitImport_statement([NotNull] Import_statementContext context) - { - // this is something like: import class Foo.Bar - // and we're not handling that yet - if (context.import_kind() != null) - return; - importModules.Add(context.import_path().GetText()); - } - - public override void EnterOperator_declaration([NotNull] Operator_declarationContext context) - { - var operatorElement = InfixOperator(context.infix_operator_declaration()) - ?? PostfixOperator(context.postfix_operator_declaration()) - ?? PrefixOperator(context.prefix_operator_declaration()); - operators.Add(operatorElement); - - currentElement.Peek().Add(operatorElement); - } - - public override void EnterOptional_type([NotNull] Optional_typeContext context) - { - } - - XElement InfixOperator(Infix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator(kInfix, context.@operator(), - context.infix_operator_group()?.precedence_group_name()?.GetText() ?? ""); - } - - XElement PostfixOperator(Postfix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator(kPostfix, context.@operator(), ""); - } - - XElement PrefixOperator(Prefix_operator_declarationContext context) - { - if (context == null) - return null; - return GeneralOperator(kPrefix, context.@operator(), ""); - } - - XElement GeneralOperator(string operatorKind, OperatorContext context, string precedenceGroup) - { - return new XElement(kOperator, - new XAttribute(kName, context.Operator().GetText()), - new XAttribute(nameof(operatorKind), operatorKind), - new XAttribute(nameof(precedenceGroup), precedenceGroup)); - } - - XElement HandleGenerics(Generic_parameter_clauseContext genericContext, Generic_where_clauseContext whereContext, bool addParentGenerics) - { - if (genericContext == null) - return null; - var genericElem = new XElement(kGenericParameters); - if (addParentGenerics) - AddParentGenerics(genericElem); - foreach (var generic in genericContext.generic_parameter_list().generic_parameter()) - { - var name = UnTick(TypeText(generic.type_name())); - var genParam = new XElement(kParam, new XAttribute(kName, name)); - genericElem.Add(genParam); - var whereType = TypeText(generic.type_identifier()) ?? - TypeText(generic.protocol_composition_type()); - if (whereType != null) - { - genericElem.Add(MakeConformanceWhere(name, whereType)); - } - } - - if (whereContext == null) - return genericElem; - - foreach (var requirement in whereContext.requirement_list().requirement()) - { - if (requirement.conformance_requirement() != null) - { - var name = UnTick(TypeText(requirement.conformance_requirement().type_identifier()[0])); - - // if there is no protocol composition type, then it's the second type identifier - var from = TypeText(requirement.conformance_requirement().protocol_composition_type()) - ?? TypeText(requirement.conformance_requirement().type_identifier()[1]); - genericElem.Add(MakeConformanceWhere(name, from)); - } - else - { - var name = UnTick(TypeText(requirement.same_type_requirement().type_identifier())); - var type = TypeText(requirement.same_type_requirement().type()); - genericElem.Add(MakeEqualityWhere(name, type)); - } - } - - return genericElem; - } - - public override void ExitTypealias_declaration([NotNull] Typealias_declarationContext context) - { - var name = UnTick(context.typealias_name().GetText()); - var generics = TypeText(context.generic_parameter_clause()) ?? ""; - var targetType = TypeText(context.typealias_assignment().type()); - var access = ToAccess(context.access_level_modifier()); - var map = new XElement(kTypeAlias, new XAttribute(kName, name + generics), - new XAttribute(kAccessibility, access), - new XAttribute(kType, targetType)); - if (access != null) - { - if (currentElement.Peek().Name == kModule) - { - typeAliasMap.Add(map); - } - else - { - var curr = currentElement.Peek(); - var aliaslist = curr.Element(kTypeAliases); - if (aliaslist == null) - { - aliaslist = new XElement(kTypeAliases); - curr.Add(aliaslist); - } - aliaslist.Add(map); - } - } - } - - XElement MakeConformanceWhere(string name, string from) - { - return new XElement(kWhere, new XAttribute(nameof(name), name), - new XAttribute(kRelationship, kInherits), - new XAttribute(nameof(from), from)); - } - - XElement MakeEqualityWhere(string firsttype, string secondtype) - { - return new XElement(kWhere, new XAttribute(nameof(firsttype), firsttype), - new XAttribute(kRelationship, kEquals), - new XAttribute(nameof(secondtype), secondtype)); - } - - public override void ExitVariable_declaration([NotNull] Variable_declarationContext context) - { - PopIgnore(); - } - - void PushIgnore() - { - currentElement.Push(new XElement(kIgnore)); - } - - void PopIgnore() - { - var elem = currentElement.Pop(); - if (elem.Name != kIgnore) - throw new ParseException($"Expected an {kIgnore} element, but got {elem}"); - } - - bool ShouldIgnore() - { - return currentElement.Peek().Name == kIgnore; - } - - public override void EnterParameter_clause([NotNull] Parameter_clauseContext context) - { - if (ShouldIgnore()) - return; - - var parameterLists = new XElement(kParameterLists); - XElement instanceList = MakeInstanceParameterList(); - var formalIndex = 0; - if (instanceList != null) - { - parameterLists.Add(instanceList); - formalIndex = 1; - } - - var formalArguments = MakeParameterList(context.parameter_list(), formalIndex, false); - - parameterLists.Add(formalArguments); - currentElement.Peek().Add(parameterLists); - } - - XElement MakeParameterList(Parameter_listContext parmList, int index, bool isSubscript, int startIndex = 0) - { - var formalArguments = new XElement(kParameterList, new XAttribute(kIndex, index.ToString())); - - if (parmList != null) - { - var i = startIndex; - foreach (var parameter in parmList.parameter()) - { - var parameterElement = ToParameterElement(parameter, i, isSubscript); - formalArguments.Add(parameterElement); - i++; - } - } - return formalArguments; - } - - XElement MakeInstanceParameterList() - { - var topElem = currentElement.Peek(); - if (topElem.Name == kModule) - return null; - if (topElem.Name != kFunc) - throw new ParseException($"Expecting a func node but got {topElem.Name}"); - if (NominalParentAfter(0) == null) - return null; - var funcName = topElem.Attribute(kName).Value; - var isStatic = topElem.Attribute(kIsStatic).Value == "true"; - var isCtorDtor = IsCtorDtor(funcName); - var isClass = NominalParentAfter(0).Attribute(kKind).Value == kClass; - var instanceName = GetInstanceName(); - var type = $"{(isClass ? "" : "inout ")}{instanceName}{(isCtorDtor ? ".Type" : "")}"; - var parameter = new XElement(kParameter, new XAttribute(kType, type), - new XAttribute(kIndex, "0"), new XAttribute(kPublicName, "self"), - new XAttribute(kPrivateName, "self"), new XAttribute(kIsVariadic, "false")); - return new XElement(kParameterList, new XAttribute(kIndex, "0"), parameter); - } - - void AddParentGenerics(XElement genericResult) - { - var parentGenerics = new List(); - for (int i = 0; i < currentElement.Count; i++) - { - var elem = currentElement.ElementAt(i); - if (!IsNominal(elem)) - continue; - var elemGenerics = elem.Element(kGenericParameters); - if (elemGenerics == null) - continue; - foreach (var param in elemGenerics.Descendants(kParam)) - { - parentGenerics.Add(new XElement(param)); - } - } - genericResult.Add(parentGenerics.ToArray()); - } - - XElement NominalParentAfter(int start) - { - for (var i = start + 1; i < currentElement.Count; i++) - { - var elem = currentElement.ElementAt(i); - if (IsNominal(elem)) - return elem; - } - return null; - } - - bool IsNominal(XElement elem) - { - var kind = elem.Attribute(kKind)?.Value; - return kind != null && (kind == kClass || kind == kStruct || kind == kEnum || kind == kProtocol); - } - - string GetInstanceName() - { - var nameBuffer = new StringBuilder(); - for (int i = 0; i < currentElement.Count; i++) - { - var elem = currentElement.ElementAt(i); - if (IsNominal(elem)) - { - if (elem.Name == kExtension) - return elem.Attribute(kOnType).Value; - if (nameBuffer.Length > 0) - nameBuffer.Insert(0, '.'); - nameBuffer.Insert(0, elem.Attribute(kName).Value); - var generics = elem.Element(kGenericParameters); - if (generics != null) - { - AddGenericsToName(nameBuffer, generics); - } - } - } - nameBuffer.Insert(0, '.'); - var module = currentElement.Last(); - nameBuffer.Insert(0, moduleName); - return nameBuffer.ToString(); - } - - void AddGenericsToName(StringBuilder nameBuffer, XElement generics) - { - var isFirst = true; - foreach (var name in GenericNames(generics)) - { - if (isFirst) - { - nameBuffer.Append("<"); - isFirst = false; - } - else - { - nameBuffer.Append(", "); - } - nameBuffer.Append(name); - } - if (!isFirst) - nameBuffer.Append(">"); - } - - IEnumerable GenericNames(XElement generics) - { - return generics.Elements().Where(elem => elem.Name == kParam).Select(elem => elem.Attribute(kName).Value); - } - - XElement ToParameterElement(ParameterContext context, int index, bool isSubscript) - { - var typeAnnotation = context.type_annotation(); - var isInOut = typeAnnotation.inout_clause() != null; - var type = TypeText(typeAnnotation.type()); - var privateName = NoUnderscore(UnTick(context.local_parameter_name()?.GetText()) ?? ""); - var replacementPublicName = isSubscript ? "" : privateName; - var publicName = NoUnderscore(UnTick(context.external_parameter_name()?.GetText()) ?? replacementPublicName); - var isVariadic = context.range_operator() != null; - if (isVariadic) - type = $"Swift.Array<{type}>"; - var isEscaping = AttributesContains(typeAnnotation.attributes(), kEscaping); - var isAutoClosure = AttributesContains(typeAnnotation.attributes(), kAutoClosure); - var typeBuilder = new StringBuilder(); - if (isEscaping) - typeBuilder.Append("@escaping[] "); - if (isAutoClosure) - typeBuilder.Append("@autoclosure[] "); - if (isInOut) - typeBuilder.Append("inout "); - typeBuilder.Append(type); - type = typeBuilder.ToString(); - - var paramElement = new XElement(kParameter, new XAttribute(nameof(index), index.ToString()), - new XAttribute(nameof(type), type), new XAttribute(nameof(publicName), publicName), - new XAttribute(nameof(privateName), privateName), new XAttribute(nameof(isVariadic), XmlBool(isVariadic))); - return paramElement; - } - - static string NoUnderscore(string s) - { - return s == "_" ? "" : s; - } - - XElement GatherAttributes(AttributesContext context) - { - if (context == null) - return null; - var attributes = new XElement(kAttributes); - foreach (var attr in context.attribute()) - { - var attrElement = GatherAttribute(attr); - if (attrElement != null) - attributes.Add(attrElement); - } - return attributes.HasElements ? attributes : null; - } - - XElement GatherAttribute(AttributeContext context) - { - var attribute = new XElement(kAttribute, new XAttribute(kName, context.attribute_name().GetText())); - if (context.attribute_argument_clause() != null) - { - var parameters = GatherParameters(context.attribute_argument_clause()?.balanced_tokens()); - if (parameters != null) - attribute.Add(parameters); - } - return attribute; - } - - XElement GatherParameters(Balanced_tokensContext context) - { - if (context == null) - return null; - var parameterlist = new XElement(kAttributeParameterList); - - foreach (var balancedToken in context.balanced_token()) - { - var parameter = ToAttributeParameter(balancedToken); - if (parameter != null) - parameterlist.Add(parameter); - } - return parameterlist.HasElements ? parameterlist : null; - } - - XElement ToAttributeParameter(Balanced_tokenContext context) - { - if (context.balanced_tokens() != null) - { - var sublist = new XElement(kAttributeParameter, new XAttribute(kKind, kSublist)); - var subparams = GatherParameters(context.balanced_tokens()); - if (subparams != null) - sublist.Add(subparams); - return sublist; - } - - if (context.label_identifier() != null) - { - var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), - new XAttribute(kValue, context.label_identifier().GetText())); - return label; - } - - if (context.literal() != null) - { - var literal = new XElement(kAttributeParameter, new XAttribute(kKind, kLiteral), - new XAttribute(kValue, context.literal().GetText())); - return literal; - } - - // make the operator look like a label - if (context.@operator() != null) - { - var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), - new XAttribute(kValue, context.@operator().GetText())); - return label; - } - - if (context.any_punctuation_for_balanced_token() != null) - { - var label = new XElement(kAttributeParameter, new XAttribute(kKind, kLabel), - new XAttribute(kValue, context.any_punctuation_for_balanced_token().GetText())); - return label; - } - - return null; - } - - List GatherInheritance(Type_inheritance_clauseContext context, bool forceProtocolInheritance, - bool removeNonProtocols = false) - { - var inheritance = new List(); - if (context == null) - return inheritance; - var list = context.type_inheritance_list(); - bool first = true; - while (list != null) - { - var inheritanceKind = forceProtocolInheritance ? kProtocol : - (inheritance.Count > 0 ? kProtocol : kLittleUnknown); - var type = TypeText(list.type_identifier()); - if (!(first && removeNonProtocols && TypeIsNotProtocol(type))) - { - var elem = new XElement(kInherit, new XAttribute(kType, type), - new XAttribute(nameof(inheritanceKind), inheritanceKind)); - inheritance.Add(elem); - if (inheritanceKind == kLittleUnknown) - unknownInheritance.Add(elem); - } - first = false; - list = list.type_inheritance_list(); - } - - return inheritance; - } - - bool TypeIsNotProtocol(string type) - { - // special case this - the type database as this as "other" - // which is technically not a protocol, but it is a protocol. - if (type == "Swift.Error") - return false; - var parts = type.Split('.'); - if (parts.Length == 1) - return true; // generic - var module = parts[0]; - if (!typeDatabase.ModuleNames.Contains(module)) - { - moduleLoader.Load(module, typeDatabase); - } - var entity = typeDatabase.TryGetEntityForSwiftName(type); - if (entity != null && entity.EntityType != EntityType.Protocol) - return true; - return false; - } - - XElement ToTypeDeclaration(string kind, string name, string accessibility, bool isObjC, - bool isFinal, bool isDeprecated, bool isUnavailable, List inherits, XElement generics, - XElement attributes) - { - var xobjects = new List(); - if (generics != null) - xobjects.Add(generics); - xobjects.Add(new XAttribute(nameof(kind), kind)); - xobjects.Add(new XAttribute(nameof(name), name)); - xobjects.Add(new XAttribute(nameof(accessibility), accessibility)); - xobjects.Add(new XAttribute(nameof(isObjC), XmlBool(isObjC))); - xobjects.Add(new XAttribute(nameof(isFinal), XmlBool(isFinal))); - xobjects.Add(new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated))); - xobjects.Add(new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable))); - - xobjects.Add(new XElement(kMembers)); - if (inherits != null && inherits.Count > 0) - xobjects.Add(new XElement(nameof(inherits), inherits.ToArray())); - if (attributes != null) - xobjects.Add(attributes); - return new XElement(kTypeDeclaration, xobjects.ToArray()); - } - - - XElement ToFunctionDeclaration(string name, string returnType, string accessibility, - bool isStatic, bool hasThrows, bool isFinal, bool isOptional, bool isConvenienceInit, - string objCSelector, string operatorKind, bool isDeprecated, bool isUnavailable, - bool isMutating, bool isRequired, bool isProperty, bool isAsync, XElement attributes) - { - var decl = new XElement(kFunc, new XAttribute(nameof(name), name), new XAttribute(nameof(returnType), returnType), - new XAttribute(nameof(accessibility), accessibility), new XAttribute(nameof(isStatic), XmlBool(isStatic)), - new XAttribute(nameof(hasThrows), XmlBool(hasThrows)), new XAttribute(nameof(isFinal), XmlBool(isFinal)), - new XAttribute(nameof(isOptional), XmlBool(isOptional)), - new XAttribute(nameof(isConvenienceInit), XmlBool(isConvenienceInit)), - new XAttribute(nameof(isDeprecated), XmlBool(isDeprecated)), - new XAttribute(nameof(isUnavailable), XmlBool(isUnavailable)), - new XAttribute(nameof(isRequired), XmlBool(isRequired)), - new XAttribute(kIsAsync, XmlBool(isAsync)), - new XAttribute(kIsProperty, XmlBool(isProperty)), - new XAttribute(nameof(isMutating), XmlBool(isMutating))); - - if (operatorKind != null) - { - decl.Add(new XAttribute(nameof(operatorKind), operatorKind)); - } - if (objCSelector != null) - { - decl.Add(new XAttribute(nameof(objCSelector), objCSelector)); - } - if (attributes != null) - { - decl.Add(attributes); - } - return decl; - } - - bool CheckForDeprecated(XElement attributes) - { - var availableTags = AvailableAttributes(attributes); - foreach (var attribute in availableTags) - { - var args = AttrbuteParameters(attribute); - var platform = args[0]; - if (!PlatformMatches(platform)) - continue; - - var deprecatedIndex = args.IndexOf(kDeprecated); - if (deprecatedIndex < 0) - continue; - var deprecatedVersion = GetVersionAfter(args, deprecatedIndex); - if (TargetVersionIsLessOrEqual(deprecatedVersion)) - return true; - } - return false; - } - - bool CheckForUnavailable(XElement attributes) - { - var availableTags = AvailableAttributes(attributes); - foreach (var attribute in availableTags) - { - var args = AttrbuteParameters(attribute); - // if unavailable exists, need to match platform - if (args.IndexOf(kUnavailable) >= 0 && PlatformMatches(args[0])) - return true; - - } - return !CheckForAvailable(attributes); - } - - bool CheckForAvailable(XElement attributes) - { - var availableTags = AvailableAttributes(attributes); - foreach (var attribute in availableTags) - { - var args = AttrbuteParameters(attribute); - if (IsShortHand(args)) - { - return AvailableShorthand(args); - } - else - { - return AvailableLonghand(args); - } - } - return true; - } - - bool AvailableLonghand(List args) - { - // args will be plat , specifiers - // specificers will be: - // introduced: version - // deprecated: version - // obsoleted: version - // unavailable - var platform = args[0]; - if (!PlatformMatches(platform)) - return true; - - // if unavailable is present, it's not there. - if (args.IndexOf(kUnavailable) >= 0) - return false; - - var introIndex = args.IndexOf(kIntroduced); - if (introIndex >= 0) - { - var introVersion = GetVersionAfter(args, introIndex); - if (TargetVersionIsGreaterOrEqual(introVersion)) - return false; - } - - var obsoletedIndex = args.IndexOf(kObsoleted); - if (obsoletedIndex >= 0) - { - var obsoletedVersion = GetVersionAfter(args, obsoletedIndex); - if (TargetVersionIsLessOrEqual(obsoletedVersion)) - return false; - } - return true; - } - - bool AvailableShorthand(List args) - { - // args will be: plat ver . x . y , plat ver , ... * - - var startIndex = 0; - while (startIndex < args.Count) - { - if (args[startIndex] == "*") - return false; - var platform = args[startIndex]; - if (PlatformMatches(platform)) - { - var endIndex = args.IndexOf(",", startIndex + 1); - var versionNumber = args.GetRange(startIndex + 1, endIndex - startIndex); - if (TargetVersionIsGreaterOrEqual(versionNumber)) - return true; - } - else - { - startIndex = args.IndexOf(",", startIndex + 1); - } - } - return false; - } - - bool IsShortHand(List args) - { - if (args[1] == ",") - return false; - return args.Last() == "*"; - } - - Version GetVersionAfter(List pieces, int indexAfter) - { - var colonIndex = ColonAfter(pieces, indexAfter); - if (colonIndex < 0) - return new Version(0, 0); - var start = colonIndex + 1; - var end = start + 1; - while (end < pieces.Count && pieces[end] != ",") - end++; - var versionPieces = pieces.GetRange(start, end - start); - return VersionPiecesToVersion(versionPieces); - } - - int ColonAfter(List pieces, int start) - { - for (int i = start + 1; i < pieces.Count; i++) - { - if (pieces[i] == ":") - return i; - if (pieces[i] == ",") - return -1; - } - return -1; - } - - bool TargetVersionIsGreaterOrEqual(List versionPieces) - { - var expectedVersion = VersionPiecesToVersion(versionPieces); - return TargetVersionIsGreaterOrEqual(expectedVersion); - } - - bool TargetVersionIsGreaterOrEqual(Version expectedVersion) - { - var compiledVersionStr = PlatformVersionFromModuleFlags(); - if (String.IsNullOrEmpty(compiledVersionStr)) - return true; // no version, I guess it's good? - var compiledVersion = new Version(compiledVersionStr); - return expectedVersion >= compiledVersion; - } - - bool TargetVersionIsLessOrEqual(List versionPieces) - { - var expectedVersion = VersionPiecesToVersion(versionPieces); - return TargetVersionIsLessOrEqual(expectedVersion); - } - - bool TargetVersionIsLessOrEqual(Version expectedVersion) - { - var compiledVersionStr = PlatformVersionFromModuleFlags(); - if (String.IsNullOrEmpty(compiledVersionStr)) - return true; // no version, I guess it's good? - var compiledVersion = new Version(compiledVersionStr); - return expectedVersion <= compiledVersion; - } - - Version VersionPiecesToVersion(List pieces) - { - var sb = new StringBuilder(); - for (int i = 0; i < pieces.Count; i++) - { - if (pieces[i] == "." && i + 1 < pieces.Count && pieces[i + 1] == "*") - break; - sb.Append(pieces[i]); - } - return new Version(sb.ToString()); - } - - IEnumerable AvailableAttributes(XElement attributes) - { - if (attributes == null) - return Enumerable.Empty(); - return attributes.Descendants(kAttribute).Where(el => el.Attribute(kName).Value == kAvailable); - - } - - List AttrbuteParameters(XElement attribute) - { - return attribute.Descendants(kAttributeParameter).Select(at => - at.Attribute(kValue)?.Value ?? "").ToList(); - } - - bool PlatformMatches(string platform) - { - var currentPlatform = PlatformFromModuleFlags(); - switch (platform) - { - case "*": - case "swift": - return true; - case "iOS": - case "iOSApplicationExtension": - return currentPlatform.StartsWith("ios", StringComparison.Ordinal) && - !currentPlatform.StartsWith("ios-macabi", StringComparison.Ordinal); - case "macOS": - case "macOSApplicationExtension": - return currentPlatform.StartsWith("macos", StringComparison.Ordinal); - case "macCatalyst": - case "macCatalystExtension": - return currentPlatform.StartsWith("ios-macabi", StringComparison.Ordinal); - case "watchOS": - case "watchOSApplicationExtension": - return currentPlatform.StartsWith("watch", StringComparison.Ordinal); - case "tvOS": - case "tvOSApplicationExtension": - return currentPlatform.StartsWith("tv", StringComparison.Ordinal); - default: - return false; - } - } - - string PlatformFromModuleFlags() - { - var flagsValue = TargetFromModuleFlags(); - var os = flagsValue.ClangTargetOS(); - var digitIndex = FirstDigitIndex(os); - if (digitIndex < 0) - return os; - return os.Substring(0, digitIndex); - } - - static int FirstDigitIndex(string s) - { - var index = 0; - foreach (char c in s) - { - if (Char.IsDigit(c)) - return index; - index++; - } - return -1; - } - - string PlatformVersionFromModuleFlags() - { - var flagsValue = TargetFromModuleFlags(); - var os = flagsValue.ClangTargetOS(); - var digitIndex = FirstDigitIndex(os); - if (digitIndex < 0) - return ""; - return os.Substring(digitIndex); - } - - string TargetFromModuleFlags() - { - string flagsValue = null; - if (!moduleFlags.TryGetValue("target", out flagsValue)) - { - return ""; - } - return flagsValue; - } - - static HashSet ModulesThatWeCanSkip = new HashSet() { - "XamGlue", - "RegisterAccess", - "_StringProcessing", - "_Concurrency", - }; - - void LoadReferencedModules() - { - var failures = new StringBuilder(); - foreach (var module in importModules) - { - // XamGlue and RegisterAccess may very well get - // used, but the functions/types exported from these - // should never need to be loaded. - if (ModulesThatWeCanSkip.Contains(module)) - continue; - // if (!moduleLoader.Load (module, typeDatabase)) { - // if (failures.Length > 0) - // failures.Append (", "); - // failures.Append (module); - // } - } - if (failures.Length > 0) - throw new ParseException($"Unable to load the following module(s): {failures.ToString()}"); - } - - void PatchPossibleOperators() - { - foreach (var func in functions) - { - var operatorKind = GetOperatorType(func.Item1); - if (operatorKind != OperatorType.None) - { - func.Item2.Attribute(nameof(operatorKind))?.Remove(); - func.Item2.SetAttributeValue(nameof(operatorKind), operatorKind.ToString()); - } - } - } - - void PatchPossibleBadInheritance() - { - foreach (var inh in unknownInheritance) - { - var type = inh.Attribute(kType).Value; - if (IsLocalClass(type) || IsGlobalClass(type) || IsNSObject(type)) - inh.Attribute(kInheritanceKind).Value = kClass; - else - inh.Attribute(kInheritanceKind).Value = kProtocol; - } - } - - void PatchAssociatedTypeConformance() - { - foreach (var assoc in associatedTypesWithConformance) - { - var conformances = assoc.Element(kConformingProtocols); - var first = conformances.Element(kConformingProtocol); - var className = (string)first.Attribute(kName); - if (IsLocalClass(className) || IsGlobalClass(className)) - { - first.Remove(); - if (conformances.Nodes().Count() == 0) - conformances.Remove(); - assoc.Add(new XElement(kSuperclass, new XAttribute(kName, className))); - } - } - } - - bool IsNSObject(string typeName) - { - return typeName == "ObjectiveC.NSObject"; - } - - bool IsLocalClass(string typeName) - { - return classes.Contains(typeName); - } - - bool IsGlobalClass(string typeName) - { - return typeDatabase.EntityForSwiftName(typeName)?.EntityType == EntityType.Class; - } - - void PatchExtensionSelfArgs() - { - foreach (var ext in extensions) - { - var onType = (string)ext.Attribute(kOnType).Value; - var parts = onType.Split('.'); - if (parts[0] == "XamGlue") - continue; - if (parts.Length > 1 && !typeDatabase.ModuleNames.Contains(parts[0])) - { - moduleLoader.Load(parts[0], typeDatabase); - } - var entity = typeDatabase.EntityForSwiftName(onType); - if (entity != null) - { - PatchExtensionSelfArgs(ext, entity); - } - } - } - - void PatchExtensionSelfArgs(XElement ext, Entity entity) - { - var isStructOrScalar = entity.IsStructOrEnum || entity.EntityType == EntityType.Scalar; - foreach (var func in ext.Descendants(kFunc)) - { - var selfArg = SelfParameter(func); - if (selfArg == null) - continue; - var attr = selfArg.Attribute(kType); - var type = (string)attr.Value; - if (entity.Type.ContainsGenericParameters) - { - type = entity.Type.ToFullyQualifiedNameWithGenerics(); - attr.Value = type; - var generics = entity.Type.Generics.ToXElement(); - if (func.Element(kGenericParameters) != null) - { - var funcGenerics = func.Element(kGenericParameters); - funcGenerics.Remove(); - foreach (var generic in funcGenerics.Elements()) - generics.Add(generic); - } - func.Add(generics); - } - if (isStructOrScalar && !type.StartsWith("inout", StringComparison.Ordinal)) - { - attr.Value = "inout " + type; - } - } - } - - XElement SelfParameter(XElement func) - { - var selfList = WhereIndexZero(func.Descendants(kParameterList)); - if (selfList == null) - return null; - var selfArg = WhereIndexZero(selfList.Descendants(kParameter)); - return selfArg; - } - - static XElement WhereIndexZero(IEnumerable elems) - { - return elems.FirstOrDefault(el => (string)el.Attribute(kIndex).Value == "0"); - } - - void PatchExtensionShortNames() - { - foreach (var ext in extensions) - { - var onType = TypeSpecParser.Parse(ext.Attribute(kOnType).Value); - var replacementType = FullyQualify(onType); - ext.Attribute(kOnType).Value = replacementType.ToString(); - foreach (var func in ext.Descendants(kFunc)) - { - var selfArg = SelfParameter(func); - if (selfArg == null) - continue; - onType = TypeSpecParser.Parse(selfArg.Attribute(kType).Value); - replacementType = FullyQualify(onType); - selfArg.Attribute(kType).Value = replacementType.ToString(); - } - } - } - - TypeSpec FullyQualify(TypeSpec spec) - { - switch (spec.Kind) - { - case TypeSpecKind.Named: - return FullyQualify(spec as NamedTypeSpec); - case TypeSpecKind.Closure: - return FullyQualify(spec as ClosureTypeSpec); - case TypeSpecKind.ProtocolList: - return FullyQualify(spec as ProtocolListTypeSpec); - case TypeSpecKind.Tuple: - return FullyQualify(spec as TupleTypeSpec); - default: - throw new NotImplementedException($"unknown TypeSpec kind {spec.Kind}"); - } - } - - TypeSpec FullyQualify(NamedTypeSpec named) - { - var dirty = false; - var newName = named.Name; - - if (!named.Name.Contains(".")) - { - newName = ReplaceName(named.Name); - dirty = true; - } - - var genParts = new TypeSpec[named.GenericParameters.Count]; - var index = 0; - foreach (var gen in named.GenericParameters) - { - var newGen = FullyQualify(gen); - genParts[index++] = newGen; - if (newGen != gen) - dirty = true; - } - - if (dirty) - { - var newNamed = new NamedTypeSpec(newName, genParts); - newNamed.Attributes.AddRange(named.Attributes); - return newNamed; - } - - return named; - } - - TypeSpec FullyQualify(TupleTypeSpec tuple) - { - var dirty = false; - var parts = new TypeSpec[tuple.Elements.Count]; - var index = 0; - foreach (var spec in tuple.Elements) - { - var newSpec = FullyQualify(spec); - if (newSpec != spec) - dirty = true; - parts[index++] = newSpec; - } - - if (dirty) - { - var newTup = new TupleTypeSpec(parts); - newTup.Attributes.AddRange(tuple.Attributes); - return newTup; - } - - return tuple; - } - - TypeSpec FullyQualify(ProtocolListTypeSpec protolist) - { - var dirty = false; - var parts = new List(); - foreach (var named in protolist.Protocols.Keys) - { - var newNamed = FullyQualify(named); - parts.Add(newNamed as NamedTypeSpec); - if (newNamed != named) - dirty = true; - } - - if (dirty) - { - var newProto = new ProtocolListTypeSpec(parts); - newProto.Attributes.AddRange(protolist.Attributes); - return newProto; - } - - return protolist; - } - - TypeSpec FullyQualify(ClosureTypeSpec clos) - { - var dirty = false; - var args = FullyQualify(clos.Arguments); - if (args != clos.Arguments) - dirty = true; - var returnType = FullyQualify(clos.ReturnType); - if (returnType != clos.ReturnType) - dirty = true; - - if (dirty) - { - var newClosure = new ClosureTypeSpec(args, returnType); - newClosure.Attributes.AddRange(clos.Attributes); - return newClosure; - } - - return clos; - } - - string ReplaceName(string nonQualified) - { - Exceptions.ThrowOnNull(nonQualified, nameof(nonQualified)); - - var localName = ReplaceLocalName(nonQualified); - if (localName != null) - return localName; - var globalName = ReplaceGlobalName(nonQualified); - if (globalName == null) - throw new ParseException($"Unable to find fully qualified name for non qualified type {nonQualified}"); - return globalName; - } - - string ReplaceLocalName(string nonQualified) - { - foreach (var candidate in nominalTypes) - { - var candidateWithoutModule = StripModule(candidate); - if (nonQualified == candidateWithoutModule) - return candidate; - } - return null; - } - - string ReplaceGlobalName(string nonQualified) - { - foreach (var module in importModules) - { - var candidateName = $"{module}.{nonQualified}"; - var entity = typeDatabase.TryGetEntityForSwiftName(candidateName); - if (entity != null) - return candidateName; - } - if (nonQualified == "EveryProtocol") - return "XamGlue.EveryProtocol"; - return null; - } - - string StripModule(string fullyQualifiedName) - { - if (fullyQualifiedName.StartsWith(moduleName, StringComparison.Ordinal)) - // don't forget the '.' - return fullyQualifiedName.Substring(moduleName.Length + 1); - return fullyQualifiedName; - } - - static bool AttributesContains(AttributesContext context, string key) - { - if (context == null) - return false; - foreach (var attr in context.attribute()) - { - if (attr.attribute_name().GetText() == key) - return true; - } - return false; - } - - static bool AttributesContainsAny(AttributesContext context, string[] keys) - { - foreach (var attr in context.attribute()) - { - var attrName = attr.attribute_name().GetText(); - foreach (var key in keys) - { - if (key == attrName) - return true; - } - } - return false; - } - - string EscapePossibleClosureType(string type) - { - var typeSpec = TypeSpecParser.Parse(type); - return typeSpec is ClosureTypeSpec ? "@escaping[] " + type : type; - } - - static Dictionary accessMap = new Dictionary() { - { kPublic, kPublicCap }, - { kPrivate, kPrivateCap }, - { kOpen, kOpenCap }, - { kInternal, kInternalCap }, - }; - - string AccessibilityFromModifiers(Declaration_modifiersContext context) - { - // If there is no context, we need to search for the appropriate context - // Swift has a number of "interesting" rules for implicitly defined accessibility - // If the parent element is a protocol, it's public - // If the parent is public, internal, or open then it's open - // If the parent is private or fileprivate, then it's private - - // Note that I don't make any distinction between private and fileprivate - // From our point of view, they're the same: they're things that we don't - // have access to and don't care about in writing a reflector of the public - // API. - if (context == null) - { - var parentElem = NominalParentAfter(-1); - if (parentElem == null) - return kInternalCap; - if (parentElem.Attribute(kKind).Value == kProtocol) - return kPublicCap; - switch (parentElem.Attribute(kAccessibility).Value) - { - case kPublic: - case kInternal: - case kOpen: - return kInternalCap; - case kPrivate: - case kFilePrivate: - return kPrivateCap; - } - } - foreach (var modifer in context.declaration_modifier()) - { - string result; - if (accessMap.TryGetValue(modifer.GetText(), out result)) - return result; - } - return kInternalCap; - } - - static bool HasAsync(Getter_keyword_clauseContext context) - { - return context == null ? false : context.async_clause() != null; - } - - static bool ModifiersContains(Declaration_modifiersContext context, string match) - { - if (context == null) - return false; - foreach (var modifier in context.declaration_modifier()) - { - var text = modifier.GetText(); - if (text == match) - return true; - } - return false; - } - - public override void EnterDeclaration_modifier([NotNull] Declaration_modifierContext context) - { - var modifier = context.GetText(); - - } - - static bool ModifiersContainsAny(Declaration_modifiersContext context, string[] matches) - { - if (context == null) - return false; - foreach (var modifier in context.declaration_modifier()) - { - var text = modifier.GetText(); - foreach (var match in matches) - if (text == match) - return true; - } - return false; - } - - static bool IsStaticOrClass(Declaration_modifiersContext context) - { - return ModifiersContainsAny(context, new string[] { kStatic, kClass }); - } - - static bool IsFinal(Declaration_modifiersContext context) - { - return ModifiersContains(context, kFinal); - } - - void AddStructToCurrentElement(XElement elem) - { - var parentElement = GetOrCreateParentElement(kInnerStructs); - parentElement.Add(elem); - RegisterNominal(elem); - } - - void AddEnumToCurrentElement(XElement elem) - { - var parentElement = GetOrCreateParentElement(kInnerEnums); - parentElement.Add(elem); - RegisterNominal(elem); - } - - void AddClassToCurrentElement(XElement elem) - { - var parentElement = GetOrCreateParentElement(kInnerClasses); - parentElement.Add(elem); - RegisterNominal(elem); - } - - void RegisterNominal(XElement elem) - { - var isClass = elem.Attribute(kKind).Value == kClass; - var builder = new StringBuilder(); - while (elem != null) - { - if (builder.Length > 0) - builder.Insert(0, '.'); - var namePart = elem.Attribute(kName)?.Value ?? moduleName; - builder.Insert(0, namePart); - elem = elem.Parent; - } - var typeName = builder.ToString(); - nominalTypes.Add(typeName); - if (isClass) - classes.Add(typeName); - } - - void AddAssociatedTypeToCurrentElement(XElement elem) - { - var parentElement = GetOrCreateParentElement(kAssociatedTypes); - parentElement.Add(elem); - } - - XElement GetOrCreateParentElement(string parentContainerName) - { - var current = currentElement.Peek(); - if (current.Name == kModule) - { - return current; - } - var container = GetOrCreate(current, parentContainerName); - return container; - } - - OperatorType GetOperatorType(Function_declarationContext context) - { - var localOp = LocalOperatorType(context); - return localOp == OperatorType.None ? GlobalOperatorType(context.function_name().GetText()) - : localOp; - } - - OperatorType LocalOperatorType(Function_declarationContext context) - { - var head = context.function_head(); - - - // if the function declaration contains prefix - if (ModifiersContains(head.declaration_modifiers(), kLittlePrefix)) - { - return OperatorType.Prefix; - } - else if (ModifiersContains(head.declaration_modifiers(), kLittlePostfix)) - { - return OperatorType.Postfix; - } - - var opName = context.function_name().GetText(); - - foreach (var op in operators) - { - var targetName = op.Attribute(kName).Value; - var targetKind = op.Attribute(kOperatorKind).Value; - if (opName == targetName && targetKind == kInfix) - return OperatorType.Infix; - } - return OperatorType.None; - } - - OperatorType GlobalOperatorType(string name) - { - foreach (var op in typeDatabase.FindOperators(importModules)) - { - if (op.Name == name) - return op.OperatorType; - } - return OperatorType.None; - } - - void InterpretCommentText(string commentText) - { - if (commentText.StartsWith(kSwiftInterfaceFormatVersion)) - { - AssignSwiftInterfaceFormat(commentText.Substring(kSwiftInterfaceFormatVersion.Length)); - } - else if (commentText.StartsWith(kSwiftCompilerVersion)) - { - AssignSwiftCompilerVersion(commentText.Substring(kSwiftCompilerVersion.Length)); - } - else if (commentText.StartsWith(kSwiftModuleFlags)) - { - ExtractModuleFlags(commentText.Substring(kSwiftModuleFlags.Length)); - moduleFlags.TryGetValue(kModuleName, out moduleName); - } - } - - void AssignSwiftInterfaceFormat(string formatVersion) - { - // when we get here, we should see something like - // [white-space]*VERSION[white-space] - formatVersion = formatVersion.Trim(); - if (!Version.TryParse(formatVersion, out interfaceVersion)) - throw new ArgumentOutOfRangeException(nameof(formatVersion), $"Expected a version string in the interface format but got {formatVersion}"); - } - - void AssignSwiftCompilerVersion(string compilerVersion) - { - // when we get here, we should see something like: - // [white-space]*Apple? Swift version VERSION (swiftlang-VERSION clang-VERSION) - var parts = compilerVersion.Trim().Split(' ', '\t'); // don't know if tab is a thing - // expect in the array: - // 0: Apple - // 1: Swift - // 2: verion - // 3: VERSION - - var swiftIndex = Array.IndexOf(parts, "Swift"); - if (swiftIndex < 0) - throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected 'Swift' in the version string, but got {compilerVersion}"); - if (parts[swiftIndex + 1] != "version") - throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected a compiler version string but got {compilerVersion}"); - var version = parts[swiftIndex + 2]; - if (version.EndsWith("-dev", StringComparison.Ordinal)) - version = version.Substring(0, version.Length - "-dev".Length); - if (!Version.TryParse(version, out this.compilerVersion)) - throw new ArgumentOutOfRangeException(nameof(compilerVersion), $"Expected a compiler version number but got {compilerVersion}"); - } - - void ExtractModuleFlags(string commentText) - { - var args = commentText.Trim().Split(' ', '\t'); - int index = 0; - while (index < args.Length) - { - var arg = args[index++]; - if (arg[0] != '-') - throw new ArgumentOutOfRangeException(nameof(CommentContext), - $"Expected argument {index - 1} to start with a '-' but got {arg} (args: {commentText}"); - var key = arg.Substring(1); - var val = ""; - if (index < args.Length && args[index][0] != '-') - { - val = args[index++]; - } - moduleFlags[key] = val; - } - } - - void SetLanguageVersion(XElement module) - { - if (compilerVersion != null) - { - module.Add(new XAttribute("swiftVersion", compilerVersion.ToString())); - } - } - - static string XmlBool(bool b) - { - return b ? "true" : "false"; - } - - static string ToAccess(Access_level_modifierContext access) - { - var accessstr = access != null ? access.GetText() : kInternalCap; - switch (accessstr) - { - case kPublic: - return kPublicCap; - case kPrivate: - return kPrivateCap; - case kOpen: - return kOpenCap; - case kInternal: - case kInternalCap: - return kInternalCap; - default: - return kUnknown; - } - } - - - static XElement GetOrCreate(XElement elem, string key) - { - var members = elem.Element(key); - if (members == null) - { - members = new XElement(key); - elem.Add(members); - } - return members; - } - - static string[] ctorDtorNames = new string[] { - kDotCtor, kDotDtor - }; - - static bool IsCtorDtor(string name) - { - return ctorDtorNames.Contains(name); - } - - public static string UnTick(string str) - { - // a back-ticked string will start and end with ` - // the swift grammar guarantees this. - // Identifier : - // Identifier_head Identifier_characters? - // | OpBackTick Identifier_head Identifier_characters? OpBackTick - // | ImplicitParameterName - // There will be no starting and ending whitespace. - // - // There are some edge cases that we can take advantage of: - // 1. If it starts with `, it *has* to end with back tick, so we don't need to check - // 2. `` will never exist, so the minimum length *has* to be 3 - // In generalized string manipulation, we couldn't make these assumptions, - // but in this case the grammar works for us. - // first weed out the easy cases: - // null, too short, does start and end with back tick - // then just substring it - if (str is null || str.Length < 3 || str[0] != '`') - return str; - return str.Substring(1, str.Length - 2); - } - - - public List ImportModules { get { return importModules; } } - } -} diff --git a/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs b/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs deleted file mode 100644 index 3f3fbbdd1d23..000000000000 --- a/src/SwiftReflector/SwiftInterfaceReflector/SyntaxDesugaringParser.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using Antlr4.Runtime; -using Antlr4.Runtime.Misc; -using Antlr4.Runtime.Tree; -using static SwiftInterfaceParser; -using System.Collections.Generic; - -namespace SwiftReflector.SwiftInterfaceReflector -{ - public class SyntaxDesugaringParser : SwiftInterfaceBaseListener - { - TokenStreamRewriter rewriter; - SwiftInterfaceParser parser; - ICharStream charStream; - SwiftInterfaceLexer lexer; - - public SyntaxDesugaringParser(string inFile) - { - charStream = CharStreams.fromPath(inFile); - lexer = new SwiftInterfaceLexer(charStream); - var tokenStream = new CommonTokenStream(lexer); - - rewriter = new TokenStreamRewriter(tokenStream); - this.parser = new SwiftInterfaceParser(tokenStream); - } - - public string Desugar() - { - var walker = new ParseTreeWalker(); - walker.Walk(this, parser.swiftinterface()); - return rewriter.GetText(); - } - - internal static string TypeText(ICharStream input, ParserRuleContext ty) - { - if (ty is null) - return null; - var start = ty.Start.StartIndex; - var end = ty.Stop.StopIndex; - var interval = new Interval(start, end); - return input.GetText(interval); - } - - string TypeText(ParserRuleContext ty) - { - return TypeText(charStream, ty); - } - - public override void ExitOptional_type([NotNull] Optional_typeContext context) - { - var innerType = TypeText(context.type()); - var replacementType = $"Swift.Optional<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace(startToken, endToken, replacementType); - } - - public override void ExitUnwrapped_optional_type([NotNull] Unwrapped_optional_typeContext context) - { - var innerType = TypeText(context.type()); - var replacementType = $"Swift.Optional<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace(startToken, endToken, replacementType); - } - - public override void ExitArray_type([NotNull] Array_typeContext context) - { - var innerType = TypeText(context.type()); - var replacementType = $"Swift.Array<{innerType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace(startToken, endToken, replacementType); - } - - public override void ExitDictionary_type([NotNull] Dictionary_typeContext context) - { - var keyType = TypeText(context.children[1] as ParserRuleContext); - var valueType = TypeText(context.children[3] as ParserRuleContext); - var replacementType = $"Swift.Dictionary<{keyType},{valueType}>"; - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace(startToken, endToken, replacementType); - } - - static Dictionary typeChanges = new Dictionary() { - { "Swift.Void", "()" }, - { "CoreFoundation.CGAffineTransform", "CoreGraphics.CGAffineTransform" }, - { "CoreFoundation.CGColorSapceModel", "CoreGraphics.CGColorSapceModel" }, - { "CoreFoundation.CGPoint", "CoreGraphics.CGPoint" }, - { "CoreFoundation.CGRect", "CoreGraphics.CGRect" }, - { "CoreFoundation.CGSize", "CoreGraphics.CGSize" }, - { "CoreFoundation.CGVector", "CoreGraphics.CGVector" }, - { "CoreFoundation.CGFloat", "CoreGraphics.CGFloat" }, - }; - - public override void ExitIdentifier_type([NotNull] Identifier_typeContext context) - { - if (typeChanges.TryGetValue(context.GetText(), out var substitution)) - { - var startToken = context.Start; - var endToken = context.Stop; - rewriter.Replace(startToken, endToken, substitution); - } - } - - public override void ExitFunction_type_argument([NotNull] Function_type_argumentContext context) - { - if (context.argument_label() is Argument_labelContext argContext && argContext.ChildCount == 2) - { - // function type argument of the form public_label private_label - // change to public_label - // in a .swiftinterface context, the private label means nothing to us - var startToken = argContext.Start; - var endToken = argContext.Stop; - rewriter.Replace(startToken, endToken, argContext.children[0].GetText()); - } - } - } -} - diff --git a/src/SwiftReflector/SwiftName.cs b/src/SwiftReflector/SwiftName.cs index 9727367110ad..b22573bc855f 100644 --- a/src/SwiftReflector/SwiftName.cs +++ b/src/SwiftReflector/SwiftName.cs @@ -12,7 +12,8 @@ public SwiftName(string name, bool isPunyCode) if (name == null) throw new ArgumentNullException("name"); PunyName = name; - Name = isPunyCode ? name.DePunyCode() : name; + // Name = isPunyCode ? name.DePunyCode() : name; + Name = name; } public string Name { get; private set; } diff --git a/src/SwiftReflector/SwiftReflector.csproj b/src/SwiftReflector/SwiftReflector.csproj index 282daa66ff9a..84a51f3ee95a 100644 --- a/src/SwiftReflector/SwiftReflector.csproj +++ b/src/SwiftReflector/SwiftReflector.csproj @@ -7,6 +7,7 @@ true + diff --git a/src/SwiftReflector/SwiftType.cs b/src/SwiftReflector/SwiftType.cs index ac253827f0a5..a60ebf1ab439 100644 --- a/src/SwiftReflector/SwiftType.cs +++ b/src/SwiftReflector/SwiftType.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using SwiftReflector.Demangling; using SwiftRuntimeLibrary; namespace SwiftReflector @@ -52,41 +51,6 @@ public SwiftType RenamedCloneOf(SwiftName newName) return ty; } - - public bool IsConstructor { get { return this is SwiftConstructorType; } } - - public bool IsOptionalConstructor - { - get - { - // a SwiftType is an optional ctor if: - // 1 it's a SwiftConstructorType - // 2 its return type is SwiftBoundGenericType - // 3 its return type has a base of Swift.Optional - // 4 its return type has exactly one bound type to the type of - // the metatype of this class - var ctor = this as SwiftConstructorType; - if (ctor == null) - return false; - var returnType = ctor.ReturnType as SwiftBoundGenericType; - if (returnType == null) - return false; - if (returnType.BoundTypes.Count != 1) - return false; - var baseType = returnType.BaseType as SwiftClassType; - if (baseType == null) - return false; - var boundType = returnType.BoundTypes[0] as SwiftClassType; - if (boundType == null) - return false; - var uncurriedParameter = ctor.UncurriedParameter as SwiftMetaClassType; - if (uncurriedParameter == null) - return false; - return baseType.ClassName.ToFullyQualifiedName() == "Swift.Optional" && - boundType.ClassName.ToFullyQualifiedName(true) == uncurriedParameter.Class.ClassName.ToFullyQualifiedName(true); - } - } - public bool IsEmptyTuple { get @@ -206,634 +170,6 @@ public static bool IsStructScalar(string fullyQualifiedName) } } - public class SwiftModuleNameType : SwiftType - { - public SwiftModuleNameType(SwiftName name, bool isReference) - : base(CoreCompoundType.ModuleName, isReference, name) - { - } - public override string ToString() - { - return Name != null ? Name.Name : "(unknown module)"; - } - } - - public abstract class SwiftBaseFunctionType : SwiftType - { - public SwiftBaseFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base(CoreCompoundType.Function, isReference, name) - { - Parameters = Exceptions.ThrowOnNull(parms, nameof(parms)); - ReturnType = Exceptions.ThrowOnNull(ret, nameof(ret)); - GenericArguments = new List(); - CanThrow = canThrow; - ExtensionOn = extensionOn; - } - - public bool ContainsGenericParameters - { - get - { - return GenericArguments.Count() > 0; - } - } - public SwiftType ExtensionOn { get; set; } - public abstract MemberType MemberType { get; } - public SwiftType Parameters { get; private set; } - public SwiftType ReturnType { get; private set; } - public List GenericArguments { get; private set; } - public bool CanThrow { get; private set; } - public bool IsExtension { get { return ExtensionOn != null; } } - public virtual bool IsThunk => false; - public SwiftBaseFunctionType Thunk { get; set; } - - public abstract SwiftBaseFunctionType AsThunk(); - - // for short-lived discretionary storage of information - public string DiscretionaryString { get; set; } - - public IEnumerable EachParameter - { - get - { - for (int i = 0; i < ParameterCount; i++) - { - yield return GetParameter(i); - } - } - } - - public int GenericParameterCount - { - get { return EachParameter.Sum(st => st is SwiftGenericArgReferenceType ? 1 : 0); } - } - - - public bool IsVoid { get { return ReturnType.Type == CoreCompoundType.Tuple && ((SwiftTupleType)ReturnType).IsEmpty; } } - - protected override bool LLEquals(SwiftType other) - { - var fn = other as SwiftBaseFunctionType; - if (fn == null) - return false; - if (Name != null) - Name.Equals(fn.Name); - return MemberType == fn.MemberType && Parameters.Equals(fn.Parameters) - && ReturnType.Equals(fn.ReturnType); - } - - public int ParameterCount - { - get - { - var tt = Parameters as SwiftTupleType; - if (tt == null) - { - return 1; - } - else - { - return tt.Contents.Count; - } - } - } - - public SwiftType GetParameter(int index) - { - var tt = Parameters as SwiftTupleType; - if (tt == null) - { - if (index == 0) - return Parameters; - else - throw new ArgumentOutOfRangeException(nameof(index)); - } - else - { - if (index < 0 || index >= tt.Contents.Count) - throw new ArgumentOutOfRangeException(nameof(index)); - return tt.Contents[index]; - } - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return $"{name}{Parameters.ToString()}->{ReturnType.ToString()}"; - } - } - - public class SwiftCFunctionType : SwiftBaseFunctionType - { - public SwiftCFunctionType(SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) - : base(parms, ret, isReference, false, name, null) - { - } - - public override MemberType MemberType - { - get - { - return MemberType.CFunction; - } - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftCFunctionTypeThunk(Parameters, ReturnType, IsReference, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftCFunctionTypeThunk : SwiftCFunctionType - { - public SwiftCFunctionTypeThunk(SwiftType parms, SwiftType ret, bool isReference, SwiftName name = null) - : base(parms, ret, isReference, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftAddressorType : SwiftBaseFunctionType - { - public SwiftAddressorType(AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) - : base(SwiftTupleType.Empty, ret, isReference, false, name, null) - { - AddressorType = addressor; - } - public AddressorType AddressorType { get; private set; } - public override MemberType MemberType - { - get - { - return MemberType.Addressor; - } - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftAddressorThunkType(AddressorType, ReturnType, IsReference, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftAddressorThunkType : SwiftAddressorType - { - public SwiftAddressorThunkType(AddressorType addressor, SwiftType ret, bool isReference, SwiftName name = null) - : base(addressor, ret, isReference, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftInitializerType : SwiftBaseFunctionType - { - public SwiftInitializerType(InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) - : base(SwiftTupleType.Empty, ret, false, false, name, null) - { - Owner = Exceptions.ThrowOnNull(owner, nameof(owner)); - InitializerType = initType; - } - - public InitializerType InitializerType { get; private set; } - public SwiftClassType Owner { get; private set; } - public override MemberType MemberType - { - get - { - return MemberType.Initializer; - } - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftInitializerThunkType(InitializerType, ReturnType, Owner, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftInitializerThunkType : SwiftInitializerType - { - public SwiftInitializerThunkType(InitializerType initType, SwiftType ret, SwiftClassType owner, SwiftName name) - : base(initType, ret, owner, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftFunctionType : SwiftBaseFunctionType - { - public SwiftFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) - : base(parms, ret, isReference, canThrow, name, extensionOn) - { - IsEscaping = isEscaping; - } - - public override MemberType MemberType { get { return MemberType.Function; } } - public bool IsEscaping { get; private set; } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftFunctionThunkType(Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn, IsEscaping); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftFunctionThunkType : SwiftFunctionType - { - public SwiftFunctionThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null, bool isEscaping = true) - : base(parms, ret, isReference, canThrow, name, extensionOn, isEscaping) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftCFunctionPointerType : SwiftFunctionType - { - public SwiftCFunctionPointerType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) - : base(parms, ret, isReference, canThrow, name, null) - { - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftCFunctionPointerThunkType(Parameters, ReturnType, IsReference, CanThrow, Name); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftCFunctionPointerThunkType : SwiftCFunctionPointerType - { - public SwiftCFunctionPointerThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null) - : base(parms, ret, isReference, canThrow, name) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftStaticFunctionType : SwiftFunctionType - { - public SwiftStaticFunctionType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) - : base(parms, ret, isReference, canThrow, name, extensionOn) - { - OfClass = ofClass; - } - - public SwiftClassType OfClass { get; private set; } - - public override SwiftBaseFunctionType AsThunk() - { - var func = new SwiftStaticFunctionThunkType(Parameters, ReturnType, IsReference, CanThrow, OfClass, Name, ExtensionOn); - func.DiscretionaryString = DiscretionaryString; - return func; - } - } - - public class SwiftStaticFunctionThunkType : SwiftStaticFunctionType - { - public SwiftStaticFunctionThunkType(SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftClassType ofClass, SwiftName name = null, SwiftType extensionOn = null) - : base(parms, ret, isReference, canThrow, ofClass, name, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - - public class SwiftClassConstructorType : SwiftFunctionType - { - public SwiftClassConstructorType(SwiftMetaClassType meta, bool isReference) - : base(SwiftTupleType.Empty, Exceptions.ThrowOnNull(meta, "meta"), isReference, false, Decomposer.kSwiftClassConstructorName) - { - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftClassConstructorThunkType(ReturnType as SwiftMetaClassType, IsReference); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftClassConstructorThunkType : SwiftClassConstructorType - { - public SwiftClassConstructorThunkType(SwiftMetaClassType meta, bool isReference) - : base(meta, isReference) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftUncurriedFunctionType : SwiftBaseFunctionType - { - public SwiftUncurriedFunctionType(SwiftType unCurriedParameter, - SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : this(MemberType.UncurriedFunction, unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) - { - } - - protected SwiftUncurriedFunctionType(MemberType memberType, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base(parms, ret, isReference, canThrow, name, extensionOn) - { - // oddly enough, this is allowed to be null - UncurriedParameter = unCurriedParameter; - this.memberType = memberType; - } - MemberType memberType; - public override MemberType MemberType { get { return memberType; } } - public SwiftType UncurriedParameter { get; private set; } - - protected override bool LLEquals(SwiftType other) - { - var ucf = other as SwiftUncurriedFunctionType; - return ucf != null && ucf.UncurriedParameter.Equals(UncurriedParameter) && base.LLEquals(other); - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftUncurriedFunctionThunkType(UncurriedParameter, Parameters, ReturnType, IsReference, CanThrow, Name, ExtensionOn); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftUncurriedFunctionThunkType : SwiftUncurriedFunctionType - { - public SwiftUncurriedFunctionThunkType(SwiftType unCurriedParameter, - SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftName name = null, SwiftType extensionOn = null) - : base(unCurriedParameter, parms, ret, isReference, canThrow, name, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - - public class SwiftConstructorType : SwiftUncurriedFunctionType - { - public SwiftConstructorType(bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) - : base(isAllocating ? MemberType.Allocator : MemberType.Constructor, - unCurriedParameter, parms, ret, isReference, canThrow, isAllocating ? Decomposer.kSwiftAllocatingConstructorName : - Decomposer.kSwiftNonAllocatingConstructorName, extensionOn) - { - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftConstructorThunkType(MemberType == MemberType.Allocator, UncurriedParameter, - Parameters, ReturnType, IsReference, CanThrow, ExtensionOn); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftConstructorThunkType : SwiftConstructorType - { - public SwiftConstructorThunkType(bool isAllocating, SwiftType unCurriedParameter, SwiftType parms, SwiftType ret, bool isReference, bool canThrow, SwiftType extensionOn = null) - : base(isAllocating, unCurriedParameter, parms, ret, isReference, canThrow, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftDestructorType : SwiftBaseFunctionType - { - public SwiftDestructorType(bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) - : base(classType, classType, isReference, canThrow, - isDeallocating ? Decomposer.kSwiftDeallocatingDestructorName : Decomposer.kSwiftNonDeallocatingDestructorName, null) - { - memberType = isDeallocating ? MemberType.Deallocator : MemberType.Destructor; - } - MemberType memberType; - public override MemberType MemberType { get { return memberType; } } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftDestructorThunkType(Name == Decomposer.kSwiftDeallocatingDestructorName, ReturnType as SwiftClassType, IsReference, CanThrow); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftDestructorThunkType : SwiftDestructorType - { - public SwiftDestructorThunkType(bool isDeallocating, SwiftClassType classType, bool isReference, bool canThrow) - : base(isDeallocating, classType, isReference, canThrow) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftPropertyType : SwiftUncurriedFunctionType - { - public SwiftPropertyType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base(unCurriedParameter, - (propType == PropertyType.Setter || propType == PropertyType.Materializer) ? ofType : SwiftTupleType.Empty, - (propType == PropertyType.Getter) ? ofType : SwiftTupleType.Empty, - isReference, false, propName, extensionOn) - { - PropertyType = propType; - PrivateName = privateName; - OfType = Exceptions.ThrowOnNull(ofType, "ofType"); - IsSubscript = false; - IsStatic = isStatic; - } - public SwiftPropertyType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base(unCurriedParameter, accessor.Parameters, accessor.ReturnType, isReference, false, propName, extensionOn) - { - PropertyType = propType; - PrivateName = privateName; - OfType = accessor; - IsSubscript = true; - IsStatic = isStatic; - } - - public PropertyType PropertyType { get; private set; } - public SwiftName PrivateName { get; private set; } - public SwiftType OfType { get; private set; } - public bool IsStatic { get; private set; } - - public bool IsSubscript { get; private set; } - public bool IsPublic { get { return PrivateName == null; } } - public bool IsPrivate { get { return PrivateName != null; } } - public bool IsGlobal { get { return UncurriedParameter == null; } } - - public SwiftPropertyType RecastAsStatic() - { - if (IsStatic) - return this; - SwiftPropertyType newProp = null; - if (OfType is SwiftFunctionType) - { - if (this is SwiftPropertyThunkType) - { - newProp = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, - true, IsReference); - - } - else - { - newProp = new SwiftPropertyType(UncurriedParameter, PropertyType, Name, PrivateName, OfType as SwiftFunctionType, - true, IsReference); - } - } - else - { - if (this is SwiftPropertyThunkType) - { - newProp = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); - - } - else - { - newProp = new SwiftPropertyType(UncurriedParameter, PropertyType, Name, PrivateName, OfType, true, IsReference); - } - } - newProp.DiscretionaryString = DiscretionaryString; - newProp.ExtensionOn = this.ExtensionOn; - return newProp; - } - - public override SwiftBaseFunctionType AsThunk() - { - if (IsSubscript) - { - var pt = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, - PrivateName, OfType as SwiftFunctionType, IsStatic, IsReference, ExtensionOn); - pt.DiscretionaryString = DiscretionaryString; - return pt; - } - else - { - var pt = new SwiftPropertyThunkType(UncurriedParameter, PropertyType, Name, - PrivateName, OfType, IsStatic, IsReference, ExtensionOn); - pt.DiscretionaryString = DiscretionaryString; - return pt; - } - } - } - - public class SwiftPropertyThunkType : SwiftPropertyType - { - public SwiftPropertyThunkType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftType ofType, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base(unCurriedParameter, propType, propName, privateName, ofType, isStatic, isReference, extensionOn) - { - } - - public SwiftPropertyThunkType(SwiftType unCurriedParameter, PropertyType propType, SwiftName propName, - SwiftName privateName, SwiftFunctionType accessor, bool isStatic, bool isReference, SwiftType extensionOn = null) - : base(unCurriedParameter, propType, propName, privateName, accessor, isStatic, isReference, extensionOn) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftExplicitClosureType : SwiftBaseFunctionType - { - public SwiftExplicitClosureType(bool isReference) - : base(SwiftTupleType.Empty, SwiftTupleType.Empty, isReference, false, null) - { - } - - public override MemberType MemberType - { - get - { - return MemberType.ExplicitClosure; - } - } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftExplicitClosureThunkType(IsReference); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftExplicitClosureThunkType : SwiftExplicitClosureType - { - public SwiftExplicitClosureThunkType(bool isReference) - : base(isReference) - { - } - - public override bool IsThunk => true; - - public override SwiftBaseFunctionType AsThunk() => this; - } - - public class SwiftWitnessTableType : SwiftUncurriedFunctionType - { - public SwiftWitnessTableType(WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) - : base((SwiftType)owningType ?? SwiftTupleType.Empty, SwiftTupleType.Empty, SwiftTupleType.Empty, false, false, null) - { - WitnessType = witnessType; - if (WitnessType == WitnessType.Protocol && protocolType == null) - throw new ArgumentNullException(nameof(protocolType)); - ProtocolType = protocolType; - } - public WitnessType WitnessType { get; private set; } - public SwiftClassType ProtocolType { get; private set; } - - public override SwiftBaseFunctionType AsThunk() - { - var thunk = new SwiftWitnessTableThunkType(WitnessType, ProtocolType, UncurriedParameter as SwiftClassType); - thunk.DiscretionaryString = DiscretionaryString; - return thunk; - } - } - - public class SwiftWitnessTableThunkType : SwiftWitnessTableType - { - public SwiftWitnessTableThunkType(WitnessType witnessType, SwiftClassType protocolType = null, SwiftClassType owningType = null) - : base(witnessType, protocolType, owningType) - { - } - - public override bool IsThunk => true; - public override SwiftBaseFunctionType AsThunk() => this; - } - public class SwiftTupleType : SwiftType { public SwiftTupleType(bool isReference) @@ -931,19 +267,6 @@ public override string ToString() } - public class SwiftArrayType : SwiftType - { - public SwiftArrayType(bool isReference, SwiftName name = null) - : base(CoreCompoundType.Array, isReference, name) - { - } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return $"{name}[]"; - } - } - public class SwiftClassType : SwiftType { public SwiftClassType(SwiftClassName className, bool isReference, SwiftName name = null) @@ -972,210 +295,6 @@ public override string ToString() } } - public class SwiftProtocolListType : SwiftType - { - public SwiftProtocolListType(IEnumerable protocols, bool isReference, SwiftName name = null) - : base(CoreCompoundType.ProtocolList, isReference, name) - { - Protocols = new List(); - Protocols.AddRange(protocols.Where(p => - { - if (p.IsProtocol) - { - return true; - } - else - { - throw new ArgumentOutOfRangeException("protocols", "protocols must contain only SwiftClassType with EntityKind protocol."); - } - })); - } - - public SwiftProtocolListType(SwiftClassType protocol, bool isReference, SwiftName name = null) - : base(CoreCompoundType.ProtocolList, isReference, name) - { - Protocols = new List(); - if (!protocol.IsProtocol) - throw new ArgumentOutOfRangeException($"Type {protocol.ClassName.ToFullyQualifiedName()} is not a protocol"); - Protocols.Add(protocol); - } - - public List Protocols { get; private set; } - - protected override bool LLEquals(SwiftType other) - { - var prot = other as SwiftProtocolListType; - if (other == null) - return false; - if (Protocols.Count != prot.Protocols.Count) - return false; - return Protocols.SequenceEqual(prot.Protocols); - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + Protocols.Select(p => p.ToString()).InterleaveStrings(" & "); - } - } - - public class SwiftMetaClassType : SwiftType - { - public SwiftMetaClassType(SwiftClassType classType, bool isReference, SwiftName name = null) - : base(CoreCompoundType.MetaClass, isReference, name) - { - Class = Exceptions.ThrowOnNull(classType, nameof(classType)); - } - public SwiftMetaClassType(SwiftGenericArgReferenceType classGenericReference, bool isReference, SwiftName name = null) - : base(CoreCompoundType.MetaClass, isReference, name) - { - ClassGenericReference = Exceptions.ThrowOnNull(classGenericReference, nameof(classGenericReference)); - } - public SwiftClassType Class { get; private set; } - public SwiftGenericArgReferenceType ClassGenericReference { get; private set; } - protected override bool LLEquals(SwiftType other) - { - var meta = other as SwiftMetaClassType; - if (meta == null) - return false; - if (Class != null) - return Class.Equals(meta.Class); - else - return ClassGenericReference.Equals(meta.ClassGenericReference); - } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + "Meta " + Class; - } - } - - public class SwiftExistentialMetaType : SwiftType - { - public SwiftExistentialMetaType(SwiftProtocolListType protocolList, bool isReference, SwiftName name = null) - : base(CoreCompoundType.MetaClass, isReference, name) - { - Protocol = Exceptions.ThrowOnNull(protocolList, nameof(protocolList)); - } - public SwiftProtocolListType Protocol { get; private set; } - protected override bool LLEquals(SwiftType other) - { - var meta = other as SwiftExistentialMetaType; - return meta != null && Protocol.Equals(meta.Protocol); - } - public bool IsAny { get { return Protocol.Protocols.Count == 0; } } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - return name + "Existential Metatype " + Protocol; - } - } - - public class GenericArgument - { - public GenericArgument(int depth, int index) - { - Constraints = new List(); - Depth = depth; - Index = index; - } - public int Depth { get; set; } - public int Index { get; set; } - public List Constraints { get; private set; } - public bool IsProtocolConstrained() - { - if (Constraints.Count == 0) - return false; - foreach (SwiftType ty in Constraints) - { - var ct = ty as SwiftClassType; - if (ct == null) - throw new NotSupportedException("Expected a class type, but got " + ty.GetType().Name); - if (ct.EntityKind != MemberNesting.Protocol) - return false; - } - return true; - } - public bool IsClassConstrained() - { - if (Constraints.Count == 0) - return false; - foreach (SwiftType ty in Constraints) - { - var ct = ty as SwiftClassType; - if (ct == null) - throw new NotSupportedException("Expected a class type, but got " + ty.GetType().Name); - if (ct.EntityKind != MemberNesting.Protocol) - return true; - } - return false; - } - } - - - public class SwiftUnboundGenericType : SwiftType - { - public SwiftUnboundGenericType(SwiftType dependentType, List parms, bool isReference, SwiftName name = null) - : base(CoreCompoundType.UnboundGeneric, isReference, name) - { - DependentType = Exceptions.ThrowOnNull(dependentType, nameof(dependentType)); - Arguments = Exceptions.ThrowOnNull(parms, nameof(parms)); - } - - public SwiftType DependentType { get; private set; } - public List Arguments { get; private set; } - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - var genArgs = Arguments.Select((arg) => $"({arg.Depth},{arg.Index})").InterleaveCommas(); - return $"{name}{DependentType.ToString()}<{genArgs}>"; - } - } - - public class SwiftGenericArgReferenceType : SwiftType - { - public SwiftGenericArgReferenceType(int depth, int index, bool isReference, SwiftName name = null, List associatedTypePath = null) - : base(CoreCompoundType.GenericReference, isReference, name) - { - Depth = depth; - Index = index; - AssociatedTypePath = new List(); - if (associatedTypePath != null) - AssociatedTypePath.AddRange(associatedTypePath); - } - - public int Depth { get; private set; } - public int Index { get; private set; } - public List AssociatedTypePath { get; private set; } - public bool HasAssociatedTypePath => AssociatedTypePath.Count > 0; - - protected override bool LLEquals(SwiftType other) - { - var art = other as SwiftGenericArgReferenceType; - if (art == null) - return false; - if (Depth != art.Depth || Index != art.Index) - return false; - if (AssociatedTypePath.Count != art.AssociatedTypePath.Count) - return false; - return AssociatedTypePath.SequenceEqual(art.AssociatedTypePath); - } - - public override string ToString() - { - var name = Name != null ? Name.Name + ": " : ""; - if (HasAssociatedTypePath) - { - var path = AssociatedTypePath.InterleaveStrings("."); - return name + $"({Depth},{Index}){(char)('A' + Depth)}{Index}.{path}"; - } - else - { - return name + $"({Depth},{Index})"; - } - } - } - public class SwiftBoundGenericType : SwiftType { public SwiftBoundGenericType(SwiftType baseType, List boundTypes, bool isReference, SwiftName name = null) diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs index 0285359cb764..4652f19569f3 100644 --- a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs +++ b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs @@ -1,9 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Xml.Linq; -using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; namespace SwiftReflector.SwiftXmlReflection diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs index 995e2d9e1e46..23171b317ec7 100644 --- a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs +++ b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs @@ -3,7 +3,6 @@ using System; using SwiftReflector.ExceptionTools; -using SwiftReflector.IOUtils; using System.Xml.Linq; using SwiftRuntimeLibrary; diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs index 7145f8ae963e..253f1ff6fede 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Xml.Linq; using SwiftReflector.ExceptionTools; -using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; namespace SwiftReflector.SwiftXmlReflection diff --git a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs index dc42d775b82e..16eb84cc9870 100644 --- a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs @@ -85,7 +85,7 @@ public string ReturnTypeName public FunctionDeclaration OverrideSurrogateFunction { get; set; } - public TypeSpec ReturnTypeSpec { get; private set; } + public TypeSpec ReturnTypeSpec { get; set; } public bool IsRequired { get; set; } public string ObjCSelector { get; set; } @@ -101,6 +101,7 @@ public string ReturnTypeName public bool IsUnavailable { get; set; } public bool IsConvenienceInit { get; set; } public bool IsVirtualClassMethod { get { return IsStatic && Access == Accessibility.Open; } } + public string MangledName { get; set; } public bool IsSubscript { get @@ -145,7 +146,7 @@ public TypeSpec PropertyType } } - public List> ParameterLists { get; private set; } + public List> ParameterLists { get; set; } public bool IsTypeSpecGeneric(ParameterItem item) { diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs index f0b53d84e973..bcbe5a14093e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs +++ b/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; -using SwiftReflector.IOUtils; namespace SwiftReflector.SwiftXmlReflection { diff --git a/src/SwiftReflector/IOUtils/IXElementConvertible.cs b/src/SwiftReflector/SwiftXmlReflection/IXElementConvertible.cs similarity index 84% rename from src/SwiftReflector/IOUtils/IXElementConvertible.cs rename to src/SwiftReflector/SwiftXmlReflection/IXElementConvertible.cs index 3e8f695527de..e20d3ee015ce 100644 --- a/src/SwiftReflector/IOUtils/IXElementConvertible.cs +++ b/src/SwiftReflector/SwiftXmlReflection/IXElementConvertible.cs @@ -3,11 +3,10 @@ using System.Xml.Linq; -namespace SwiftReflector.IOUtils +namespace SwiftReflector { public interface IXElementConvertible { XElement ToXElement(); } } - diff --git a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs index 1377e7f92de9..4178bc991f46 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; -using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; namespace SwiftReflector.SwiftXmlReflection diff --git a/src/SwiftReflector/SwiftXmlReflection/Member.cs b/src/SwiftReflector/SwiftXmlReflection/Member.cs index 6a3a4ddf1233..82a9c3d3fff8 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Member.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Member.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Xml.Linq; -using SwiftReflector.IOUtils; namespace SwiftReflector.SwiftXmlReflection { diff --git a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs index 5a24894f5f4f..abcc5f5fd417 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs @@ -38,7 +38,7 @@ public ModuleDeclaration MakeUnrooted() return unrooted; } - public List Declarations { get; private set; } + public List Declarations { get; set; } public List TypeAliases { get; private set; } public static ModuleDeclaration FromXElement(XElement elem, TypeDatabase typeDatabase) diff --git a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs index 3ef94e0bd034..15b3d046810e 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs @@ -2,12 +2,10 @@ // Licensed under the MIT License. using System; -using SwiftReflector.Inventory; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using SwiftReflector.ExceptionTools; -using SwiftReflector.IOUtils; using SwiftRuntimeLibrary; namespace SwiftReflector.SwiftXmlReflection diff --git a/src/SwiftReflector/SwiftXmlReflection/Reflector.cs b/src/SwiftReflector/SwiftXmlReflection/Reflector.cs deleted file mode 100644 index 7ee62ad61bec..000000000000 --- a/src/SwiftReflector/SwiftXmlReflection/Reflector.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Linq; -using System.Xml.Linq; -using System.Collections.Generic; -using SwiftReflector.ExceptionTools; -using System.IO; -using SwiftReflector.IOUtils; -using System.Diagnostics; -using System.Text; -using SwiftReflector.TypeMapping; - -namespace SwiftReflector.SwiftXmlReflection -{ - public class Reflector - { - public const double kCurrentVersion = 1.0; - const double kNextMajorVersion = 2.0; - - public static List FromXml(XDocument doc, TypeDatabase typeDatabase) - { - var xamreflect = doc.Element("xamreflect"); - var version = xamreflect.DoubleAttribute("version"); - - if (version < kCurrentVersion || version >= kNextMajorVersion) - { - throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 5, $"Unsupported xamreflect version {version}. Current is {kCurrentVersion}"); - } - - try - { - List modules = (from module in xamreflect.Descendants("module") - select ModuleDeclaration.FromXElement(module, typeDatabase)).ToList(); - return modules; - } - catch (Exception e) - { - throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 6, $"Error while reading XML reflection information: {e.Message}"); - } - } - - public static List FromXml(Stream stm, TypeDatabase typeDatabase) - { - var doc = XDocument.Load(stm); - return FromXml(doc, typeDatabase); - } - - public static List FromXmlFile(string path, TypeDatabase typeDatabase) - { - try - { - using (FileStream stm = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - return FromXml(stm, typeDatabase); - } - } - catch (Exception e) - { - throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 10, e, $"Failed to load xml file '{path}': {e.Message}"); - } - } - - public static List FromXml(string xmlText, TypeDatabase typeDatabase) - { - using (StringReader reader = new StringReader(xmlText)) - { - var doc = XDocument.Load(reader); - return FromXml(doc, typeDatabase); - } - } - - public static List FromModules(string executablePath, List searchDirectories, List modules, - IFileProvider provider, string outfileName, out string fullOutputPath) - { - fullOutputPath = PathToXmlFromModules(executablePath, searchDirectories, modules, provider, outfileName); - return FromXmlFile(fullOutputPath, null); - } - - public static string PathToXmlFromModules(string executablePath, List searchDirectories, List modules, - IFileProvider provider, string outfileName) - { - string fullOutputPath = provider.ProvideFileFor(outfileName); - try - { - return PathToXmlFromModules(executablePath, searchDirectories, modules, fullOutputPath); - } - finally - { - provider.NotifyFileDone(outfileName, fullOutputPath); - } - } - - // returns the path to the output XML file - public static string PathToXmlFromModules(string executablePath, List searchDirectories, List modules, - string outfilePath) - { - var args = BuildArgs(searchDirectories, modules, outfilePath); - ExecAndCollect.Run(executablePath, args); - return outfilePath; - } - - static string BuildArgs(List searchDirectories, List modules, string outfilePath) - { - StringBuilder sb = new StringBuilder(); - - // -xamreflect [-I dir]* -o outfilePath module1 [module2 ...] - - sb.Append("-xamreflect "); - - foreach (string s in searchDirectories) - { - sb.Append("-I "); - sb.Append(QuoteIfNeeded(s)); - } - if (sb.Length > 0) - sb.Append(" "); - sb.Append("-o ").Append(QuoteIfNeeded(outfilePath)); - sb.Append(" "); - foreach (string s in modules) - { - sb.Append(QuoteIfNeeded(s)); - } - return sb.ToString(); - } - - static string QuoteIfNeeded(string s) - { - throw new NotImplementedException(); - } - } -} - diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs index a72bcb2313ea..dc19bf211b7a 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs @@ -5,9 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; -using SwiftReflector.IOUtils; using SwiftReflector.ExceptionTools; -using SwiftReflector.Demangling; using SwiftReflector.TypeMapping; using System.Text; diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs index 682e7b551860..77f2f828242b 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs @@ -500,7 +500,7 @@ public class NamedTypeSpec : TypeSpec public NamedTypeSpec(string name) : base(TypeSpecKind.Named) { - name = SwiftInterfaceReflector.SwiftInterfaceReflector.UnTick(name); + // name = SwiftInterfaceReflector.SwiftInterfaceReflector.UnTick(name); // Hack filter. // For whatever reason, Any and AnyObject are not // strictly in the Swift module. But they are. diff --git a/src/SwiftReflector/TopLevelFunctionCompiler.cs b/src/SwiftReflector/TopLevelFunctionCompiler.cs deleted file mode 100644 index aca0ac95a416..000000000000 --- a/src/SwiftReflector/TopLevelFunctionCompiler.cs +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using SyntaxDynamo; -using SyntaxDynamo.CSLang; -using SwiftReflector.ExceptionTools; -using SwiftReflector.TypeMapping; -using SwiftReflector.SwiftXmlReflection; -using SwiftRuntimeLibrary; -using SwiftReflector.Demangling; - -namespace SwiftReflector -{ - public class TopLevelFunctionCompiler - { - TypeMapper typeMap; - Dictionary mangledToCSharp = new Dictionary(); - - public TopLevelFunctionCompiler(TypeMapper typeMap) - { - this.typeMap = typeMap; - } - - public CSProperty CompileProperty(string propertyName, CSUsingPackages packs, SwiftType swiftPropertyType, bool hasGetter, bool hasSetter, - CSMethodKind methodKind) - { - propertyName = typeMap.SanitizeIdentifier(propertyName); - NetTypeBundle propertyType = typeMap.MapType(swiftPropertyType, false); - - if (!(swiftPropertyType is SwiftGenericArgReferenceType)) - AddUsingBlock(packs, propertyType); - ICodeElement[] uselessLine = new ICodeElement[] { CSReturn.ReturnLine(new CSIdentifier("useless")) }; - - CSCodeBlock getterBlock = null; - if (hasGetter) - getterBlock = new CSCodeBlock(uselessLine); - CSCodeBlock setterBlock = null; - if (hasSetter) - setterBlock = new CSCodeBlock(uselessLine); - - CSProperty theProp = new CSProperty(propertyType.ToCSType(packs), methodKind, - new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); - if (getterBlock != null) - getterBlock.Clear(); - if (setterBlock != null) - setterBlock.Clear(); - - return theProp; - } - - public CSProperty CompileProperty(CSUsingPackages packs, string propertyName, - FunctionDeclaration getter, FunctionDeclaration setter, CSMethodKind methodKind = CSMethodKind.None) - { - var swiftPropertyType = GetPropertyType(getter, setter); - NetTypeBundle propertyType = null; - if (TypeMapper.IsCompoundProtocolListType(swiftPropertyType)) - { - propertyType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList); - } - else - { - propertyType = typeMap.MapType(getter, swiftPropertyType, false, true); - } - propertyName = propertyName ?? typeMap.SanitizeIdentifier(getter != null ? getter.PropertyName : setter.PropertyName); - bool isSubscript = getter != null ? getter.IsSubscript : - setter.IsSubscript; - - if (!getter.IsTypeSpecGeneric(swiftPropertyType)) - AddUsingBlock(packs, propertyType); - - var uselessLine = new ICodeElement[] { CSReturn.ReturnLine(new CSIdentifier("useless")) }; - - CSCodeBlock getterBlock = null; - if (getter != null) - getterBlock = new CSCodeBlock(uselessLine); - CSCodeBlock setterBlock = null; - if (setter != null) - setterBlock = new CSCodeBlock(uselessLine); - - CSProperty theProp = null; - var csPropType = propertyType.ToCSType(packs); - if (isSubscript) - { - List swiftParms = null; - if (getter != null) - { - swiftParms = getter.ParameterLists[1]; - } - else - { - swiftParms = setter.ParameterLists[1].Skip(1).ToList(); - } - var args = typeMap.MapParameterList(getter, swiftParms, false, false, null, null, packs); - args.ForEach(a => AddUsingBlock(packs, a.Type)); - - var csParams = - new CSParameterList( - args.Select(a => - new CSParameter(a.Type.ToCSType(packs), - new CSIdentifier(a.Name), a.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null))); - theProp = new CSProperty(csPropType, methodKind, CSVisibility.Public, getterBlock, - CSVisibility.Public, setterBlock, csParams); - - - } - else - { - theProp = new CSProperty(csPropType, methodKind, - new CSIdentifier(propertyName), CSVisibility.Public, getterBlock, CSVisibility.Public, setterBlock); - } - // if (propertyType.Throws) - // DecoratePropWithThrows (theProp, packs); - if (getterBlock != null) - getterBlock.Clear(); - if (setterBlock != null) - setterBlock.Clear(); - - return theProp; - } - - SwiftType GetPropertyType(SwiftPropertyType getter, SwiftPropertyType setter) - { - if (getter != null) - { - return getter.ReturnType; - } - if (setter != null) - { - if (setter.IsSubscript) - { - return ((SwiftTupleType)setter.Parameters).Contents[0]; - } - else - { - return setter.Parameters; - } - } - throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 0, "neither getter nor setter provided"); - } - - TypeSpec GetPropertyType(FunctionDeclaration getter, FunctionDeclaration setter) - { - if (getter != null) - { - return getter.ReturnTypeSpec; - } - if (setter != null) - { - // same for subscript and prop - return setter.ParameterLists[1][0].TypeSpec; - } - throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 1, "neither getter nor setter provided"); - } - - public CSMethod CompileMethod(FunctionDeclaration func, CSUsingPackages packs, string libraryPath, - string mangledName, string functionName, bool isPinvoke, bool isFinal, bool isStatic) - { - isStatic = isStatic || func.IsExtension; - var extraProtoArgs = new CSGenericTypeDeclarationCollection(); - var extraProtoConstraints = new CSGenericConstraintCollection(); - var args = typeMap.MapParameterList(func, func.ParameterLists.Last(), isPinvoke, false, extraProtoArgs, extraProtoConstraints, packs); - if (isPinvoke && func.ParameterLists.Count > 1) - { - var metaTypeBundle = new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, false, EntityType.None); - NetParam p = new NetParam("metaClass", metaTypeBundle); - args.Add(p); - } - - NetTypeBundle returnType = null; - if (func.ReturnTypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) - { - returnType = new NetTypeBundle("System", "object", false, false, EntityType.ProtocolList); - } - else - { - returnType = typeMap.MapType(func, func.ReturnTypeSpec, isPinvoke, true); - } - - string funcName = functionName ?? typeMap.SanitizeIdentifier(func.Name); - - if (isPinvoke && !mangledToCSharp.ContainsKey(mangledName)) - mangledToCSharp.Add(mangledName, funcName); - - args.ForEach(a => AddUsingBlock(packs, a.Type)); - - if (returnType != null && !(func.IsTypeSpecGeneric(func.ReturnTypeSpec))) - AddUsingBlock(packs, returnType); - - CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType(packs); - - var csParams = new CSParameterList(); - foreach (var arg in args) - { - var csType = arg.Type.ToCSType(packs); - // if (arg.Type.Throws) - // csType = DecorateTypeWithThrows (csType, packs); - csParams.Add(new CSParameter(csType, new CSIdentifier(arg.Name), - arg.Type.IsReference ? CSParameterKind.Ref : CSParameterKind.None, null)); - - } - - if (isPinvoke) - { - // AddExtraGenericArguments (func, csParams, packs); - var pinvoke = CSMethod.InternalPInvoke(csReturnType, funcName, libraryPath, - mangledName.Substring(1), csParams); - if (csReturnType is CSSimpleType simple && simple.Name == "bool") - { - CSAttribute.ReturnMarshalAsI1.AttachBefore(pinvoke); - } - return pinvoke; - } - else - { - CSMethod retval = null; - if (func.IsConstructor) - { - retval = CSMethod.PublicConstructor(funcName, csParams, new CSCodeBlock()); - } - else - { - if (isFinal) - retval = new CSMethod(CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.None, csReturnType, new CSIdentifier(funcName), - csParams, new CSCodeBlock()); - else - retval = new CSMethod(CSVisibility.Public, isStatic ? CSMethodKind.Static : CSMethodKind.Virtual, csReturnType, new CSIdentifier(funcName), - csParams, new CSCodeBlock()); - } - if (extraProtoArgs.Count > 0) - { - retval.GenericParameters.AddRange(extraProtoArgs); - retval.GenericConstraints.AddRange(extraProtoConstraints); - } - return retval; - } - } - - public static bool GenericArgumentIsReferencedByGenericClassInParameterList(SwiftBaseFunctionType func, GenericArgument arg) - { - foreach (SwiftType st in func.EachParameter) - { - if (st is SwiftUnboundGenericType) - { - var sut = (SwiftUnboundGenericType)st; - if (!sut.DependentType.IsClass) - continue; - // there appears to be a bug in the swift compiler that doesn't accept certain - // generic patterns that will ensure that sut.Arguments won't ever have more than 1 - // element in it in cases that we care about, but what the heck - do the general case. - foreach (GenericArgument gen in sut.Arguments) - { - if (gen.Depth == arg.Depth && gen.Index == arg.Index) - return true; - } - } - } - return false; - } - - public static bool GenericDeclarationIsReferencedByGenericClassInParameterList(FunctionDeclaration func, GenericDeclaration genDecl, TypeMapper mapper) - { - foreach (ParameterItem pi in func.ParameterLists.Last()) - { - if (pi.TypeSpec is NamedTypeSpec) - { - // this inner section should probably be recursive, but I was unable to - // even test if SomeClass> is valid because the swift compiler - // wouldn't take it. - var ns = (NamedTypeSpec)pi.TypeSpec; - if (ns.ContainsGenericParameters) - { - Entity en = mapper.GetEntityForTypeSpec(ns); - if (en != null && en.EntityType == EntityType.Class) - { - foreach (TypeSpec genTS in ns.GenericParameters) - { - var nsGen = genTS as NamedTypeSpec; - if (nsGen != null) - { - if (genDecl.Name == nsGen.Name) - return true; - } - } - } - } - } - } - return false; - } - - public string CSMethodForMangledName(string mangledName) - { - return mangledToCSharp[SwiftRuntimeLibrary.Exceptions.ThrowOnNull(mangledName, "mangledName")]; - } - - static void AddUsingBlock(CSUsingPackages packs, NetTypeBundle type) - { - if (type.IsVoid || String.IsNullOrEmpty(type.NameSpace)) - return; - packs.AddIfNotPresent(type.NameSpace); - } - - - int TotalProtocolConstraints(GenericArgument gen) - { - int count = 0; - foreach (var constraint in gen.Constraints) - { - var ct = constraint as SwiftClassType; - if (ct == null) - throw ErrorHelper.CreateError(ReflectorError.kCompilerBase + 11, $"Expected a SwiftClassType for constraint, but got {constraint.GetType().Name}."); - if (ct.EntityKind == MemberNesting.Protocol) - count++; - } - return count; - } - int TotalProtocolConstraints(GenericDeclaration gen) - { - int count = 0; - foreach (BaseConstraint constraint in gen.Constraints) - { - var inh = constraint as InheritanceConstraint; - if (inh == null) - continue; - // throw ErrorHelper.CreateError (ReflectorError.kCompilerBase + 12, $"Expected a SwiftClassType for constraint, but got {constraint.GetType ().Name}."); - var en = typeMap.GetEntityForTypeSpec(inh.InheritsTypeSpec); - if (en.EntityType == EntityType.Protocol) - count++; - } - return count; - } - - bool IsObjCStruct(NetParam ntb, SwiftType parmType) - { - if (ntb.Type.Entity != EntityType.Struct) - return false; - - // if the Entity is EntityType.Struct, it's guaranteed to be a SwiftClassType - var structType = parmType as SwiftClassType; - var entity = typeMap.GetEntityForSwiftClassName(structType.ClassName.ToFullyQualifiedName(true)); - if (entity == null) - throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 5, $"Unable to get the entity for struct type {structType.ClassName.ToFullyQualifiedName(true)}"); - return entity.Type.IsObjC; - } - - bool IsObjCStruct(TypeSpec typeSpec) - { - if (!(typeSpec is NamedTypeSpec)) - return false; - var entity = typeMap.GetEntityForTypeSpec(typeSpec); - if (entity == null) - throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 6, $"Unable to get the entity for type {typeSpec.ToString()}"); - return entity.IsObjCStruct; - } - - void RemapSwiftClosureRepresensation(List args) - { - for (int i = 0; i < args.Count; i++) - { - if (args[i].Type.FullName == "SwiftRuntimeLibrary.SwiftClosureRepresentation") - { - var bundle = new NetTypeBundle("SwiftRuntimeLibrary", "BlindSwiftClosureRepresentation", false, args[i].Type.IsReference, EntityType.Closure); - args[i] = new NetParam(args[i].Name, bundle); - } - } - } - - public static bool TypeSpecCanThrow(TypeSpec t, bool isPinvoke) - { - if (t == null) - return false; - return !isPinvoke && t is ClosureTypeSpec cl && cl.Throws; - } - } -} - diff --git a/src/SwiftReflector/TypeMapping/Entity.cs b/src/SwiftReflector/TypeMapping/Entity.cs index e345a52574a4..cb8d7a0c5560 100644 --- a/src/SwiftReflector/TypeMapping/Entity.cs +++ b/src/SwiftReflector/TypeMapping/Entity.cs @@ -3,7 +3,6 @@ using System; using SwiftReflector.SwiftXmlReflection; -using SwiftReflector.IOUtils; using System.Xml.Linq; namespace SwiftReflector.TypeMapping diff --git a/src/SwiftReflector/TypeMapping/TypeDatabase.cs b/src/SwiftReflector/TypeMapping/TypeDatabase.cs index b06d8f4da621..8e82d15d3192 100644 --- a/src/SwiftReflector/TypeMapping/TypeDatabase.cs +++ b/src/SwiftReflector/TypeMapping/TypeDatabase.cs @@ -48,11 +48,19 @@ public class TypeDatabase Dictionary swiftNamesToNetNames = new Dictionary(); Dictionary modules = new Dictionary(); + public IEnumerable ModuleNames { get { return modules.Keys; } } - public TypeDatabase() + public int Count { + get + { + return modules.Select(m => m.Value.Count).Sum(); + } } + public TypeDatabase() + { + } public DotNetName DotNetNameForSwiftName(string swiftName) { @@ -110,47 +118,6 @@ public Entity TryGetEntityForSwiftName(string swiftName) } } - public int Count - { - get - { - return modules.Select(m => m.Value.Count).Sum(); - } - } - - public bool Contains(string swiftClassName) - { - return EntityForSwiftName(swiftClassName) != null; - } - - public bool Contains(SwiftClassName swiftClassName) - { - return Contains(swiftClassName.ToFullyQualifiedName(true)); - } - - public bool Contains(DotNetName name) - { - return netNamesToSwiftNames.ContainsKey(name); - } - - public IEnumerable ModuleNames { get { return modules.Keys; } } - - public void Update(Entity e) - { - var old = EntityForSwiftName(e.Type.ToFullyQualifiedName(true)); - if (old == null) - { - Add(e); - } - else - { - old.EntityType = e.EntityType; - old.SharpNamespace = e.SharpNamespace; - old.SharpTypeName = e.SharpTypeName; - old.Type = e.Type; - } - } - public void Add(Entity e) { if (e.Type != null && !e.Type.IsUnrooted) @@ -192,81 +159,6 @@ public IEnumerable TypeAliasesForModule(string moduleName) return Enumerable.Empty(); } - public void Write(string file, IEnumerable modules) - { - using (FileStream stm = new FileStream(Exceptions.ThrowOnNull(file, nameof(file)), FileMode.Create)) - { - Write(stm, modules); - } - } - - public void Write(Stream stm, IEnumerable modules) - { - Write(stm, modules.Select(s => EntitiesForModule(s)).SelectMany(x => x).Select(entity => entity.ToXElement())); - } - - IEnumerable GatherXElements(IEnumerable modules) - { - foreach (var modName in modules) - { - foreach (var entity in EntitiesForModule(modName)) - { - yield return entity.ToXElement(); - } - foreach (var op in OperatorsForModule(modName)) - { - yield return op.ToXElement(); - } - foreach (var alias in TypeAliasesForModule(modName)) - { - yield return alias.ToXElement(); - } - } - } - - public void Write(string file, string module) - { - using (FileStream stm = new FileStream(Exceptions.ThrowOnNull(file, "file"), FileMode.Create)) - { - Write(stm, module); - } - } - - public void Write(Stream stm, string module) - { - Write(stm, EntitiesForModule(module).Select(entity => entity.ToXElement())); - } - - void Write(Stream stm, IEnumerable entities) - { - var entityList = new XElement("entities", entities); - var db = new XElement("xamtypedatabase", - new XAttribute("version", 1.0), - entityList); - var doc = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - db); - doc.Save(stm); - } - - public bool Merge(TypeDatabase other, ErrorHandling errors) - { - var initialErrorCount = errors.ErrorCount; - foreach (var mod in other.modules.Values) - { - foreach (var entity in mod.Values) - { - AddEntity(entity, errors); - } - foreach (var op in mod.Operators) - { - AddOperator(op); - } - } - return initialErrorCount != errors.ErrorCount; - } - - public ErrorHandling Read(List files) { var errors = new ErrorHandling(); diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/TypeMapping/TypeMapper.cs index 30b147a7d236..3437d9691e45 100644 --- a/src/SwiftReflector/TypeMapping/TypeMapper.cs +++ b/src/SwiftReflector/TypeMapping/TypeMapper.cs @@ -7,7 +7,6 @@ using System.Text; using System.Globalization; using SwiftReflector.ExceptionTools; -using SwiftReflector.Inventory; using SwiftReflector.SwiftXmlReflection; using System.IO; using SyntaxDynamo.CSLang; @@ -15,6 +14,42 @@ namespace SwiftReflector.TypeMapping { + public class CSKeywords + { + static HashSet keyWords; + static string[] keyArr = new string[] { + "abstract", "as", "base", "bool", "break", "byte", + "case", "catch", "char", "checked", "class", "const", + "continue", "decimal", "default", "delegate", "do", + "double", "else", "enum", "event", "explicit", "extern", + "false", "finally", "fixed", "float", "for", "foreach", + "goto", "if", "implicit", "in", "int", "interface", "internal", + "is", "lock", "long", "namespace", "new", "null", "object", + "operator", "out", "override", "params", "private", "protected", + "public", "readonly", "ref", "return", "sbyte", "sealed", "short", + "sizeof", "stackalloc", "static", "string", "struct", "switch", + "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", + "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", + "add", "alias", "ascending", "async", "await", "descending", "dynamic", + "from", "get", "global", "group", "into", "join", "let", "orderby", + "partial", "remove", "select", "set", "value", "var", "where", "yield" + }; + static CSKeywords() + { + keyWords = new HashSet(); + foreach (string s in keyArr) + { + keyWords.Add(s); + } + } + + public static bool IsKeyword(string s) + { + Exceptions.ThrowOnNull(s, "s"); + return keyWords.Contains(s); + } + } + public class TypeMapper { public TypeDatabase TypeDatabase { get; private set; } @@ -41,88 +76,6 @@ public void AddTypeDatabase(string fileName) throw new AggregateException(errors.Errors.Select((v) => v.Exception)); } - DotNetName PreRegisterEntityName(string swiftClassName, EntityType entityKind) - { - - var en = TypeDatabase.EntityForSwiftName(swiftClassName); - if (en != null) - return en.GetFullType(); - - - var netClassName = MakeDotNetClassName(swiftClassName, entityKind == EntityType.Protocol); - - en = new Entity - { - SharpNamespace = netClassName.Namespace, - SharpTypeName = netClassName.TypeName, - Type = new ShamDeclaration(swiftClassName, entityKind), - EntityType = entityKind - }; - TypeDatabase.Add(en); - return netClassName; - } - - public bool IsRegistered(SwiftClassName cl) - { - return TypeDatabase.Contains(cl); - } - - public bool IsRegistered(string fullyQualifiedName) - { - return TypeDatabase.Contains(fullyQualifiedName); - } - - public DotNetName PreRegisterEntityName(SwiftClassName cl) - { - var swiftClassName = cl.ToFullyQualifiedName(); - var entity = EntityType.None; - // FIXME - if (cl.IsClass) - entity = EntityType.Class; - else if (cl.IsStruct) - entity = EntityType.Struct; - else if (cl.IsEnum) - entity = EntityType.Enum; - else - { - throw new NotImplementedException(); - } - return PreRegisterEntityName(swiftClassName, entity); - } - - public DotNetName GetDotNetNameForSwiftClassName(SwiftClassName cl) - { - return TypeDatabase.EntityForSwiftName(cl).GetFullType(); - } - - public DotNetName GetDotNetNameForTypeSpec(TypeSpec spec) - { - var named = spec as NamedTypeSpec; - if (named == null) - return null; - return GetDotNetNameForSwiftClassName(named.Name); - } - - public DotNetName GetDotNetNameForSwiftClassName(string fullyQualifiedName) - { - var entity = TypeDatabase.EntityForSwiftName(fullyQualifiedName); - if (entity == null) - return null; - return entity.GetFullType(); - } - - public EntityType GetEntityTypeForSwiftClassName(string fullyQualifiedName) - { - var ent = TypeDatabase.EntityForSwiftName(fullyQualifiedName); - return ent != null ? ent.EntityType : EntityType.None; - } - - public EntityType GetEntityTypeForDotNetName(DotNetName netClassName) - { - var ent = TypeDatabase.EntityForDotNetName(netClassName); - return ent != null ? ent.EntityType : EntityType.None; - } - public Entity GetEntityForSwiftClassName(string fullyQualifiedName) { return TypeDatabase.EntityForSwiftName(fullyQualifiedName); @@ -170,191 +123,6 @@ public EntityType GetEntityTypeForTypeSpec(TypeSpec spec) throw new ArgumentOutOfRangeException(spec.GetType().Name); } - public Entity GetEntityForDotNetName(DotNetName netName) - { - return TypeDatabase.EntityForDotNetName(netName); - } - - public DotNetName RegisterClass(TypeDeclaration t) - { - t = t.MakeUnrooted(); - var isProtocol = false; - // FIXME - var entity = EntityType.None; - // don't reorder - until I change this, ProtocolDeclaration extends from ClassDeclaration - if (t is ProtocolDeclaration) - { - entity = EntityType.Protocol; - isProtocol = true; - } - else if (t is ClassDeclaration) - { - entity = EntityType.Class; - } - else if (t is StructDeclaration) - { - entity = EntityType.Struct; - } - else - { - EnumDeclaration eDecl = t as EnumDeclaration; - entity = (eDecl.IsTrivial || (eDecl.IsIntegral && eDecl.IsHomogenous && eDecl.Inheritance.Count == 0)) ? EntityType.TrivialEnum : EntityType.Enum; - } - var sharpName = MakeDotNetClassName(t.ToFullyQualifiedName(true), isProtocol); - - var en = new Entity - { - SharpNamespace = sharpName.Namespace, - SharpTypeName = sharpName.TypeName, - Type = t, - EntityType = entity - }; - - TypeDatabase.Update(en); - return sharpName; - } - - public IEnumerable RegisterClasses(IEnumerable decl) - { - var allReg = new List(); - foreach (TypeDeclaration cl in decl) - { - DotNetName reg = RegisterClass(cl); - allReg.Add(reg); - } - return allReg; - } - - DotNetName MakeDotNetClassName(string fullyQualifiedName, bool isProtocol) - { - var parts = fullyQualifiedName.Split('.'); - var sb = new StringBuilder(); - var namesp = MapModuleToNamespace(parts[0]); - for (int i = 1; i < parts.Length; i++) - { - if (i > 1) - sb.Append('.'); - if (isProtocol && i == parts.Length - 1) - sb.Append('I'); - sb.Append(SanitizeIdentifier(parts[i])); - } - return new DotNetName(namesp, sb.ToString()); - } - - string MakeDotNetClassName(SwiftClassName name) - { - var sb = new StringBuilder(); - var namesp = MapModuleToNamespace(name.Module); - sb.Append(namesp); - foreach (SwiftName sn in name.NestingNames) - { - sb.Append('.'); - sb.Append(SanitizeIdentifier(sn.Name)); - } - return sb.ToString(); - } - - public string MapModuleToNamespace(SwiftName name) - { - string finalName = null; - finalName = UserModuleMap(name); - if (finalName == null) - { - finalName = SanitizeIdentifier(name.Name); - } - return finalName; - } - - public string MapModuleToNamespace(string name) - { - string finalName = null; - finalName = UserModuleMap(name); - if (finalName == null) - { - finalName = SanitizeIdentifier(name); - } - return finalName; - } - - - string UserModuleMap(SwiftName name) - { - return null; - } - - string UserModuleMap(string name) - { - return null; - } - - static UnicodeCategory[] validStarts = { - UnicodeCategory.UppercaseLetter, - UnicodeCategory.LowercaseLetter, - UnicodeCategory.TitlecaseLetter, - UnicodeCategory.ModifierLetter, - UnicodeCategory.OtherLetter, - UnicodeCategory.LetterNumber - }; - - static bool ValidIdentifierStart(UnicodeCategory cat) - { - return validStarts.Contains(cat); - } - - static UnicodeCategory[] validContent = { - UnicodeCategory.DecimalDigitNumber, - UnicodeCategory.ConnectorPunctuation, - UnicodeCategory.Format - }; - - static bool ValidIdentifierContent(UnicodeCategory cat) - { - return ValidIdentifierStart(cat) || validContent.Contains(cat); - } - - static bool IsValidIdentifier(int position, UnicodeCategory cat) - { - if (position == 0) - return ValidIdentifierStart(cat); - else - return ValidIdentifierContent(cat); - } - - static bool IsHighUnicode(string s) - { - // Steve says: this is arbitrary, but it solves an issue - // with mcs and csc not liking certain Ll and Lu class - // unicode characters (for now). - // Open issue: https://github.com/dotnet/roslyn/issues/27986 - var encoding = Encoding.UTF32; - var bytes = encoding.GetBytes(s); - var utf32Value = BitConverter.ToUInt32(bytes, 0); - return utf32Value > 0xffff; - } - - public string SanitizeIdentifier(string name) - { - var sb = new StringBuilder(); - - var characterEnum = StringInfo.GetTextElementEnumerator(name); - while (characterEnum.MoveNext()) - { - string c = characterEnum.GetTextElement(); - int i = characterEnum.ElementIndex; - - var cat = CharUnicodeInfo.GetUnicodeCategory(name, i); - - if (IsValidIdentifier(i, cat) && !IsHighUnicode(c)) - sb.Append(i == 0 && cat == UnicodeCategory.LowercaseLetter ? c.ToUpper() : c); - else - sb.Append(unicodeMapper.MapToUnicodeName(c)); - } - - if (CSKeywords.IsKeyword(sb.ToString())) - sb.Append('_'); - return sb.ToString(); - } - static string ComeUpWithAName(string given, string typeName, int index) { if (String.IsNullOrEmpty(given)) @@ -412,63 +180,19 @@ static List SanitizeParamNames(List parms) return outlist; } - public List GetLineage(SwiftUncurriedFunctionType uft) - { - var lineage = new List(); - if (uft != null) - { - var theClass = uft.UncurriedParameter as SwiftClassType; - if (theClass == null) - { - var meta = uft.UncurriedParameter as SwiftMetaClassType; - if (meta == null) - throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 17, $"Expected a SwiftClassType or a SwiftMetaClassType as the uncurried parameter in a function, but got {uft.UncurriedParameter.GetType().Name}."); - theClass = meta.Class; - } - var sb = new StringBuilder().Append(theClass.ClassName.Module.Name); - foreach (SwiftName name in theClass.ClassName.NestingNames) - { - sb.Append('.').Append(name.Name); - lineage.Add(sb.ToString()); - } - } - return lineage; - } - - internal object GetEntityForTypeSpec(object inheritsTypeSpec) - { - throw new NotImplementedException(); - } - - NetTypeBundle RecastToReference(BaseDeclaration typeContext, NetTypeBundle netBundle, TypeSpec theElem, bool structsAndEnumsAreAlwaysRefs) { - if (typeContext.IsTypeSpecGenericReference(theElem) || typeContext.IsProtocolWithAssociatedTypesFullPath(theElem as NamedTypeSpec, this)) - return netBundle; - if (theElem is ClosureTypeSpec) - return netBundle; - if (theElem is ProtocolListTypeSpec) - return new NetTypeBundle(netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); var entity = GetEntityForTypeSpec(theElem); if (entity != null && (entity.IsObjCStruct || entity.IsObjCEnum) && netBundle.IsReference) return netBundle; if (theElem.IsInOut && netBundle.Entity != EntityType.Struct) return netBundle; - var objcStructType = ObjCStructOrEnumReferenceType(typeContext, theElem as NamedTypeSpec); if (objcStructType != null) { return MapType(typeContext, objcStructType, true); } - var isStructOrEnum = netBundle.Entity == EntityType.Struct || netBundle.Entity == EntityType.Enum; - if (isStructOrEnum) - { - if (MustForcePassByReference(typeContext, theElem) || netBundle.Entity == EntityType.Enum || structsAndEnumsAreAlwaysRefs) - { - return new NetTypeBundle("System", "IntPtr", netBundle.IsScalar, false, netBundle.Entity); - } - } - else if (entity != null && entity.EntityType == EntityType.Protocol && !entity.IsObjCProtocol) + if (entity != null && entity.EntityType == EntityType.Protocol && !entity.IsObjCProtocol) { return new NetTypeBundle(netBundle.NameSpace, netBundle.Type, netBundle.IsScalar, true, netBundle.Entity); } @@ -478,7 +202,7 @@ NetTypeBundle RecastToReference(BaseDeclaration typeContext, NetTypeBundle netBu NetParam MapParameterItem(BaseDeclaration context, ParameterItem parameter, int index, bool isPinvoke, bool structsAndEnumsAreAlwaysRefs) { - var theType = parameter.TypeSpec; //parameter.IsInOut && !parameter.TypeSpec.IsInOut ? parameter.TypeSpec.WithInOutSet () : parameter.TypeSpec; + var theType = parameter.TypeSpec; var t = MapType(context, theType, isPinvoke); if (isPinvoke) { @@ -494,95 +218,15 @@ NetParam MapParameterItem(BaseDeclaration context, ParameterItem parameter, int var parms = new List(); for (int i = 0; i < st.Count; i++) { - if (st[i].TypeSpec is ProtocolListTypeSpec plitem && !isPinvoke) - { - var genprotoName = new CSIdentifier($"TProto{i}"); - extraProtocolTypes.Add(new CSGenericTypeDeclaration(genprotoName)); - extraProtocolContstraints.Add(new CSGenericConstraint(genprotoName, ToConstraintIDs(context, plitem.Protocols.Keys, isPinvoke))); - var netBundle = new NetTypeBundle("", genprotoName.Name, false, st[i].IsInOut, EntityType.ProtocolList); - - parms.Add(ToNamedParam(st[i], netBundle, i)); - } - else - { - var entity = !context.IsTypeSpecGeneric(st[i].TypeSpec) ? GetEntityForTypeSpec(st[i].TypeSpec) : null; - if (entity != null && entity.EntityType == EntityType.Protocol && !isPinvoke) - { - var proto = entity.Type as ProtocolDeclaration; - // if (proto.HasDynamicSelf) { - // extraProtocolTypes.Add (new CSGenericTypeDeclaration (BindingsCompiler.kGenericSelf)); - // var csProtoBundle = MapType (context, st [i].TypeSpec, isPinvoke); - // var csType = csProtoBundle.ToCSType (use); - // extraProtocolContstraints.Add (new CSGenericConstraint (BindingsCompiler.kGenericSelf, new CSIdentifier (csType.ToString ()))); - // } - } - + var entity = GetEntityForTypeSpec(st[i].TypeSpec); parms.Add(MapParameterItem(context, st[i], i, isPinvoke, structsAndEnumsAreAlwaysRefs)); - } } return SanitizeParamNames(parms); } - public IEnumerable ToConstraintIDs(BaseDeclaration context, IEnumerable types, bool isPinvoke) - { - foreach (var ns in types) - { - var cstype = MapType(context, ns, isPinvoke); - yield return new CSIdentifier(cstype.ToString()); - } - } - - public static bool IsCompoundProtocolListType(SwiftType st) - { - return st is SwiftProtocolListType pt && pt.Protocols.Count > 1; - } - - public static bool IsCompoundProtocolListType(TypeSpec sp) - { - return sp is ProtocolListTypeSpec pl && pl.Protocols.Count > 1; - } - - public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = false) - { - if (IsCompoundProtocolListType(st) && !isPinvoke) - throw new NotImplementedException("Check for a protocol list type first because you need to promote the method to a generic"); - switch (st.Type) - { - case CoreCompoundType.Scalar: - return ToScalar((SwiftBuiltInType)st); - case CoreCompoundType.Tuple: - return ToTuple((SwiftTupleType)st, isPinvoke); - case CoreCompoundType.MetaClass: - return ToMetaClass((SwiftMetaClassType)st); - case CoreCompoundType.Class: - if (st.IsStruct) - return ToStruct((SwiftClassType)st, isPinvoke); - else if (st.IsClass) - return ToClass((SwiftClassType)st, isPinvoke); - else if (st.IsEnum) - return ToEnum((SwiftClassType)st, isPinvoke, isReturnValue); - else if (st.IsProtocol) - return ToProtocol((SwiftClassType)st, isPinvoke); - else - throw new NotImplementedException(); - case CoreCompoundType.ProtocolList: - return ToProtocol((SwiftProtocolListType)st, isPinvoke); - case CoreCompoundType.BoundGeneric: - return ToBoundGeneric((SwiftBoundGenericType)st, isPinvoke); - case CoreCompoundType.GenericReference: - return ToGenericReference((SwiftGenericArgReferenceType)st, isPinvoke); - case CoreCompoundType.Function: - return ToClosure((SwiftBaseFunctionType)st, isPinvoke, isReturnValue); - default: - throw new NotImplementedException(); - } - } - public NetTypeBundle MapType(BaseDeclaration context, TypeSpec spec, bool isPinvoke, bool isReturnValue = false, Tuple selfDepthIndex = null) { - if (IsCompoundProtocolListType(spec) && !isPinvoke) - throw new NotImplementedException("Check for a protocol list type first because you need to promote the method to a generic"); switch (spec.Kind) { case TypeSpecKind.Named: @@ -591,86 +235,6 @@ public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = { return ToScalar(named.Name, spec.IsInOut); } - if (context.IsProtocolWithAssociatedTypesFullPath(named, this)) - { - if (isPinvoke) - { - return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); - } - else - { - var assocType = context.AssociatedTypeDeclarationFromGenericWithFullPath(named, this); - var owningProtocol = context.OwningProtocolFromGenericWithFullPath(named, this); - return new NetTypeBundle(owningProtocol, assocType, false); - } - } - else if (context.IsEqualityConstrainedByAssociatedType(named, this)) - { - if (isPinvoke) - { - return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); - } - else - { - var assocType = context.AssociatedTypeDeclarationFromConstrainedGeneric(named, this); - var owningProtocol = context.OwningProtocolFromConstrainedGeneric(named, this); - return new NetTypeBundle(owningProtocol, assocType, false); - } - } - else if (context.IsTypeSpecGeneric(spec) && (!spec.ContainsGenericParameters || isPinvoke)) - { - if (context.IsTypeSpecGenericMetatypeReference(spec)) - { - return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, spec.IsInOut, EntityType.None); - } - else - { - if (isPinvoke) - { - var isPAT = context.GetConstrainedProtocolWithAssociatedType(named, this) != null; - var isInOut = isPAT ? false : named.IsInOut; - return new NetTypeBundle("System", "IntPtr", false, isInOut, EntityType.None); - } - else - { - var depthIndex = context.GetGenericDepthAndIndex(spec); - return new NetTypeBundle(depthIndex.Item1, depthIndex.Item2); - } - } - } - else if (context.IsTypeSpecAssociatedType(named)) - { - if (isPinvoke) - { - return new NetTypeBundle("System", "IntPtr", false, named.IsInOut, EntityType.None); - } - else - { - if (named.ContainsGenericParameters) - { - var en = TypeDatabase.EntityForSwiftName(named.Name); - var retval = new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); - foreach (var gen in named.GenericParameters) - { - var genNtb = MapType(context, gen, isPinvoke, isReturnValue); - retval.GenericTypes.Add(genNtb); - } - return retval; - } - else - { - var assocType = context.AssociatedTypeDeclarationFromNamedTypeSpec(named); - return new NetTypeBundle(context.AsProtocolOrParentAsProtocol(), assocType, named.IsInOut); - } - } - } - // else if (named.Name == "Self") { - // if (isPinvoke) { - // return new NetTypeBundle ("System", "IntPtr", false, named.IsInOut, EntityType.None); - // } else { - // return new NetTypeBundle (BindingsCompiler.kGenericSelfName, named.IsInOut); - // } - // } else { Entity en = TypeDatabase.EntityForSwiftName(named.Name); @@ -680,56 +244,6 @@ public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = { switch (en.EntityType) { - case EntityType.Class: - case EntityType.Enum: - case EntityType.Tuple: - if (en.IsObjCEnum) - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); - case EntityType.TrivialEnum: - return ToTrivialEnumType(en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, spec.IsInOut); - case EntityType.Protocol: - if (en.IsObjCProtocol) - { - return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); - } - else - { - if (spec is ProtocolListTypeSpec protocolList) - { - var container = $"SwiftExistentialContainer{protocolList.Protocols.Count}"; - return new NetTypeBundle("SwiftRuntimeLibrary", container, false, true, EntityType.None); - } - else - { - return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, true, - EntityType.None); - } - } - case EntityType.Struct: - var protocolListRef = GetBoundProtocolListType(named); - if (protocolListRef != null) - { - var container = $"SwiftExistentialContainer{protocolListRef.Protocols.Count}"; - return new NetTypeBundle("SwiftRuntimeLibrary", container, false, true, EntityType.None); - - } - en = MapToObjCStructOrEnumReference(context, named) ?? en; - if (en.IsObjCStruct || en.IsObjCEnum) - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - en = MapToScalarReference(context, named) ?? en; - if (en.EntityType == EntityType.Scalar) - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - else - { - return new NetTypeBundle("System", "IntPtr", false, spec.IsInOut, EntityType.None); - } case EntityType.Scalar: return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); default: @@ -739,28 +253,6 @@ public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = else { var retval = new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, spec.IsInOut, en.EntityType); - if (en.EntityType == EntityType.Protocol && en.Type is ProtocolDeclaration proto) - { - // if (proto.HasDynamicSelf) { - // if (selfDepthIndex != null) { - // retval.GenericTypes.Add (new NetTypeBundle (selfDepthIndex.Item1, selfDepthIndex.Item2)); - // } else { - // retval.GenericTypes.Add (new NetTypeBundle (BindingsCompiler.kGenericSelfName, spec.IsInOut)); - // } - // } - foreach (var assoc in proto.AssociatedTypes) - { - var genMap = new NetTypeBundle(proto, assoc, spec.IsInOut); - retval.GenericTypes.Add(genMap); - } - } - else - { - foreach (var gen in spec.GenericParameters) - { - retval.GenericTypes.Add(MapType(context, gen, isPinvoke)); - } - } return retval; } } @@ -786,73 +278,11 @@ public NetTypeBundle MapType(SwiftType st, bool isPinvoke, bool isReturnValue = return NetTypeBundle.Void; var tupTypes = tuple.Elements.Select(ts => MapType(context, ts, isPinvoke)).ToList(); return new NetTypeBundle(tupTypes, tuple.IsInOut); - case TypeSpecKind.Closure: - if (isPinvoke) - { - return new NetTypeBundle("SwiftRuntimeLibrary", isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", false, false, EntityType.Closure); - } - else - { - ClosureTypeSpec ft = spec as ClosureTypeSpec; - var throws = !isPinvoke && ft.Throws; - var arguments = ft.EachArgument().Select(parm => MapType(context, parm, false)).ToList(); - - string delegateName = "Action"; - if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) - { - var returnBundle = MapType(context, ft.ReturnType, false, true); - arguments.Add(returnBundle); - delegateName = "Func"; - } - - if (arguments.Count == 0) - return new NetTypeBundle("System", delegateName, false, false, EntityType.Closure, swiftThrows: throws); - else - return new NetTypeBundle("System", delegateName, EntityType.Closure, false, arguments, swiftThrows: throws); - } - case TypeSpecKind.ProtocolList: - var pl = (ProtocolListTypeSpec)spec; - return new NetTypeBundle("SwiftRuntimeLibrary", $"SwiftExistentialContainer{pl.Protocols.Count}", - false, true, EntityType.None); - default: throw new NotImplementedException(); } } - bool IsProtocolListTypeReference(BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundProtocolListType(spec); - - return boundType != null; - } - - Entity MapToScalarReference(BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundPointerType(spec); - if (boundType == null) - return null; - if (context.IsTypeSpecGenericReference(boundType)) - return null; - if (context.IsProtocolWithAssociatedTypesFullPath(boundType, this)) - return null; - var entity = TypeDatabase.EntityForSwiftName(boundType.Name); - return entity.EntityType == EntityType.Scalar || SwiftType.IsStructScalar(boundType.Name) ? entity : null; - } - - Entity MapToObjCStructOrEnumReference(BaseDeclaration context, NamedTypeSpec spec) - { - var boundType = GetBoundPointerType(spec); - if (boundType == null) - return null; - if (context.IsTypeSpecGenericReference(boundType)) - return null; - if (context.IsProtocolWithAssociatedTypesFullPath(boundType, this)) - return null; - var entity = TypeDatabase.EntityForSwiftName(boundType.Name); - return entity.IsObjCStruct || entity.IsObjCEnum ? entity : null; - } - TypeSpec ObjCStructOrEnumReferenceType(BaseDeclaration context, NamedTypeSpec spec) { var boundType = GetBoundPointerType(spec); @@ -876,27 +306,6 @@ static NamedTypeSpec GetBoundPointerType(NamedTypeSpec spec) return boundType; } - static ProtocolListTypeSpec GetBoundProtocolListType(NamedTypeSpec spec) - { - if (spec == null) - return null; - if (spec.Name != "Swift.UnsafePointer" && spec.Name != "Swift.UnsafeMutablePointer") - return null; - return spec.GenericParameters[0] as ProtocolListTypeSpec; - } - - NetTypeBundle ToTuple(SwiftTupleType tt, bool isPinvoke) - { - if (tt.IsEmpty) - return NetTypeBundle.Void; - if (tt.Contents.Count == 1) - { - return MapType(tt.Contents[0], isPinvoke); - } - var lt = tt.Contents.Select(t => MapType(t, isPinvoke)).ToList(); - return new NetTypeBundle(lt, tt.IsReference); - } - NetTypeBundle ToScalar(SwiftBuiltInType bit) { switch (bit.BuiltInType) @@ -964,321 +373,11 @@ NetTypeBundle ToScalar(string builtIn, bool isReference) throw new ArgumentOutOfRangeException(nameof(builtIn)); } - NetTypeBundle ToMetaClass(SwiftMetaClassType mt) - { - return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftMetatype", false, mt.IsReference, EntityType.None); - } - - NetTypeBundle ToClass(SwiftClassType ct, bool isPinvoke) - { - if (isPinvoke) - { - return new NetTypeBundle("System", "IntPtr", false, ct.IsReference, EntityType.None); - } - else - { - var en = TypeDatabase.EntityForSwiftName(ct.ClassName); - if (en != null) - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, ct.IsReference, en.EntityType); - } - else - { - throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 9, $"Unable to find swift class '{ct.ClassName.ToFullyQualifiedName()}'."); - } - } - } - - NetTypeBundle ToProtocol(SwiftProtocolListType lt, bool isPinvoke) - { - if (lt.Protocols.Count > 1) - { - return ToProtocols(lt, isPinvoke); - } - return ToProtocol(lt.Protocols[0], isPinvoke); - } - - NetTypeBundle ToProtocols(SwiftProtocolListType lt, bool isPinvoke) - { - if (!isPinvoke) - throw new NotImplementedException("If you're not doing a PInvoke, this has to be handled specially"); - return new NetTypeBundle("SwiftRuntimeLibrary", $"SwiftExistentialContainer{lt.Protocols.Count}", false, true, EntityType.ProtocolList); - } - - NetTypeBundle ToProtocol(SwiftClassType proto, bool isPinvoke) - { - var en = GetEntityForSwiftClassName(proto.ClassName.ToFullyQualifiedName(true)); - if (!en.Type.IsObjC) - { - if (isPinvoke) - { - return new NetTypeBundle("SwiftRuntimeLibrary", "SwiftExistentialContainer1", false, isPinvoke || proto.IsReference, - EntityType.None); - } - return ToClass(proto, false); - } - else - { - return ToClass(proto, isPinvoke); - } - } - - NetTypeBundle ToGenericReference(SwiftGenericArgReferenceType st, bool isPinvoke) - { - if (isPinvoke) - { - return NetTypeBundle.IntPtr; - } - else - { - return new NetTypeBundle(st.Depth, st.Index); - } - } - - NetTypeBundle ToClosure(SwiftBaseFunctionType ft, bool isPinvoke, bool isReturnValue) - { - if (isPinvoke) - { - return new NetTypeBundle("SwiftRuntimeLibrary", - isReturnValue ? "BlindSwiftClosureRepresentation" : "SwiftClosureRepresentation", - false, false, EntityType.Closure); - } - else - { - var arguments = ft.EachParameter.Select(parm => MapType(parm, false)).ToList(); - - string delegateName = "Action"; - if (ft.ReturnType != null && !ft.ReturnType.IsEmptyTuple) - { - var returnBundle = MapType(ft.ReturnType, false, true); - arguments.Add(returnBundle); - delegateName = "Func"; - } - - if (arguments.Count == 0) - return new NetTypeBundle("System", delegateName, false, false, EntityType.Closure); - else - return new NetTypeBundle("System", delegateName, EntityType.Closure, false, arguments); - } - } - - NetTypeBundle ToBoundGeneric(SwiftBoundGenericType gt, bool isPinvoke) - { - var ct = gt.BaseType as SwiftClassType; - if (ct != null && IsSwiftPointerType(ct.ClassName.ToFullyQualifiedName(true))) - { - if (gt.BoundTypes[0] is SwiftClassType boundType) - { - var entity = GetEntityForSwiftClassName(boundType.ClassName.ToFullyQualifiedName(true)); - if (entity != null && entity.IsObjCStruct) - return MapType(boundType, isPinvoke); - } - return new NetTypeBundle("System", "IntPtr", false, gt.IsReference, EntityType.None); - } - - if (isPinvoke) - { - return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); - } - - var baseType = MapType(ct, false); - var genericTypes = gt.BoundTypes.Select(bt => MapType(bt, false)); - return new NetTypeBundle(baseType.NameSpace, baseType.Type, baseType.Entity, baseType.IsReference, genericTypes); - } - - NetTypeBundle ToStruct(SwiftClassType st, bool isPinvoke) - { - var en = TypeDatabase.EntityForSwiftName(st.ClassName); - if (en != null) - { - if (isPinvoke && !SwiftType.IsStructScalar(st)) - { - if (en.Type.IsObjC) - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, true, en.EntityType); - } - else - { - return NetTypeBundle.IntPtr; - } - } - else - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); - } - } - else - { - throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 10, $"Unable to find swift struct '{st.ClassName.ToFullyQualifiedName()}'."); - } - } - - NetTypeBundle ToEnum(SwiftClassType st, bool isPinvoke, bool isReturnValue) - { - var en = TypeDatabase.EntityForSwiftName(st.ClassName); - if (en == null) - { - throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 11, $"Unable to find swift enum '{st.ClassName.ToFullyQualifiedName()}'"); - } - if (en.EntityType == EntityType.TrivialEnum) - { - return ToTrivialEnumType(en, en.Type as EnumDeclaration, isPinvoke, isReturnValue, st.IsReference); - } - else - { - if (isPinvoke) - { - return NetTypeBundle.IntPtr; - } - else - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, st.IsReference, en.EntityType); - } - } - } - - public bool TargetPlatformIs64Bit { get; private set; } - - public int MachinePointerSize { get { return TargetPlatformIs64Bit ? 8 : 4; } } - - - bool MustForcePassByReference(Entity en) - { - if (en == null) - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 4, "Null entity."); - // can't big structs, non-blitable structs, or plain enums - if (en.EntityType == EntityType.Scalar) - return false; - return en.IsStructOrEnum || (en.EntityType == EntityType.Protocol && !en.IsObjCProtocol); - } - - public bool MustForcePassByReference(TypeDeclaration decl) - { - var en = TypeDatabase.EntityForSwiftName(decl.ToFullyQualifiedName()); - if (en == null) - return false; - return MustForcePassByReference(en); - } - - public bool MustForcePassByReference(SwiftType st) - { - if (st is SwiftUnboundGenericType) - return true; - if (st is SwiftGenericArgReferenceType) - return true; - if (st is SwiftBaseFunctionType) - return false; - var protList = st as SwiftProtocolListType; - if (protList != null) - { - if (protList.Protocols.Count > 1) - return true; - return MustForcePassByReference(protList.Protocols[0]); - } - var classType = st as SwiftClassType; - if (classType == null) - { - SwiftTupleType tuple = st as SwiftTupleType; - if (tuple != null) - { - return tuple.Contents.Count > 0; - } - SwiftBuiltInType bit = st as SwiftBuiltInType; - if (bit != null) - { - return false; - } - SwiftBoundGenericType bgt = st as SwiftBoundGenericType; - if (bgt == null) - throw new NotImplementedException(); - classType = bgt.BaseType as SwiftClassType; - } - - var en = TypeDatabase.EntityForSwiftName(classType.ClassName); - if (en == null) - { - if (!classType.IsClass) - { - var module = classType.ClassName.Module.Name; - return !(classType.IsEnum && (module == "__C" || module == "__ObjC")); - } - return false; - } - return MustForcePassByReference(en); - } - - public bool MustForcePassByReference(BaseDeclaration context, TypeSpec sp) - { - if (sp.IsEmptyTuple) - return false; - if (sp is TupleTypeSpec tuple) - return tuple.Elements.Count > 1; - if (sp is ClosureTypeSpec) - return false; - if (sp is ProtocolListTypeSpec protolist) - { - if (protolist.Protocols.Count > 1) - return true; - return MustForcePassByReference(context, protolist.Protocols.ElementAt(0).Key); - } - if (context.IsTypeSpecGeneric(sp) && context.IsTypeSpecGenericReference(sp)) - return true; - if (context.IsProtocolWithAssociatedTypesFullPath(sp as NamedTypeSpec, this)) - return true; - if (sp.IsDynamicSelf) - return true; - var en = GetEntityForTypeSpec(sp); - if (en == null) - return false; - if (sp.IsUnboundGeneric(context, this)) - return en.EntityType != EntityType.Class; - return MustForcePassByReference(en); - } - public static bool IsSwiftPointerType(string fullTypeName) { return fullTypeName == "Swift.UnsafePointer" || fullTypeName == "Swift.UnsafeMutablePointer" || fullTypeName == "Swift.UnsafeRawPointer" || fullTypeName == "Swift.UnsafeMutableRawPointer"; } - - static NetTypeBundle ToTrivialEnumType(Entity en, EnumDeclaration decl, bool isPinvoke, bool isReturnValue, bool isReference) - { - if (decl.HasRawType) - { - if (decl.RawTypeName == "Swift.Int" || decl.RawTypeName == "Swift.UInt") - { - return new NetTypeBundle("System", decl.RawTypeName == "Swift.Int" ? "nint" : "nuint", false, false, EntityType.None); - } - else - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); - } - } - else - { - if (isPinvoke) - { - if (isReturnValue) - { - var enType = en.Type as EnumDeclaration; - if (enType.IsTrivial && !enType.HasRawType) - { - if (enType.Elements.Count < 256) - return new NetTypeBundle("System", "byte", false, false, EntityType.None); - else if (enType.Elements.Count < 65536) - { - return new NetTypeBundle("System", "ushort", false, false, EntityType.None); - } - } - } - return new NetTypeBundle("System", "IntPtr", false, false, EntityType.None); - } - else - { - return new NetTypeBundle(en.SharpNamespace, en.SharpTypeName, false, isReference, en.EntityType); - } - } - } } } diff --git a/src/SwiftReflector/ValueWitnessTable.cs b/src/SwiftReflector/ValueWitnessTable.cs deleted file mode 100644 index dccefbf82441..000000000000 --- a/src/SwiftReflector/ValueWitnessTable.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; -using SwiftReflector.ExceptionTools; -using SwiftReflector.Demangling; - -namespace SwiftReflector -{ - public class ValueWitnessTable - { - // #define FOR_ALL_FUNCTION_VALUE_WITNESSES(MACRO) \ - // MACRO(destroyBuffer) \ - // MACRO(initializeBufferWithCopyOfBuffer) \ - // MACRO(projectBuffer) \ - // MACRO(deallocateBuffer) \ - // MACRO(destroy) \ - // MACRO(initializeBufferWithCopy) \ - // MACRO(initializeWithCopy) \ - // MACRO(assignWithCopy) \ - // MACRO(initializeBufferWithTake) \ - // MACRO(initializeWithTake) \ - // MACRO(assignWithTake) \ - // MACRO(allocateBuffer) \ - // MACRO(initializeBufferWithTakeOfBuffer) \ - // MACRO(destroyArray) \ - // MACRO(initializeArrayWithCopy) \ - // MACRO(initializeArrayWithTakeFrontToBack) \ - // MACRO(initializeArrayWithTakeBackToFront) - public long DestroyBufferOffset { get; private set; } - public long InitializeBufferWithCopyOfBufferOffset { get; private set; } - public long ProjectBufferOffset { get; private set; } - public long DeallocateBufferOffset { get; private set; } - public long DestroyOffset { get; private set; } - public long InitializeBufferWithCopyOffset { get; private set; } - public long InitializeWithCopyOffset { get; private set; } - public long AssignWithCopyOffset { get; private set; } - public long InitializeBufferWithTakeOffset { get; private set; } - public long InitializeWithTakeOffset { get; private set; } - public long AssignWithTakeOffset { get; private set; } - public long AllocateBufferOffset { get; private set; } - public long InitializeBufferWithTakeOfBufferOffset { get; private set; } - public long DestroyArrayOffset { get; private set; } - public long InitializeArrayWithCopyOffset { get; private set; } - public long InitializeArrayWithTakeFrontToBackOffset { get; private set; } - public long InitializeArrayWithTakeBackToFrontOffset { get; private set; } - public long Size { get; private set; } - public ushort Flags { get; private set; } - public ushort Log2Stride { get; private set; } - public long Stride { get; private set; } - public string MangledName { get; private set; } - - ValueWitnessTable() - { - } - - public static ValueWitnessTable FromStream(Stream stm, TLFunction tlf, int sizeofMachinePointer) - { - if (sizeofMachinePointer != 4 && sizeofMachinePointer != 8) - { - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 14, $"Expected a maching pointer size of either 4 or 8, but got {sizeofMachinePointer}"); - } - var wit = tlf.Signature as SwiftWitnessTableType; - if (wit == null || wit.WitnessType != WitnessType.Value) - throw ErrorHelper.CreateError(ReflectorError.kCantHappenBase + 15, $"Expected a SwiftWitnessTable, but got {tlf.Signature.GetType().Name}."); - var reader = new BinaryReader(stm); - reader.BaseStream.Seek((long)tlf.Offset, SeekOrigin.Begin); - - var table = new ValueWitnessTable(); - table.MangledName = tlf.MangledName; - if (sizeofMachinePointer == 4) - table.Read32(reader); - else - table.Read64(reader); - return table; - } - - void Read32(BinaryReader reader) - { - DestroyBufferOffset = reader.ReadInt32(); - InitializeBufferWithCopyOfBufferOffset = reader.ReadInt32(); - ProjectBufferOffset = reader.ReadInt32(); - DeallocateBufferOffset = reader.ReadInt32(); - DestroyOffset = reader.ReadInt32(); - InitializeBufferWithCopyOffset = reader.ReadInt32(); - InitializeWithCopyOffset = reader.ReadInt32(); - AssignWithCopyOffset = reader.ReadInt32(); - InitializeBufferWithTakeOffset = reader.ReadInt32(); - InitializeWithTakeOffset = reader.ReadInt32(); - AssignWithTakeOffset = reader.ReadInt32(); - AllocateBufferOffset = reader.ReadInt32(); - InitializeBufferWithTakeOfBufferOffset = reader.ReadInt32(); - DestroyArrayOffset = reader.ReadInt32(); - InitializeArrayWithCopyOffset = reader.ReadInt32(); - InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt32(); - InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt32(); - Size = reader.ReadInt32(); - Flags = reader.ReadUInt16(); - Log2Stride = reader.ReadUInt16(); - Stride = reader.ReadInt32(); - } - - void Read64(BinaryReader reader) - { - DestroyBufferOffset = reader.ReadInt64(); - InitializeBufferWithCopyOfBufferOffset = reader.ReadInt64(); - ProjectBufferOffset = reader.ReadInt64(); - DeallocateBufferOffset = reader.ReadInt64(); - DestroyOffset = reader.ReadInt64(); - InitializeBufferWithCopyOffset = reader.ReadInt64(); - InitializeWithCopyOffset = reader.ReadInt64(); - AssignWithCopyOffset = reader.ReadInt64(); - InitializeBufferWithTakeOffset = reader.ReadInt64(); - InitializeWithTakeOffset = reader.ReadInt64(); - AssignWithTakeOffset = reader.ReadInt64(); - AllocateBufferOffset = reader.ReadInt64(); - InitializeBufferWithTakeOfBufferOffset = reader.ReadInt64(); - DestroyArrayOffset = reader.ReadInt64(); - InitializeArrayWithCopyOffset = reader.ReadInt64(); - InitializeArrayWithTakeFrontToBackOffset = reader.ReadInt64(); - InitializeArrayWithTakeBackToFrontOffset = reader.ReadInt64(); - Size = reader.ReadInt64(); - reader.ReadInt32(); - Flags = reader.ReadUInt16(); - Log2Stride = reader.ReadUInt16(); - Stride = reader.ReadInt64(); - } - } -} - diff --git a/src/SwiftReflector/XmlToTLFunctionMapper.cs b/src/SwiftReflector/XmlToTLFunctionMapper.cs deleted file mode 100644 index 2913c617787c..000000000000 --- a/src/SwiftReflector/XmlToTLFunctionMapper.cs +++ /dev/null @@ -1,548 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using SwiftReflector.SwiftXmlReflection; -using SwiftReflector.Inventory; -using System.Collections.Generic; -using System.Linq; -using SwiftReflector.Demangling; -using SwiftReflector.TypeMapping; - -namespace SwiftReflector -{ - public class XmlToTLFunctionMapper - { - public static TLFunction ToProtocolFactory(string swiftProxyFactoryName, ModuleDeclaration modDecl, ModuleContents contents, TypeMapper typeMap) - { - var swiftProxyFunctionDecl = modDecl.TopLevelFunctions.Where(fn => fn.Name == swiftProxyFactoryName).FirstOrDefault(); - if (swiftProxyFunctionDecl == null) - return null; - return ToTLFunction(swiftProxyFunctionDecl, contents, typeMap); - } - - public static TLFunction ToTLFunction(FunctionDeclaration decl, ModuleContents contents, TypeMapper typeMap) - { - string nameToSearch = GetNameToSearchOn(decl); - var funcs = FuncsToSearch(contents, decl, nameToSearch); - return MatchFunctionDecl(decl, funcs, typeMap); - } - - public static TLFunction ToTLFunction(FunctionDeclaration decl, ModuleInventory mi, TypeMapper typeMap) - { - var scn = ToSwiftClassName(decl); - var contents = mi.Values.FirstOrDefault(mc => mc.Name.Equals(scn.Module)); - if (contents == null) - return null; - return ToTLFunction(decl, contents, typeMap); - } - - public static TLFunction ToTLFunction(FunctionDeclaration decl, ClassContents classContents, TypeMapper typeMap) - { - string name = decl.IsProperty ? decl.PropertyName : decl.Name; - var funcsToSearch = FuncsToSearch(classContents, decl, name);//decl.ParameterLists.Count == 2 ? classContents.Methods.MethodsWithName (decl.Name) - //: classContents.StaticFunctions.MethodsWithName (decl.Name); - return MatchFunctionDecl(decl, funcsToSearch, typeMap); - } - - static List FuncsToSearch(ModuleContents contents, FunctionDeclaration decl, string name) - { - - List funcs = null; - if (decl.Parent == null) - { // top level - if (decl.IsProperty) - { - funcs = contents.Functions.MethodsWithName(name).Where(tlf => tlf.Signature is SwiftPropertyType).ToList(); - } - else - { - funcs = contents.Functions.MethodsWithName(name).Where(tlf => !(tlf.Signature is SwiftPropertyType)).ToList(); - } - } - else - { - var cn = ToSwiftClassName(decl); - var theClass = LocateClassContents(contents, cn); - funcs = FuncsToSearch(theClass, decl, name); - } - return funcs; - } - - static List FuncsToSearch(ClassContents theClass, FunctionDeclaration decl, string name) - { - List funcs = null; - - if (theClass == null) - { - funcs = new List(); - } - else - { - if (decl.IsProperty) - { - funcs = new List(); - if (decl.IsSubscript) - { - funcs.AddRange(theClass.Subscripts); - } - else - { - foreach (var pc in theClass.AllPropertiesWithName(name)) - { - var propType = pc.TLFGetter.Signature as SwiftPropertyType; - if (propType == null) // should never happen, but... - continue; - if (propType.IsStatic != decl.IsStatic) - continue; - if (decl.IsGetter) - funcs.Add(pc.TLFGetter); - else if (decl.IsSetter && pc.TLFSetter != null) - funcs.Add(pc.TLFSetter); - else if (decl.IsMaterializer && pc.TLFMaterializer != null) - funcs.Add(pc.TLFMaterializer); - } - } - } - else if (decl.IsConstructor) - { - funcs = theClass.Constructors.AllocatingConstructors(); - } - else if (decl.IsDestructor) - { - funcs = theClass.Destructors.DeallocatingDestructors(); - } - else - { - if (decl.IsStatic) - funcs = theClass.StaticFunctions.MethodsWithName(name); - else - funcs = theClass.Methods.MethodsWithName(name); - } - } - return funcs; - } - - static string GetNameToSearchOn(FunctionDeclaration decl) - { - if (!decl.IsProperty) - return decl.Name; - if (decl.IsGetter) - return decl.Name.Substring(FunctionDeclaration.kPropertyGetterPrefix.Length); - else if (decl.IsSetter) - return decl.Name.Substring(FunctionDeclaration.kPropertySetterPrefix.Length); - else if (decl.IsMaterializer) - return decl.Name.Substring(FunctionDeclaration.kPropertyMaterializerPrefix.Length); - else - throw new ArgumentOutOfRangeException("decl", "Expected getter or setter but got something else?"); - } - - public static ClassContents LocateClassContents(ModuleContents contents, SwiftClassName cn) - { - return contents.Classes.Values.FirstOrDefault(cc => cc.Name.Equals(cn)); - } - - public static ClassContents LocateClassContents(ModuleInventory modInventory, SwiftClassName className) - { - var contents = modInventory.Values.FirstOrDefault(mod => mod.Name.Equals(className.Module)); - if (contents == null) - return null; - return LocateClassContents(contents, className); - } - - public static ProtocolContents LocateProtocolContents(ModuleContents contents, SwiftClassName cn) - { - return contents.Protocols.Values.FirstOrDefault(cc => cc.Name.Equals(cn)); - } - - public static ProtocolContents LocateProtocolContents(ModuleInventory modInventory, SwiftClassName className) - { - var contents = modInventory.Values.FirstOrDefault(mod => mod.Name.Equals(className.Module)); - if (contents == null) - return null; - return LocateProtocolContents(contents, className); - } - - - - public static SwiftClassName ToSwiftClassName(BaseDeclaration bdl, string suffix = null) - { - var nesting = new List(); - var names = new List(); - var walker = bdl; - do - { - if (IsNestable(walker)) - { - nesting.Insert(0, ToMemberNesting(walker)); - names.Insert(0, new SwiftName(walker.Name + (walker == bdl && suffix != null ? suffix : ""), false)); - } - walker = walker.Parent; - } while (walker != null); - return new SwiftClassName(new SwiftName(bdl.Module.Name, false), nesting, names); - } - - static bool IsNestable(BaseDeclaration bdl) - { - return bdl is ClassDeclaration || bdl is StructDeclaration - || bdl is EnumDeclaration - ; - } - - static MemberNesting ToMemberNesting(BaseDeclaration decl) - { - // Don't reorder - a ProtocolDeclaration is a ClassDeclaration (for now) - if (decl is ProtocolDeclaration) - { - return MemberNesting.Protocol; - } - if (decl is ClassDeclaration) - { - return MemberNesting.Class; - } - if (decl is StructDeclaration) - { - return MemberNesting.Struct; - } - if (decl is EnumDeclaration) - { - return MemberNesting.Enum; - } - throw new ArgumentOutOfRangeException("decl", String.Format("unknown class entity type {0}", decl.GetType().Name)); - } - - static TLFunction MatchFunctionDecl(FunctionDeclaration decl, List funcs, TypeMapper typeMap) - { - if (decl.Parent == null) - funcs = funcs.Where(fn => fn.IsTopLevelFunction).ToList(); - else - funcs = funcs.Where(fn => !fn.IsTopLevelFunction).ToList(); - - foreach (var func in funcs) - { - if (SignaturesMatch(decl, func, typeMap)) - return func; - } - return null; - } - - - static bool SignaturesMatch(FunctionDeclaration decl, TLFunction func, TypeMapper typeMap) - { - if (decl.IsConstructor && !(func.Signature is SwiftConstructorType) || - (!decl.IsConstructor && func.Signature is SwiftConstructorType)) - return false; - List significantParameterList = decl.ParameterLists.Last(); - if (decl.ParameterLists.Count > 1 && !decl.IsStatic) - { - var ucf = func.Signature as SwiftUncurriedFunctionType; - if (ucf == null) - return false; - - var uncurriedParameter = ucf.UncurriedParameter; - var uncurriedTuple = uncurriedParameter as SwiftTupleType; - - // the !decl.IsConstructor is because the uncurried parameter in a constructor comes out - // "funny" in XmlReflection and won't match - if ((decl.Parent == null || !(decl.Parent is StructDeclaration)) && !decl.IsConstructor) - { - if (decl.ParameterLists[0].Count == 1) - { - if (!TypeMatches(decl, decl.ParameterLists[0][0], uncurriedParameter, false, typeMap)) - return false; - } - else if (decl.ParameterLists[0].Count == 0) - { - if (uncurriedTuple == null || !uncurriedTuple.IsEmpty) - return false; - } - else - { - if (uncurriedTuple == null || !TypeMatches(decl, decl.ParameterLists[0], uncurriedTuple, typeMap)) - return false; - } - } - } - - // return is implied in constructor - we're good on that, thanks - bool dontMatchReturn = decl.IsConstructor; - - if (func.Signature.ParameterCount == significantParameterList.Count) - { - if (func.Signature.ParameterCount == 0) - return dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); - if (func.Signature.ParameterCount == 1) - { - var tuple = func.Signature.Parameters as SwiftTupleType; - var argsMatch = TypeMatches(decl, significantParameterList[0], tuple != null ? tuple.Contents[0] : func.Signature.Parameters, decl.IsSetter, typeMap); - var returnMatches = (dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); - return argsMatch && returnMatches; - } - else - { - var argsMatch = TypeMatches(decl, significantParameterList, func.Signature.Parameters as SwiftTupleType, typeMap); - var returnMatches = dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap); - return argsMatch && returnMatches; - } - } - else - { - // oh, hooray. Swift does a reduction in the tuple-ness of arguments. - // if I declare a function, func a(a:(Bool, Bool)) { } - // This should get turned into: - // __TF6Module1aFTTSbSb__T_ - // Instead, swift turns it into: - // __TF6Module1aFTSbSb_T_ - // In other words, if the only argument to the function is a tuple, unwrap it. - if (significantParameterList.Count == 1 && significantParameterList[0].TypeSpec is TupleTypeSpec) - { - return TypeMatches(decl, significantParameterList[0], func.Signature.Parameters, false, typeMap) - && (dontMatchReturn || TypeMatches(decl, decl.ReturnTypeSpec, func.Signature.ReturnType, typeMap)); - } - } - return false; - } - - - static bool TypeMatches(FunctionDeclaration decl, List parms, SwiftTupleType tuple, TypeMapper typeMap) - { - if (tuple == null || parms.Count != tuple.Contents.Count) - return false; - for (int i = 0; i < parms.Count; i++) - { - if (!TypeMatches(decl, parms[i], tuple.Contents[i], decl.IsSubscript, typeMap)) - return false; - } - return true; - } - - static bool TypeMatches(FunctionDeclaration decl, ParameterItem pi, SwiftType st, bool ignoreName, TypeMapper typeMap) - { - // some SwiftType parameters have no names, such as operators - if (!ignoreName && pi.PublicName != "self" && st.Name != null && pi.PublicName != st.Name.Name) - return false; - if (pi.IsVariadic != st.IsVariadic) - return false; - return TypeMatches(decl, pi.TypeSpec, st, typeMap); - } - - static bool TypeMatches(FunctionDeclaration decl, TypeSpec ts, SwiftType st, TypeMapper typeMap) - { - switch (ts.Kind) - { - case TypeSpecKind.Named: - return TypeMatches(decl, ts as NamedTypeSpec, st, typeMap); - case TypeSpecKind.Closure: - return TypeMatches(decl, ts as ClosureTypeSpec, st, typeMap); - case TypeSpecKind.Tuple: - return TypeMatches(decl, ts as TupleTypeSpec, st, typeMap); - case TypeSpecKind.ProtocolList: - return TypeMatches(decl, ts as ProtocolListTypeSpec, st, typeMap); - default: - throw new ArgumentOutOfRangeException(nameof(ts)); - } - } - - static bool TypeMatches(FunctionDeclaration decl, ClosureTypeSpec cs, SwiftType st, TypeMapper typeMap) - { - SwiftBaseFunctionType bft = st as SwiftBaseFunctionType; - return TypeMatches(decl, cs.Arguments, bft.Parameters, typeMap) && - TypeMatches(decl, cs.ReturnType, bft.ReturnType, typeMap); - } - - static bool TypeMatches(FunctionDeclaration decl, TupleTypeSpec ts, SwiftType st, TypeMapper typeMap) - { - var tuple = st as SwiftTupleType; - if (tuple == null || tuple.Contents.Count != ts.Elements.Count) - return false; - for (int i = 0; i < ts.Elements.Count; i++) - { - if (!TypeMatches(decl, ts.Elements[i], tuple.Contents[i], typeMap)) - return false; - } - return true; - } - - static bool TypeMatches(FunctionDeclaration decl, ProtocolListTypeSpec ps, SwiftType st, TypeMapper typeMap) - { - var protoList = st as SwiftProtocolListType; - if (protoList == null || protoList.Protocols.Count != ps.Protocols.Count) - return false; - for (int i = 0; i < ps.Protocols.Count; i++) - { - if (!TypeMatches(decl, ps.Protocols.Keys[i], protoList.Protocols[i], typeMap)) - return false; - } - return true; - } - - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftType st, TypeMapper typeMap) - { - switch (st.Type) - { - case CoreCompoundType.Scalar: - return TypeMatches(decl, ts, st as SwiftBuiltInType, typeMap); - case CoreCompoundType.Class: - return TypeMatches(decl, ts, st as SwiftClassType, typeMap); - case CoreCompoundType.MetaClass: - if (st is SwiftExistentialMetaType exist) - return TypeMatches(decl, ts, exist, typeMap); - else - return TypeMatches(decl, ts, st as SwiftMetaClassType, typeMap); - case CoreCompoundType.BoundGeneric: - return TypeMatches(decl, ts, st as SwiftBoundGenericType, typeMap); - case CoreCompoundType.ProtocolList: - return TypeMatches(decl, ts, st as SwiftProtocolListType, typeMap); - case CoreCompoundType.GenericReference: - return TypeMatches(decl, ts, st as SwiftGenericArgReferenceType, typeMap); - case CoreCompoundType.Struct: - default: - return false; - } - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftGenericArgReferenceType genArg, TypeMapper typeMap) - { - if (genArg.HasAssociatedTypePath) - { - if (!decl.IsProtocolWithAssociatedTypesFullPath(ts, typeMap)) - return false; - var parts = ts.Name.Split('.'); - // parts will have the generic part at 0, genArg will not - if (parts.Length != genArg.AssociatedTypePath.Count + 1) - return false; - var depthAndIndex = decl.GetGenericDepthAndIndex(parts[0]); - if (genArg.Depth != depthAndIndex.Item1 || genArg.Index != depthAndIndex.Item2) - return false; - for (int i = 0; i < genArg.AssociatedTypePath.Count; i++) - { - if (genArg.AssociatedTypePath[i] != parts[i + 1]) - return false; - } - return true; - } - else - { - if (!decl.IsTypeSpecGeneric(ts)) - return false; - var depthAndIndex = decl.GetGenericDepthAndIndex(ts.Name); - return genArg.Depth == depthAndIndex.Item1 && genArg.Index == depthAndIndex.Item2; - } - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftProtocolListType protList, TypeMapper typeMap) - { - if (protList == null) - return false; - if (protList.Protocols.Count == 1 && !ts.IsProtocolList) - { - return TypeMatches(decl, ts, protList.Protocols[0], typeMap); - } - - if (protList.Protocols.Count != ts.GenericParameters.Count || !ts.IsProtocolList) - return false; - for (int i = 0; i < ts.GenericParameters.Count; i++) - { - if (!TypeMatches(decl, ts.GenericParameters[i], protList.Protocols[i], typeMap)) - return false; - } - return true; - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftClassType ct, TypeMapper typeMap) - { - if (ct == null) - return false; - return ts.Name == ct.ClassName.ToFullyQualifiedName(true) || - ts.NameWithoutModule == ct.ClassName.ToFullyQualifiedName(false); - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftBuiltInType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (ts.IsInOut != st.IsReference) - return false; - switch (st.BuiltInType) - { - case CoreBuiltInType.Bool: - return ts.Name == "Swift.Bool"; - case CoreBuiltInType.Double: - return ts.Name == "Swift.Double"; - case CoreBuiltInType.Float: - return ts.Name == "Swift.Float"; - case CoreBuiltInType.Int: - return ts.Name == "Swift.Int"; - case CoreBuiltInType.UInt: - return ts.Name == "Swift.UInt"; - default: - throw new ArgumentOutOfRangeException("st"); - } - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftExistentialMetaType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (st.Protocol.Protocols.Count != 1) - return false; - var protoClass = st.Protocol.Protocols[0]; - if (ts.Name == "Any.Type") - { - return protoClass.ClassName.ToFullyQualifiedName() == "Swift.Any"; - } - if (ts.Name == protoClass.ClassName.ToFullyQualifiedName()) - return true; - if (ts.Name.EndsWith(".Type", StringComparison.Ordinal)) - { - var maybeClassName = ts.Name.Substring(0, ts.Name.Length - ".Type".Length); - return maybeClassName == protoClass.ClassName.ToFullyQualifiedName(); - } - return false; - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftMetaClassType st, TypeMapper typeMap) - { - if (st == null) - return false; - return ts.Name == st.Class.ClassName.ToFullyQualifiedName(true); - } - - static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftBoundGenericType st, TypeMapper typeMap) - { - if (st == null) - return false; - if (!ts.ContainsGenericParameters) - return false; - return TypeMatches(decl, ts.GenericParameters, st.BoundTypes, typeMap); - } - - static bool TypeMatches(FunctionDeclaration decl, List ts, List st, TypeMapper typeMap) - { - if (ts == null || st == null) - return false; - if (ts.Count != st.Count) - return false; - if (ts.Count == 1) - { - // Thanks swift, you're the best... - if (IsVoid(ts[0]) && st[0].IsEmptyTuple) - return true; - } - for (int i = 0; i < ts.Count; i++) - { - if (!TypeMatches(decl, ts[i], st[i], typeMap)) - return false; - } - return true; - } - - static bool IsVoid(TypeSpec ts) - { - var ns = ts as NamedTypeSpec; - return ns != null && (ns.Name == "Void" || ns.Name == "Swift.Void"); - } - } -} - diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs index 6ed7aca85208..82fa672ea46a 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs @@ -53,6 +53,14 @@ public static CSAttribute DllImport(CSBaseExpression dllName, string entryPoint return new CSAttribute(new CSIdentifier("DllImport"), args, true); } + public static CSAttribute UnmanagedCallConv(string callconv) + { + CSArgumentList args = new CSArgumentList(); + + args.Add(new CSAssignment("CallConvs", CSAssignmentOperator.Assign, new CSIdentifier("new Type[] { typeof("+callconv+") }"))); + return new CSAttribute(new CSIdentifier("UnmanagedCallConv"), args, true); + } + static CSAttribute returnMarshalAsI1 = new CSAttribute("return: MarshalAs", new CSIdentifier("UnmanagedType.I1")); public static CSAttribute ReturnMarshalAsI1 => returnMarshalAsI1; diff --git a/src/samples/HelloWorld/Program.cs b/src/samples/HelloWorld/Program.cs index b85e031f1e9f..1d3607cd7854 100644 --- a/src/samples/HelloWorld/Program.cs +++ b/src/samples/HelloWorld/Program.cs @@ -10,7 +10,7 @@ public class Program { public static void Main(string[] args) { - HelloLibrary.SayHello(); + HelloLibrary.sayHello(); } } } diff --git a/src/samples/HelloWorld/build.sh b/src/samples/HelloWorld/build.sh index 1b7ed46863bf..d89b3859611a 100755 --- a/src/samples/HelloWorld/build.sh +++ b/src/samples/HelloWorld/build.sh @@ -6,7 +6,7 @@ dotnet build ../../SwiftBindings/src/SwiftBindings.csproj if [ $? -eq 0 ]; then echo "Build successful. Running the BindingsTool..." - dotnet ../../../artifacts/bin/SwiftBindings/Debug/net7.0/SwiftBindings.dll -d "./libHelloLibrary.dylib" -s "./HelloLibrary.swiftinterface" -o "./" + dotnet ../../../artifacts/bin/SwiftBindings/Debug/net7.0/SwiftBindings.dll -a "./HelloLibrary.abi.json" -o "./" dotnet run else echo "Build failed. Exiting..." From 4856a8efa0dbd52019b9a4ab9334472582282263 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 21 Feb 2024 16:41:41 +0100 Subject: [PATCH 30/37] Refactor null exceptions to use ArgumentNullException.ThrowIfNull --- src/SwiftReflector/SwiftClassName.cs | 9 ++++-- src/SwiftReflector/SwiftType.cs | 3 +- .../AttributeDeclaration.cs | 12 +++++--- .../SwiftXmlReflection/BaseConstraint.cs | 3 +- .../SwiftXmlReflection/EnumElement.cs | 3 +- .../ExtensionDeclaration.cs | 3 +- .../SwiftXmlReflection/FunctionDeclaration.cs | 6 ++-- .../SwiftXmlReflection/Inheritance.cs | 5 ++-- .../SwiftXmlReflection/ParameterItem.cs | 5 ++-- .../SwiftXmlReflection/PropertyDeclaration.cs | 3 +- .../TypeAliasDeclaration.cs | 12 ++++---- .../SwiftXmlReflection/TypeSpecParser.cs | 2 +- .../SwiftXmlReflection/TypeSpecToken.cs | 6 ++-- src/SwiftReflector/TypeMapping/NetParam.cs | 3 +- .../TypeMapping/NetTypeBundle.cs | 6 ++-- .../TypeMapping/TypeDatabase.cs | 15 ++++++---- src/SwiftReflector/TypeMapping/TypeMapper.cs | 5 ++-- src/SwiftRuntimeLibrary/Exceptions.cs | 26 ---------------- src/SyntaxDynamo/CodeWriter.cs | 5 ++-- .../CommaListElementCollection.cs | 9 ++++-- .../DelegatedCommaListElementCollection.cs | 9 ++++-- src/SyntaxDynamo/Exceptions.cs | 24 --------------- src/SyntaxDynamo/Extensions.cs | 4 +-- .../LabeledCodeElementCollection.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSArgument.cs | 3 +- .../SyntaxDynamo.CSLang/CSArray1D.cs | 18 +++++++---- .../SyntaxDynamo.CSLang/CSAssignment.cs | 8 +++-- .../SyntaxDynamo.CSLang/CSAttribute.cs | 5 ++-- .../SyntaxDynamo.CSLang/CSBinaryExpression.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSClass.cs | 3 +- .../SyntaxDynamo.CSLang/CSCodeBlock.cs | 2 +- .../SyntaxDynamo.CSLang/CSComment.cs | 6 ++-- .../CSConditionalCompilation.cs | 3 +- .../SyntaxDynamo.CSLang/CSConstant.cs | 3 +- .../SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs | 3 +- .../SyntaxDynamo.CSLang/CSEnum.cs | 3 +- .../SyntaxDynamo.CSLang/CSFieldDeclaration.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSFileBasic.cs | 3 +- .../SyntaxDynamo.CSLang/CSFixed.cs | 9 ++++-- .../SyntaxDynamo.CSLang/CSForEach.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSFunctionCall.cs | 9 ++++-- .../CSGenericConstraint.cs | 9 ++++-- .../CSGenericTypeDeclaration.cs | 3 +- .../SyntaxDynamo.CSLang/CSIdentifier.cs | 3 +- .../SyntaxDynamo.CSLang/CSIfElse.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSIndexExpression.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSInheritance.cs | 2 +- .../SyntaxDynamo.CSLang/CSInitializer.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSInterface.cs | 3 +- .../SyntaxDynamo.CSLang/CSLambda.cs | 3 +- .../SyntaxDynamo.CSLang/CSLine.cs | 3 +- .../SyntaxDynamo.CSLang/CSMethod.cs | 30 ++++++++++++------- .../SyntaxDynamo.CSLang/CSNamespace.cs | 5 ++-- .../SyntaxDynamo.CSLang/CSParameter.cs | 15 ++++++---- .../CSParenthesisExpression.cs | 9 ++++-- .../SyntaxDynamo.CSLang/CSProperty.cs | 23 +++++++++----- .../SyntaxDynamo.CSLang/CSTernary.cs | 9 ++++-- .../SyntaxDynamo.CSLang/CSThrow.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSType.cs | 6 ++-- .../SyntaxDynamo.CSLang/CSUnaryExpression.cs | 3 +- .../SyntaxDynamo.CSLang/CSUsing.cs | 2 +- .../ICSTopLevelDeclaration.cs | 3 +- 62 files changed, 251 insertions(+), 184 deletions(-) delete mode 100644 src/SwiftRuntimeLibrary/Exceptions.cs delete mode 100644 src/SyntaxDynamo/Exceptions.cs diff --git a/src/SwiftReflector/SwiftClassName.cs b/src/SwiftReflector/SwiftClassName.cs index 8f5ef62269ab..7b61e530c182 100644 --- a/src/SwiftReflector/SwiftClassName.cs +++ b/src/SwiftReflector/SwiftClassName.cs @@ -13,9 +13,12 @@ public class SwiftClassName { public SwiftClassName(SwiftName module, IList nesting, IList nestingNames, OperatorType oper = OperatorType.None) { - Module = Exceptions.ThrowOnNull(module, "module"); - Nesting = Exceptions.ThrowOnNull(nesting, "nesting"); - NestingNames = Exceptions.ThrowOnNull(nestingNames, "nestingNames"); + ArgumentNullException.ThrowIfNull(module, nameof(module)); + ArgumentNullException.ThrowIfNull(nesting, nameof(nesting)); + ArgumentNullException.ThrowIfNull(nestingNames, nameof(nestingNames)); + Module = module; + Nesting = nesting; + NestingNames = nestingNames; Terminus = NestingNames.Count > 0 ? NestingNames[NestingNames.Count - 1] : null; Operator = oper; } diff --git a/src/SwiftReflector/SwiftType.cs b/src/SwiftReflector/SwiftType.cs index a60ebf1ab439..eba26743ef29 100644 --- a/src/SwiftReflector/SwiftType.cs +++ b/src/SwiftReflector/SwiftType.cs @@ -300,7 +300,8 @@ public class SwiftBoundGenericType : SwiftType public SwiftBoundGenericType(SwiftType baseType, List boundTypes, bool isReference, SwiftName name = null) : base(CoreCompoundType.BoundGeneric, isReference, name) { - BaseType = Exceptions.ThrowOnNull(baseType, "baseType"); + ArgumentNullException.ThrowIfNull(baseType, nameof(baseType)); + BaseType = baseType; BoundTypes = new List(); if (boundTypes != null) BoundTypes.AddRange(boundTypes); diff --git a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs index 1c11ba360b15..c106d3d1e5a3 100644 --- a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs @@ -13,7 +13,8 @@ public class AttributeDeclaration { public AttributeDeclaration(string typeName) { - Name = Exceptions.ThrowOnNull(typeName, nameof(typeName)); + ArgumentNullException.ThrowIfNull(typeName, nameof(typeName)); + Name = typeName; Parameters = new List(); } @@ -69,7 +70,7 @@ public string Name } private set { - Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); var ts = TypeSpecParser.Parse(value); if (ts is NamedTypeSpec named) AttributeType = named; @@ -104,7 +105,9 @@ public class AttributeParameterLabel : AttributeParameter { public AttributeParameterLabel(string label) { - Label = Exceptions.ThrowOnNull(label, nameof(label)); + + ArgumentNullException.ThrowIfNull(label, nameof(label)); + Label = label; } public AttributeParameterLabel(AttributeParameterLabel other) @@ -120,7 +123,8 @@ public class AttributeParameterLiteral : AttributeParameter { public AttributeParameterLiteral(string literal) { - Literal = Exceptions.ThrowOnNull(literal, nameof(literal)); + ArgumentNullException.ThrowIfNull(literal, nameof(literal)); + Literal = literal; } public AttributeParameterLiteral(AttributeParameterLiteral other) diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs index 4652f19569f3..529eb3a7334f 100644 --- a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs +++ b/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs @@ -87,7 +87,8 @@ public class InheritanceConstraint : BaseConstraint public InheritanceConstraint(string name, string inheritsTypeSpecString, TypeAliasFolder folder = null) : base(ConstraintKind.Inherits) { - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; Inherits = inheritsTypeSpecString; if (folder != null) InheritsTypeSpec = folder.FoldAlias(null, InheritsTypeSpec); diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs index 23171b317ec7..b37c06759366 100644 --- a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs +++ b/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs @@ -12,7 +12,8 @@ public class EnumElement : IXElementConvertible { public EnumElement(string name, string typeName, long? value) { - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; TypeName = typeName; Value = value; } diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs index 253f1ff6fede..0e4f8223c56a 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs @@ -39,7 +39,8 @@ public string ExtensionOnTypeName } set { - extensionOnTypeName = Exceptions.ThrowOnNull(value, "value"); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + extensionOnTypeName = value; try { ExtensionOnType = TypeSpecParser.Parse(extensionOnTypeName); diff --git a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs index 16eb84cc9870..f114f59a4fb9 100644 --- a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs @@ -67,7 +67,8 @@ public string ReturnTypeName get { return returnTypeName; } set { - returnTypeName = Exceptions.ThrowOnNull(value, "value"); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + returnTypeName = value; try { ReturnTypeSpec = TypeSpecParser.Parse(returnTypeName); @@ -254,13 +255,14 @@ public bool ContainsBoundGenericClosure() public static FunctionDeclaration FuncFromXElement(TypeAliasFolder folder, XElement elem, ModuleDeclaration module, BaseDeclaration parent) { + ArgumentNullException.ThrowIfNull((string)elem.Attribute("returnType"), "returnType"); FunctionDeclaration decl = new FunctionDeclaration { Name = (string)elem.Attribute("name"), Module = module, Parent = parent, Access = TypeDeclaration.AccessibilityFromString((string)elem.Attribute("accessibility")), - ReturnTypeName = Exceptions.ThrowOnNull((string)elem.Attribute("returnType"), "returnType"), + ReturnTypeName = (string)elem.Attribute("returnType"), IsAsync = elem.BoolAttribute("isAsync"), IsProperty = elem.BoolAttribute("isProperty"), IsStatic = elem.BoolAttribute("isStatic"), diff --git a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs index 4178bc991f46..a35ece2c1818 100644 --- a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs +++ b/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs @@ -26,7 +26,8 @@ public string InheritedTypeName get { return inheritedTypeName; } set { - inheritedTypeName = Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + inheritedTypeName = value; try { InheritedTypeSpec = TypeSpecParser.Parse(inheritedTypeName); @@ -70,7 +71,7 @@ static string ToString(InheritanceKind kind) static InheritanceKind ToInheritanceKind(string kindStr) { - Exceptions.ThrowOnNull(kindStr, nameof(kindStr)); + ArgumentNullException.ThrowIfNull(kindStr, nameof(kindStr)); switch (kindStr) { case "protocol": diff --git a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs index 15b3d046810e..7b934707af79 100644 --- a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs +++ b/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs @@ -37,7 +37,8 @@ public string TypeName get { return typeName; } set { - typeName = Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + typeName = value; try { typeSpec = TypeSpecParser.Parse(typeName); @@ -54,7 +55,7 @@ public TypeSpec TypeSpec get { return typeSpec; } set { - Exceptions.ThrowOnNull(value, "value"); + ArgumentNullException.ThrowIfNull(value, nameof(value)); typeSpec = value; typeName = value.ToString(); } diff --git a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs index b67b300c265f..64ef240aff3d 100644 --- a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs @@ -38,7 +38,8 @@ public string TypeName } set { - typeName = Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + typeName = value; try { TypeSpec = TypeSpecParser.Parse(typeName); diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs index dc117eee8ab2..4629953e9199 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs @@ -22,7 +22,8 @@ public string TypeName get { return typeName; } set { - typeName = Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + typeName = value; if (typeName.IndexOf(':') >= 0) throw ErrorHelper.CreateError(ReflectorError.kReflectionErrorBase + 12, $"typealias {value} has a generic constraint which is not supported"); try @@ -42,7 +43,7 @@ public TypeSpec TypeSpec get { return typeSpec; } set { - Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); typeSpec = value; typeName = value.ToString(); } @@ -54,7 +55,8 @@ public string TargetTypeName get { return targetTypeName; } set { - targetTypeName = Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + targetTypeName = value; try { targetTypeSpec = TypeSpecParser.Parse(targetTypeName); @@ -72,7 +74,7 @@ public TypeSpec TargetTypeSpec get { return targetTypeSpec; } set { - Exceptions.ThrowOnNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value, nameof(value)); targetTypeSpec = value; targetTypeName = value.ToString(); } @@ -98,7 +100,7 @@ public static TypeAliasDeclaration FromXElement(string moduleName, XElement elem var aliasName = element.Attribute("name").Value; if (!aliasName.Contains(".")) { - Exceptions.ThrowOnNull(moduleName, nameof(moduleName)); + ArgumentNullException.ThrowIfNull(moduleName, nameof(moduleName)); aliasName = $"{moduleName}.{aliasName}"; } return new TypeAliasDeclaration() diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs index 74466147b15d..c82a4bb0c57b 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs @@ -232,7 +232,7 @@ void ParseAttributeParameters(List parameters) TypeSpec ParseProtocolList(NamedTypeSpec first) { - Exceptions.ThrowOnNull(first, nameof(first)); + ArgumentNullException.ThrowIfNull(first, nameof(first)); var protocols = new List(); protocols.Add(first); while (true) diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs index 7ab2db7b76e3..70bc6b54d203 100644 --- a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs +++ b/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs @@ -16,11 +16,13 @@ public class TypeSpecToken public string Value { get; private set; } public static TypeSpecToken LabelFromString(string value) { - return new TypeSpecToken(TypeTokenKind.TypeLabel, Exceptions.ThrowOnNull(value, "value")); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + return new TypeSpecToken(TypeTokenKind.TypeLabel, value); } public static TypeSpecToken FromString(string value) { - return new TypeSpecToken(TypeTokenKind.TypeName, Exceptions.ThrowOnNull(value, "value")); + ArgumentNullException.ThrowIfNull(value, nameof(value)); + return new TypeSpecToken(TypeTokenKind.TypeName, value); } static TypeSpecToken leftparenthesis = new TypeSpecToken(TypeTokenKind.LeftParenthesis, "("); static TypeSpecToken rightparenthesis = new TypeSpecToken(TypeTokenKind.RightParenthesis, ")"); diff --git a/src/SwiftReflector/TypeMapping/NetParam.cs b/src/SwiftReflector/TypeMapping/NetParam.cs index ecb7108dbd91..1bc6a961e843 100644 --- a/src/SwiftReflector/TypeMapping/NetParam.cs +++ b/src/SwiftReflector/TypeMapping/NetParam.cs @@ -9,7 +9,8 @@ public class NetParam { public NetParam(string name, NetTypeBundle bundle) { - Name = Exceptions.ThrowOnNull(name, "name"); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; Type = bundle; } public string Name { get; private set; } diff --git a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs index b1ca1c124732..3032f7acd1d8 100644 --- a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs +++ b/src/SwiftReflector/TypeMapping/NetTypeBundle.cs @@ -42,7 +42,8 @@ public NetTypeBundle(List tupleElements, bool isReference) IsScalar = false; IsReference = isReference; Entity = EntityType.Tuple; - TupleTypes.AddRange(Exceptions.ThrowOnNull(tupleElements, "tupleElements")); + ArgumentNullException.ThrowIfNull(tupleElements, nameof(tupleElements)); + TupleTypes.AddRange(tupleElements); } public NetTypeBundle(string nameSpace, string entityName, EntityType entity, bool isReference, IEnumerable genericTypes, @@ -79,8 +80,9 @@ public NetTypeBundle(ProtocolDeclaration proto, AssociatedTypeDeclaration assoc, public NetTypeBundle(string selfRepresentation, bool isReference) { + ArgumentNullException.ThrowIfNull(selfRepresentation, nameof(selfRepresentation)); GenericIndex = -1; - Type = FullName = Exceptions.ThrowOnNull(selfRepresentation, nameof(selfRepresentation)); + Type = FullName = selfRepresentation; NameSpace = String.Empty; IsReference = isReference; IsSelf = true; diff --git a/src/SwiftReflector/TypeMapping/TypeDatabase.cs b/src/SwiftReflector/TypeMapping/TypeDatabase.cs index 8e82d15d3192..694a1d49e3bb 100644 --- a/src/SwiftReflector/TypeMapping/TypeDatabase.cs +++ b/src/SwiftReflector/TypeMapping/TypeDatabase.cs @@ -65,19 +65,22 @@ public TypeDatabase() public DotNetName DotNetNameForSwiftName(string swiftName) { DotNetName netName = null; - swiftNamesToNetNames.TryGetValue(Exceptions.ThrowOnNull(swiftName, "swiftName"), out netName); + ArgumentNullException.ThrowIfNull(swiftName, nameof(swiftName)); + swiftNamesToNetNames.TryGetValue(swiftName, out netName); return netName; // may be null } public DotNetName DotNetNameForSwiftName(SwiftClassName swiftName) { - return DotNetNameForSwiftName(Exceptions.ThrowOnNull(swiftName, "swiftName").ToFullyQualifiedName(true)); + ArgumentNullException.ThrowIfNull(swiftName, nameof(swiftName)); + return DotNetNameForSwiftName(swiftName.ToFullyQualifiedName(true)); } public string SwiftNameForDotNetName(DotNetName netName) { string swiftName = null; - netNamesToSwiftNames.TryGetValue(Exceptions.ThrowOnNull(netName, "netName"), out swiftName); + ArgumentNullException.ThrowIfNull(netName, nameof(netName)); + netNamesToSwiftNames.TryGetValue(netName, out swiftName); return swiftName; } @@ -131,7 +134,8 @@ public void Add(Entity e) ModuleDatabase EntityCollection(string moduleName) { ModuleDatabase module = null; - modules.TryGetValue(Exceptions.ThrowOnNull(moduleName, nameof(moduleName)), out module); + ArgumentNullException.ThrowIfNull(moduleName, nameof(moduleName)); + modules.TryGetValue(moduleName, out module); return module; } @@ -365,7 +369,8 @@ Entity EntityFromXElement(XElement entityElem, Dictionary= 0; + ArgumentNullException.ThrowIfNull(builtIn, nameof(builtIn)); + return ScalarIndex(builtIn) >= 0; } public static bool IsScalar(TypeSpec spec) diff --git a/src/SwiftRuntimeLibrary/Exceptions.cs b/src/SwiftRuntimeLibrary/Exceptions.cs deleted file mode 100644 index 495285d05bec..000000000000 --- a/src/SwiftRuntimeLibrary/Exceptions.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SwiftRuntimeLibrary -{ - public static class Exceptions - { - public static T ThrowOnNull(T o, string name, string message = null) where T : class - { - if (o == null) - ThrowArgumentNull(name, message); - return o!; - } - - static void ThrowArgumentNull(string name, string message = null) - { - name = name ?? "::no name supplied::"; - if (message == null) - throw new ArgumentNullException(name); - else - throw new ArgumentNullException(name, message); - } - } -} diff --git a/src/SyntaxDynamo/CodeWriter.cs b/src/SyntaxDynamo/CodeWriter.cs index 5d32962399d9..3b51edacce94 100644 --- a/src/SyntaxDynamo/CodeWriter.cs +++ b/src/SyntaxDynamo/CodeWriter.cs @@ -16,13 +16,14 @@ public class CodeWriter : ICodeWriter const int kWrapPoint = 60; public CodeWriter(Stream stm) - : this(new StreamWriter(Exceptions.ThrowOnNull(stm, "stm"))) + : this(new StreamWriter(stm)) { } public CodeWriter(TextWriter tw) { - TextWriter = Exceptions.ThrowOnNull(tw, "tw"); + ArgumentNullException.ThrowIfNull(tw, nameof(tw)); + TextWriter = tw; charsWrittenThisLine = 0; IndentLevel = 0; IsAtLineStart = true; diff --git a/src/SyntaxDynamo/CommaListElementCollection.cs b/src/SyntaxDynamo/CommaListElementCollection.cs index 8aeb8ad982eb..2f4ec9a2141c 100644 --- a/src/SyntaxDynamo/CommaListElementCollection.cs +++ b/src/SyntaxDynamo/CommaListElementCollection.cs @@ -22,14 +22,17 @@ public CommaListElementCollection(IEnumerable objs) public CommaListElementCollection(string prefix, string suffix) : base() { - Prefix = Exceptions.ThrowOnNull(prefix, nameof(prefix)); - Suffix = Exceptions.ThrowOnNull(suffix, nameof(suffix)); + ArgumentNullException.ThrowIfNull(prefix, nameof(prefix)); + ArgumentNullException.ThrowIfNull(suffix, nameof(suffix)); + Prefix = prefix; + Suffix = suffix; } public CommaListElementCollection(string prefix, string suffix, IEnumerable objs, bool newlineAfterEach = false) : this(prefix, suffix) { - AddRange(Exceptions.ThrowOnNull(objs, nameof(objs))); + ArgumentNullException.ThrowIfNull(objs, nameof(objs)); + AddRange(objs); NewlineAfterEach = newlineAfterEach; } diff --git a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs index 2d3d8dbd4d08..d6f3e517b3d5 100644 --- a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs +++ b/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs @@ -12,14 +12,17 @@ public class DelegatedCommaListElemCollection : List, ICodeElement where T public DelegatedCommaListElemCollection(Action elementWriter) : base() { - this.elementWriter = Exceptions.ThrowOnNull(elementWriter, nameof(elementWriter)); + ArgumentNullException.ThrowIfNull(elementWriter, nameof(elementWriter)); + this.elementWriter = elementWriter; } public DelegatedCommaListElemCollection(Action elementWriter, IEnumerable objs) : base() { - this.elementWriter = Exceptions.ThrowOnNull(elementWriter, nameof(elementWriter)); - AddRange(Exceptions.ThrowOnNull(objs, nameof(objs))); + ArgumentNullException.ThrowIfNull(elementWriter, nameof(elementWriter)); + ArgumentNullException.ThrowIfNull(objs, nameof(objs)); + this.elementWriter = elementWriter; + AddRange(objs); } public event EventHandler Begin = (s, e) => { }; diff --git a/src/SyntaxDynamo/Exceptions.cs b/src/SyntaxDynamo/Exceptions.cs deleted file mode 100644 index a6777a75fe94..000000000000 --- a/src/SyntaxDynamo/Exceptions.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -namespace SyntaxDynamo -{ - public class Exceptions - { - public static T ThrowOnNull(T o, string name, string message = null) where T : class - { - name = name ?? "::no name supplied::"; - if (o == null) - { - if (message == null) - throw new ArgumentNullException(name); - else - throw new ArgumentNullException(name, message); - } - return o; - } - } -} - diff --git a/src/SyntaxDynamo/Extensions.cs b/src/SyntaxDynamo/Extensions.cs index 561ae3c70c22..3fd16f1a6dc2 100644 --- a/src/SyntaxDynamo/Extensions.cs +++ b/src/SyntaxDynamo/Extensions.cs @@ -54,7 +54,7 @@ public static IEnumerable BracketInterleave(this IEnumerable contents, public static T AttachBefore(this T attacher, ICodeElement attachTo) where T : ICodeElement { - Exceptions.ThrowOnNull(attachTo, nameof(attachTo)); + ArgumentNullException.ThrowIfNull(attachTo, nameof(attachTo)); attachTo.Begin += (s, eventArgs) => { attacher.WriteAll(eventArgs.Writer); @@ -64,7 +64,7 @@ public static IEnumerable BracketInterleave(this IEnumerable contents, public static T AttachAfter(this T attacher, ICodeElement attachTo) where T : ICodeElement { - Exceptions.ThrowOnNull(attachTo, nameof(attachTo)); + ArgumentNullException.ThrowIfNull(attachTo, nameof(attachTo)); attachTo.End += (s, eventArgs) => { attacher.WriteAll(eventArgs.Writer); diff --git a/src/SyntaxDynamo/LabeledCodeElementCollection.cs b/src/SyntaxDynamo/LabeledCodeElementCollection.cs index f829f486d5d9..f0de5ada7e2a 100644 --- a/src/SyntaxDynamo/LabeledCodeElementCollection.cs +++ b/src/SyntaxDynamo/LabeledCodeElementCollection.cs @@ -10,8 +10,10 @@ public class LabeledCodeElementCollection : ICodeElementSet where T : ICodeEl { public LabeledCodeElementCollection(SimpleLineElement label, CodeElementCollection block) { - Label = Exceptions.ThrowOnNull(label, nameof(label)); - Block = Exceptions.ThrowOnNull(block, nameof(block)); + ArgumentNullException.ThrowIfNull(label, nameof(label)); + ArgumentNullException.ThrowIfNull(block, nameof(block)); + Label = label; + Block = block; } public SimpleLineElement Label { get; private set; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs index f945c23a7ff8..7f039b51daa3 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs @@ -7,7 +7,8 @@ public class CSArgument : DelegatedSimpleElement { public CSArgument(ICSExpression expr) { - Value = Exceptions.ThrowOnNull(expr, nameof(expr)); + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); + Value = expr; } public ICSExpression Value { get; private set; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs index fb37e94a94e5..4ac2d473c104 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs @@ -10,8 +10,10 @@ public class CSArray1D : CSBaseExpression { public CSArray1D(CSIdentifier name, CommaListElementCollection paramList) { - Name = Exceptions.ThrowOnNull(name, "name"); - Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(paramList, nameof(paramList)); + Name = name; + Parameters = paramList; } public CSArray1D(string name, params CSBaseExpression[] parameters) @@ -41,8 +43,10 @@ public class CSArray1DInitialized : CSBaseExpression { public CSArray1DInitialized(CSType type, CommaListElementCollection initializers) { - Type = Exceptions.ThrowOnNull(type, "type"); - Parameters = Exceptions.ThrowOnNull(initializers, "initializers"); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(initializers, nameof(initializers)); + Type = type; + Parameters = initializers; } public CSArray1DInitialized(CSType type, params CSBaseExpression[] parameters) @@ -79,8 +83,10 @@ public class CSListInitialized : CSBaseExpression { public CSListInitialized(CSType type, CommaListElementCollection initializers) { - Type = Exceptions.ThrowOnNull(type, "type"); - Parameters = Exceptions.ThrowOnNull(initializers, "initializers"); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(initializers, nameof(initializers)); + Type = type; + Parameters = initializers; } public CSListInitialized(CSType type, params CSBaseExpression[] parameters) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs index 8c717c19721f..4f84f8e97d9c 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs @@ -10,13 +10,15 @@ public class CSAssignment : CSBaseExpression, ICSLineable { public CSAssignment(CSBaseExpression lhs, CSAssignmentOperator op, CSBaseExpression rhs) { - Target = Exceptions.ThrowOnNull(lhs, "lhs"); - Value = Exceptions.ThrowOnNull(rhs, "rhs"); + ArgumentNullException.ThrowIfNull(lhs, nameof(lhs)); + ArgumentNullException.ThrowIfNull(rhs, nameof(rhs)); + Target = lhs; + Value = rhs; Operation = op; } public CSAssignment(string lhs, CSAssignmentOperator op, CSBaseExpression rhs) - : this(new CSIdentifier(Exceptions.ThrowOnNull(lhs, "lhs")), op, rhs) + : this(new CSIdentifier(lhs), op, rhs) { } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs index 82fa672ea46a..413a96413e35 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs @@ -11,10 +11,11 @@ public class CSAttribute : LineCodeElementCollection public CSAttribute(CSIdentifier name, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) : base(isSingleLine, false, isSingleLine) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); Add(new SimpleElement("[")); if (isReturn) Add(new SimpleElement("return:")); - Add(Exceptions.ThrowOnNull(name, nameof(name))); + Add(name); if (args != null) { Add(new SimpleElement("(")); @@ -81,7 +82,7 @@ public static CSAttribute LayoutKind(LayoutKind layout) public static CSAttribute FromAttr(Type attribute, CSArgumentList args, bool isSingleLine = false, bool isReturn = false) { - Exceptions.ThrowOnNull(attribute, nameof(attribute)); + ArgumentNullException.ThrowIfNull(attribute, nameof(attribute)); if (!attribute.IsSubclassOf(typeof(Attribute))) throw new ArgumentException(String.Format("Type {0} is not an Attribute type.", attribute.Name), nameof(attribute)); var name = attribute.Name.EndsWith("Attribute") ? diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs index cecd457a58cd..64eea92012d6 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs @@ -10,9 +10,11 @@ public class CSBinaryExpression : CSBaseExpression { public CSBinaryExpression(CSBinaryOperator op, ICSExpression lhs, ICSExpression rhs) { + ArgumentNullException.ThrowIfNull(lhs, nameof(lhs)); + ArgumentNullException.ThrowIfNull(rhs, nameof(rhs)); Operation = op; - Left = Exceptions.ThrowOnNull(lhs, "lhs"); - Right = Exceptions.ThrowOnNull(rhs, "rhs"); + Left = lhs; + Right = rhs; } protected override void LLWrite(ICodeWriter writer, object o) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs index ca1d60b1fee4..680b4773c410 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs @@ -13,10 +13,11 @@ public class CSClass : ICodeElementSet, ICSTopLevelDeclaration public CSClass(CSVisibility vis, CSIdentifier name, IEnumerable methods = null, bool isStatic = false, bool isSealed = false) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); Visibility = vis; IsStatic = isStatic; IsSealed = isSealed; - Name = Exceptions.ThrowOnNull(name, "name"); + Name = name; Inheritance = new CSInheritance(); Delegates = new List(); Fields = new List(); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs index 1520e9b2fb20..59546585ad24 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs @@ -25,7 +25,7 @@ public static CSCodeBlock Create(params ICodeElement[] statements) } public CSCodeBlock(string start, string end, IEnumerable statements) - : base(Exceptions.ThrowOnNull(start, "start"), Exceptions.ThrowOnNull(end, "end"), true, true, true) + : base(start, end, true, true, true) { if (statements != null) { diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs index 8ffc0e40ecae..abd5036b0809 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs @@ -31,7 +31,8 @@ public CSCommentBlock(params CSComment[] comments) public CSCommentBlock(params string[] text) { - AddRange(Sanitize(Exceptions.ThrowOnNull(text, "text"))); + ArgumentNullException.ThrowIfNull(text, nameof(text)); + AddRange(Sanitize(text)); } static IEnumerable Sanitize(string[] text) @@ -52,7 +53,8 @@ public CSCommentBlock And(string text) public CSCommentBlock And(CSComment comment) { - Add(Exceptions.ThrowOnNull(comment, "comment")); + ArgumentNullException.ThrowIfNull(comment, nameof(comment)); + Add(comment); return this; } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs index 5e576ce1ba6f..f707134431a4 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs @@ -27,7 +27,8 @@ public class CSConditionalCompilation : LineCodeElementCollection public static CSConditionalCompilation If(CSIdentifier condition) { - return new CSConditionalCompilation(new CSIdentifier("#if"), Exceptions.ThrowOnNull(condition, nameof(condition))); + ArgumentNullException.ThrowIfNull(condition, nameof(condition)); + return new CSConditionalCompilation(new CSIdentifier("#if"), condition); } public static void ProtectWithIfEndif(CSIdentifier condition, ICodeElement elem) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs index 257ad0ccdb2d..b5de9d544dfd 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs @@ -13,7 +13,8 @@ public class CSConstant : CSBaseExpression { public CSConstant(string val) { - Value = Exceptions.ThrowOnNull(val, "val"); + ArgumentNullException.ThrowIfNull(val, nameof(val)); + Value = val; } public static explicit operator CSConstant(string val) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs index f3404d183519..d2d9ea342d05 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs @@ -9,9 +9,10 @@ public class CSDelegateTypeDecl : DelegatedSimpleElement, ICSStatement { public CSDelegateTypeDecl(CSVisibility vis, CSType type, CSIdentifier name, CSParameterList parms, bool isUnsafe = false) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); Visibility = vis; Type = type != null ? type : CSSimpleType.Void; - Name = Exceptions.ThrowOnNull(name, "name"); + Name = name; Parameters = parms; IsUnsafe = isUnsafe; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs index 8bbedbaf2e74..934f0fb9e68d 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs @@ -11,8 +11,9 @@ public class CSEnum : ICodeElementSet, ICSTopLevelDeclaration { public CSEnum(CSVisibility vis, CSIdentifier name, CSType optionalType) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); Values = new List(); - Name = Exceptions.ThrowOnNull(name, "name"); + Name = name; OptionalType = optionalType; Visibility = vis; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs index f6512d2f8b11..b4fc99e0abe7 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs @@ -13,9 +13,11 @@ public class CSVariableDeclaration : LineCodeElementCollection, IC public CSVariableDeclaration(CSType type, IEnumerable bindings) : base(null, false, true) { - Type = Exceptions.ThrowOnNull(type, "type"); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(bindings, nameof(bindings)); + Type = type; And(Type).And(SimpleElement.Spacer); - Bindings = new CommaListElementCollection(Exceptions.ThrowOnNull(bindings, "bindings")); + Bindings = new CommaListElementCollection(bindings); Add(Bindings); } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs index 3e5ad11de975..26d618a55575 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs @@ -11,7 +11,8 @@ public class CSFileBasic : ICodeElementSet public CSFileBasic(string nameSpace) { - this.nameSpace = Exceptions.ThrowOnNull(nameSpace, "nameSpace"); + ArgumentNullException.ThrowIfNull(nameSpace, nameof(nameSpace)); + this.nameSpace = nameSpace; Using = new CSUsingPackages(); Classes = new CSClasses(); } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs index 2d76968ca9c5..2f29dbc29399 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs @@ -11,9 +11,12 @@ public class CSFixedCodeBlock : CSCodeBlock, ICSStatement public CSFixedCodeBlock(CSType type, CSIdentifier ident, CSBaseExpression expr, IEnumerable body) : base(body) { - Type = Exceptions.ThrowOnNull(type, "type"); - Identifier = Exceptions.ThrowOnNull(ident, "ident"); - Expr = Exceptions.ThrowOnNull(expr, "expr"); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(ident, nameof(ident)); + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); + Type = type; + Identifier = ident; + Expr = expr; } public override void Write(ICodeWriter writer, object o) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs index 445ce3695c85..f850cff6d2df 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs @@ -45,9 +45,11 @@ protected override void LLWrite(ICodeWriter writer, object o) public CSForEach(CSType type, CSIdentifier ident, CSBaseExpression expr, CSCodeBlock body) { + ArgumentNullException.ThrowIfNull(ident, nameof(ident)); + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); Type = type; - Ident = Exceptions.ThrowOnNull(ident, nameof(ident)); - Expr = Exceptions.ThrowOnNull(expr, nameof(expr)); + Ident = ident; + Expr = expr; Body = body ?? new CSCodeBlock(); Add(new ForElement(type, ident, expr)); Add(Body); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs index 02e250877d10..c69531c1835c 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs @@ -9,8 +9,10 @@ public class CSFunctionCall : CSBaseExpression, ICSLineable { public CSFunctionCall(CSIdentifier ident, CommaListElementCollection paramList, bool isConstructor = false) { - Name = Exceptions.ThrowOnNull(ident, "ident"); - Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + ArgumentNullException.ThrowIfNull(ident, nameof(ident)); + ArgumentNullException.ThrowIfNull(paramList, nameof(paramList)); + Name = ident; + Parameters = paramList; IsConstructor = isConstructor; } @@ -65,7 +67,8 @@ public static CSLine FunctionCallLine(string identifier, params CSBaseExpression public static CSLine FunctionCallLine(string identifier, bool isConstructor, params CSBaseExpression[] parameters) { - return new CSLine(new CSFunctionCall(new CSIdentifier(Exceptions.ThrowOnNull(identifier, "identifier")), + ArgumentNullException.ThrowIfNull(identifier, nameof(identifier)); + return new CSLine(new CSFunctionCall(new CSIdentifier(identifier), new CommaListElementCollection(parameters), isConstructor)); } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs index 36539f39a64a..606539126221 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs @@ -10,14 +10,17 @@ public class CSGenericConstraint : DelegatedSimpleElement { public CSGenericConstraint(CSIdentifier name, CSIdentifier isA) { - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(isA, nameof(isA)); + Name = name; IsA = new CommaListElementCollection(); - IsA.Add(Exceptions.ThrowOnNull(isA, nameof(isA))); + IsA.Add(isA); } public CSGenericConstraint(CSIdentifier name, IEnumerable multiIs) { - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; IsA = new CommaListElementCollection(); if (multiIs != null) IsA.AddRange(multiIs); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs index 58c3c6b466cd..cf5db8e79a68 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs @@ -10,7 +10,8 @@ public class CSGenericTypeDeclaration { public CSGenericTypeDeclaration(CSIdentifier name) { - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; } public CSIdentifier Name { get; private set; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs index 856bbea1ee3b..4fb13707c02c 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs @@ -10,7 +10,8 @@ public class CSIdentifier : CSBaseExpression { public CSIdentifier(string name) { - Name = Exceptions.ThrowOnNull(name, "name"); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + Name = name; } public static explicit operator CSIdentifier(string name) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs index ffcff9b5c823..e0a6a1db9c7a 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs @@ -31,8 +31,10 @@ protected override void LLWrite(ICodeWriter writer, object o) public CSIfElse(CSBaseExpression condition, CSCodeBlock ifClause, CSCodeBlock elseClause = null) : base() { - Condition = new CSIfElement(Exceptions.ThrowOnNull(condition, "condition")); - IfClause = Exceptions.ThrowOnNull(ifClause, "ifClause"); + ArgumentNullException.ThrowIfNull(condition, nameof(condition)); + ArgumentNullException.ThrowIfNull(ifClause, nameof(ifClause)); + Condition = new CSIfElement(condition); + IfClause = ifClause; ElseClause = elseClause; Add(Condition); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs index 8ec0d0656377..62b0df4a4edf 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs @@ -9,9 +9,11 @@ public class CSIndexExpression : CSBaseExpression { public CSIndexExpression(CSBaseExpression aggregate, CommaListElementCollection paramList, bool addParensAroundAggregate) { + ArgumentNullException.ThrowIfNull(aggregate, nameof(aggregate)); + ArgumentNullException.ThrowIfNull(paramList, nameof(paramList)); AddParensAroundAggregate = addParensAroundAggregate; - Aggregate = Exceptions.ThrowOnNull(aggregate, "aggregate"); - Parameters = Exceptions.ThrowOnNull(paramList, "paramList"); + Aggregate = aggregate; + Parameters = paramList; } public CSIndexExpression(string identifier, bool addParensAroundAggregate, params CSBaseExpression[] parameters) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs index 77f91acd69cb..58d3a9b3547d 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs @@ -23,7 +23,7 @@ public CSInheritance(params string[] identifiers) public void Add(Type t) { - Exceptions.ThrowOnNull(t, "t"); + ArgumentNullException.ThrowIfNull(t, "t"); Add(new CSIdentifier(t.Name)); } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs index 8293e4453ed1..388dcd9dd6ad 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs @@ -27,8 +27,10 @@ public class CSInitializedType : CSBaseExpression { public CSInitializedType(CSFunctionCall call, CSInitializer initializer) { - Call = Exceptions.ThrowOnNull(call, nameof(call)); - Initializer = Exceptions.ThrowOnNull(initializer, nameof(initializer)); + ArgumentNullException.ThrowIfNull(call, nameof(call)); + ArgumentNullException.ThrowIfNull(initializer, nameof(initializer)); + Call = call; + Initializer = initializer; } public CSInitializedType(CSFunctionCall call, IEnumerable parameters, bool appendNewlineAfterEach) diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs index 37faa49174be..26eec748786b 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs @@ -12,8 +12,9 @@ public class CSInterface : ICodeElementSet, ICSTopLevelDeclaration public CSInterface(CSVisibility vis, CSIdentifier name, IEnumerable methods = null) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); Visibility = vis; - Name = Exceptions.ThrowOnNull(name, "name"); + Name = name; Inheritance = new CSInheritance(); Methods = new List(); Properties = new List(); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs index 834ae0819117..26d3ede9f7d4 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs @@ -11,8 +11,9 @@ public class CSLambda : CSBaseExpression { public CSLambda(CSParameterList parameters, ICSExpression value) { + ArgumentNullException.ThrowIfNull(value, nameof(value)); Parameters = parameters ?? new CSParameterList(); - Value = Exceptions.ThrowOnNull(value, "value"); + Value = value; Body = null; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs index b76d4cc502df..283814feffb6 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs @@ -10,7 +10,8 @@ public class CSLine : DelegatedSimpleElement, ICSStatement { public CSLine(ICodeElement contents, bool addSemicolon = true) { - Contents = Exceptions.ThrowOnNull(contents, nameof(contents)); + ArgumentNullException.ThrowIfNull(contents, nameof(contents)); + Contents = contents; if (!(contents is ICSLineable) && addSemicolon) throw new ArgumentException("contents must be ILineable", nameof(contents)); AddSemicolon = addSemicolon; diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs index 9377a859be0f..95c5731075ee 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs @@ -19,13 +19,15 @@ public CSMethod(CSVisibility vis, CSMethodKind kind, CSType type, CSIdentifier n CSParameterList parms, CSBaseExpression[] baseOrThisCallParms, bool callsBase, CSCodeBlock body, bool isSealed = false, bool isAsync = false) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(parms, nameof(parms)); GenericParameters = new CSGenericTypeDeclarationCollection(); GenericConstraints = new CSGenericConstraintCollection(); Visibility = vis; Kind = kind; Type = type; // no throw on null - could be constructor - Name = Exceptions.ThrowOnNull(name, nameof(name)); - Parameters = Exceptions.ThrowOnNull(parms, nameof(parms)); + Name = name; + Parameters = parms; CallsBase = callsBase; BaseOrThisCallParameters = baseOrThisCallParms; @@ -170,39 +172,46 @@ public static string MethodKindToString(CSMethodKind kind) public static CSMethod PublicMethod(CSType type, string name, CSParameterList parms, CSCodeBlock body) { - return new CSMethod(CSVisibility.Public, CSMethodKind.None, type, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + ArgumentNullException.ThrowIfNull(body, nameof(body)); + return new CSMethod(CSVisibility.Public, CSMethodKind.None, type, new CSIdentifier(name), parms, body); } public static CSMethod PublicMethod(CSMethodKind kind, CSType type, string name, CSParameterList parms, CSCodeBlock body) { - return new CSMethod(CSVisibility.Public, kind, type, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + ArgumentNullException.ThrowIfNull(body, nameof(body)); + return new CSMethod(CSVisibility.Public, kind, type, new CSIdentifier(name), parms, body); } public static CSMethod PublicConstructor(string name, CSParameterList parms, CSCodeBlock body) { - return new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + ArgumentNullException.ThrowIfNull(body, nameof(body)); + return new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier(name), parms, body); } public static CSMethod PublicConstructor(string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression[] baseParams) { + ArgumentNullException.ThrowIfNull(body, nameof(body)); return new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier(name), parms, - baseParams, true, Exceptions.ThrowOnNull(body, "body")); + baseParams, true, body); } public static CSMethod PrivateConstructor(string name, CSParameterList parms, CSCodeBlock body) { - return new CSMethod(CSVisibility.None, CSMethodKind.None, null, new CSIdentifier(name), parms, Exceptions.ThrowOnNull(body, "body")); + ArgumentNullException.ThrowIfNull(body, nameof(body)); + return new CSMethod(CSVisibility.None, CSMethodKind.None, null, new CSIdentifier(name), parms, body); } public static CSMethod PrivateConstructor(string name, CSParameterList parms, CSCodeBlock body, params CSBaseExpression[] baseParams) { + ArgumentNullException.ThrowIfNull(body, nameof(body)); return new CSMethod(CSVisibility.None, CSMethodKind.None, null, new CSIdentifier(name), parms, - baseParams, true, Exceptions.ThrowOnNull(body, "body")); + baseParams, true, body); } public static CSMethod PInvoke(CSVisibility vis, CSType type, string name, string dllName, string externName, CSParameterList parms) { - CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull(type, "type"), + ArgumentNullException.ThrowIfNull(type, nameof(type)); + CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, type, new CSIdentifier(name), parms, null); CSAttribute.DllImport(dllName, externName).AttachBefore(method); @@ -212,7 +221,8 @@ public static CSMethod PInvoke(CSVisibility vis, CSType type, string name, strin public static CSMethod PInvoke(CSVisibility vis, CSType type, string name, CSBaseExpression dllName, string externName, CSParameterList parms) { - CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, Exceptions.ThrowOnNull(type, "type"), + ArgumentNullException.ThrowIfNull(type, nameof(type)); + CSMethod method = new CSMethod(vis, CSMethodKind.StaticExtern, type, new CSIdentifier(name), parms, null); CSAttribute.DllImport(dllName, externName).AttachBefore(method); diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs index d3bd9241e9da..b967392f3d3f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs @@ -17,7 +17,7 @@ public CSNamespace() } public CSNamespace(string nameSpace) - : base(new SimpleLineElement(string.Format("namespace {0}", Exceptions.ThrowOnNull(nameSpace, nameof(nameSpace))), + : base(new SimpleLineElement(string.Format("namespace {0}", nameSpace), false, true, false), new DecoratedCodeElementCollection("{", "}", true, true, true)) { @@ -46,7 +46,8 @@ public CSNamespaceBlock And(string s) public CSNamespaceBlock And(CSNamespace ns) { - Add(Exceptions.ThrowOnNull(ns, "ns")); + ArgumentNullException.ThrowIfNull(ns, nameof(ns)); + Add(ns); return this; } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs index 7307d025a33b..bfd4c5759b33 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs @@ -15,8 +15,10 @@ public class CSParameter : DelegatedSimpleElement CSParameterKind parameterKind = CSParameterKind.None, CSConstant defaultValue = null) { - CSType = Exceptions.ThrowOnNull(type, nameof(type)); - Name = Exceptions.ThrowOnNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + CSType = type; + Name = name; ParameterKind = parameterKind; DefaultValue = defaultValue; } @@ -99,7 +101,8 @@ public CSParameterList(params CSParameter[] parameters) public CSParameterList And(CSParameter parameter) { - Add(Exceptions.ThrowOnNull(parameter, nameof(parameter))); + ArgumentNullException.ThrowIfNull(parameter, nameof(parameter)); + Add(parameter); return this; } @@ -107,8 +110,10 @@ public CSParameterList And(CSParameter parameter) CSParameterKind parameterKind = CSParameterKind.None, CSConstant defaultValue = null) { - return And(new CSParameter(new CSSimpleType(Exceptions.ThrowOnNull(type, nameof(type))), - new CSIdentifier(Exceptions.ThrowOnNull(identifier, nameof(identifier))), parameterKind, defaultValue)); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(identifier, nameof(identifier)); + return And(new CSParameter(new CSSimpleType(type), + new CSIdentifier(identifier), parameterKind, defaultValue)); } } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs index c732cc0b1a54..a5f5acefe050 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs @@ -9,7 +9,8 @@ public class CSParenthesisExpression : CSBaseExpression { public CSParenthesisExpression(ICSExpression within) { - Within = Exceptions.ThrowOnNull(within, "within"); + ArgumentNullException.ThrowIfNull(within, nameof(within)); + Within = within; } public ICSExpression Within { get; private set; } @@ -31,8 +32,10 @@ public CSCastExpression(string type, ICSExpression toCast) public CSCastExpression(CSType type, ICSExpression toCast) { - Type = Exceptions.ThrowOnNull(type, "type"); - ToCast = Exceptions.ThrowOnNull(toCast, "toCast"); + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(toCast, nameof(toCast)); + Type = type; + ToCast = toCast; } public CSType Type { get; private set; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs index 47620400afe8..716c8c95aa7f 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs @@ -32,7 +32,7 @@ public class CSProperty : CodeElementCollection CSVisibility getVis, CSCodeBlock getter, CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) : this(type, kind, new CSIdentifier("this"), getVis, getter, setVis, setter, - Exceptions.ThrowOnNull(parms, nameof(parms))) + parms) { } @@ -40,6 +40,8 @@ public class CSProperty : CodeElementCollection CSVisibility getVis, CSCodeBlock getter, CSVisibility setVis, CSCodeBlock setter, CSParameterList parms) { + ArgumentNullException.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(name, nameof(name)); bool unifiedVis = getVis == setVis; IndexerParameters = parms; @@ -55,8 +57,8 @@ public class CSProperty : CodeElementCollection PropType = type; Name = name; - decl.And(Exceptions.ThrowOnNull(type, "type")).And(SimpleElement.Spacer) - .And(Exceptions.ThrowOnNull(name, nameof(name))); + decl.And(type).And(SimpleElement.Spacer) + .And(name); if (parms != null) { decl.And(new SimpleElement("[", true)).And(parms).And(new SimpleElement("]")); @@ -130,9 +132,10 @@ public static CSProperty PublicGetPrivateSet(CSType type, string name) static CSProperty PublicGetPubPrivSetBacking(CSType type, string name, bool declareField, bool setIsPublic, string backingFieldName = null) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); if (!declareField && backingFieldName == null) throw new ArgumentException("declareField must be true if there is no supplied field name", nameof(declareField)); - backingFieldName = backingFieldName ?? MassageName(Exceptions.ThrowOnNull(name, nameof(name))); + backingFieldName = backingFieldName ?? MassageName(name); CSIdentifier backingIdent = new CSIdentifier(backingFieldName); @@ -165,12 +168,14 @@ public static CSProperty PublicGetPrivateSetBacking(CSType type, string name, bo public static CSProperty PublicGetBacking(CSType type, CSIdentifier name, CSIdentifier backingFieldName, bool includeBackingFieldDeclaration = false, CSMethodKind methodKind = CSMethodKind.None) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(backingFieldName, nameof(backingFieldName)); LineCodeElementCollection getCode = new LineCodeElementCollection( new ICodeElement[] { - CSReturn.ReturnLine (Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))) + CSReturn.ReturnLine (backingFieldName) }, false, true); - CSProperty prop = new CSProperty(type, methodKind, Exceptions.ThrowOnNull(name, nameof(name)), + CSProperty prop = new CSProperty(type, methodKind, name, CSVisibility.Public, new CSCodeBlock(getCode), CSVisibility.Public, null); if (includeBackingFieldDeclaration) @@ -181,9 +186,11 @@ public static CSProperty PublicGetPrivateSetBacking(CSType type, string name, bo public static CSProperty PublicGetBacking(CSType type, string name, string backingFieldName, bool includeBackingFieldDeclaration = false) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(backingFieldName, nameof(backingFieldName)); return PublicGetBacking(type, - new CSIdentifier(Exceptions.ThrowOnNull(name, nameof(name))), - new CSIdentifier(Exceptions.ThrowOnNull(backingFieldName, nameof(backingFieldName))), + new CSIdentifier(name), + new CSIdentifier(backingFieldName), includeBackingFieldDeclaration); } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs index cf4fb47dc11c..e4c73ddb38e8 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs @@ -9,9 +9,12 @@ public class CSTernary : CSBaseExpression { public CSTernary(CSBaseExpression predicate, CSBaseExpression onTrue, CSBaseExpression onFalse, bool addParentheses) { - Predicate = Exceptions.ThrowOnNull(predicate, "predicate"); - OnTrue = Exceptions.ThrowOnNull(onTrue, "onTrue"); - OnFalse = Exceptions.ThrowOnNull(onFalse, "onFalse"); + ArgumentNullException.ThrowIfNull(predicate, nameof(predicate)); + ArgumentNullException.ThrowIfNull(onTrue, nameof(onTrue)); + ArgumentNullException.ThrowIfNull(onFalse, nameof(onFalse)); + Predicate = predicate; + OnTrue = onTrue; + OnFalse = onFalse; AddParentheses = addParentheses; } public CSBaseExpression Predicate { get; private set; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs index 91a880271cc8..09d429718032 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs @@ -9,7 +9,8 @@ public class CSThrow : CSBaseExpression, ICSStatement, ICSLineable { public CSThrow(CSBaseExpression expr) { - Expr = Exceptions.ThrowOnNull(expr, "expr"); + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); + Expr = expr; } public CSBaseExpression Expr { get; private set; } @@ -39,8 +40,9 @@ protected override void LLWrite(ICodeWriter writer, object o) public static CSLine ThrowLine(T exType, CSBaseExpression expr) where T : Exception { + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); CommaListElementCollection args = new CommaListElementCollection(); - args.Add(Exceptions.ThrowOnNull(expr, nameof(expr))); + args.Add(expr); return ThrowLine(exType, args); } } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs index 92d226624160..768f4ef7fea2 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs @@ -58,7 +58,8 @@ public CSSimpleType(CSSimpleType csSimpleType) public CSSimpleType(string name, bool isArray) { - hiddenName = Exceptions.ThrowOnNull(name, "name") + (isArray ? "[]" : ""); + ArgumentNullException.ThrowIfNull(name, nameof(name)); + hiddenName = name + (isArray ? "[]" : ""); } public static explicit operator CSSimpleType(string name) @@ -73,9 +74,10 @@ public static CSSimpleType CreateArray(string name) public CSSimpleType(string name, bool isArray, params CSType[] genericSpecialization) { + ArgumentNullException.ThrowIfNull(name, nameof(name)); IsGeneric = genericSpecialization != null && genericSpecialization.Length > 0; GenericTypes = genericSpecialization; - GenericTypeName = Exceptions.ThrowOnNull(name, nameof(name)); + GenericTypeName = name; IsArray = isArray; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs index a05e0e33a3a9..bf9f21363692 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs @@ -9,8 +9,9 @@ public class CSUnaryExpression : CSBaseExpression { public CSUnaryExpression(CSUnaryOperator op, ICSExpression expr) { + ArgumentNullException.ThrowIfNull(expr, nameof(expr)); Operation = op; - Expr = Exceptions.ThrowOnNull(expr, nameof(expr)); + Expr = expr; } protected override void LLWrite(ICodeWriter writer, object o) { diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs index 359f0d1fc6a9..f822988f4e2a 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs @@ -11,7 +11,7 @@ namespace SyntaxDynamo.CSLang public class CSUsing : SimpleLineElement { public CSUsing(string package) - : base(string.Format("using {0};", Exceptions.ThrowOnNull(package, nameof(package))), false, false, false) + : base(string.Format("using {0};", package), false, false, false) { Package = package; } diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs index c7b2459a5d93..3bd0a33d066d 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs +++ b/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs @@ -12,7 +12,8 @@ public class CSTopLevelDeclations : CodeElementCollection Date: Wed, 21 Feb 2024 16:50:04 +0100 Subject: [PATCH 31/37] Update target framework to net8.0 --- global.json | 4 ++-- src/SwiftBindings/src/SwiftBindings.csproj | 2 +- src/SwiftBindings/tests/SwiftBindings.Tests.csproj | 2 +- src/SwiftReflector/SwiftReflector.csproj | 4 +--- src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj | 2 +- src/SyntaxDynamo/SyntaxDynamo.csproj | 2 +- src/samples/HelloWorld/HelloWorld.csproj | 2 +- 7 files changed, 8 insertions(+), 10 deletions(-) diff --git a/global.json b/global.json index e62916b1b7c8..c5c66e5ff962 100644 --- a/global.json +++ b/global.json @@ -1,11 +1,11 @@ { "sdk": { - "version": "7.0.100", + "version": "8.0.100", "allowPrerelease": true, "rollForward": "major" }, "tools": { - "dotnet": "7.0.100" + "dotnet": "8.0.100" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.22430.3" diff --git a/src/SwiftBindings/src/SwiftBindings.csproj b/src/SwiftBindings/src/SwiftBindings.csproj index 991ccbd4e6fa..08f73f605ad7 100644 --- a/src/SwiftBindings/src/SwiftBindings.csproj +++ b/src/SwiftBindings/src/SwiftBindings.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable disable diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index e9bedd90a5dc..8e450143cb2f 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,6 +1,6 @@ - net7.0 + net8.0 cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make diff --git a/src/SwiftReflector/SwiftReflector.csproj b/src/SwiftReflector/SwiftReflector.csproj index 84a51f3ee95a..c4ce481df76c 100644 --- a/src/SwiftReflector/SwiftReflector.csproj +++ b/src/SwiftReflector/SwiftReflector.csproj @@ -1,7 +1,7 @@  Library - net7.0 + net8.0 enable disable true @@ -10,7 +10,5 @@ - - diff --git a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj index de826e1d007c..aa237dc759f5 100644 --- a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj +++ b/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj @@ -1,7 +1,7 @@  Library - net7.0 + net8.0 enable disable true diff --git a/src/SyntaxDynamo/SyntaxDynamo.csproj b/src/SyntaxDynamo/SyntaxDynamo.csproj index 9cce3e52d3c7..c93a4aeb0ac9 100644 --- a/src/SyntaxDynamo/SyntaxDynamo.csproj +++ b/src/SyntaxDynamo/SyntaxDynamo.csproj @@ -1,7 +1,7 @@  Library - net7.0 + net8.0 enable disable true diff --git a/src/samples/HelloWorld/HelloWorld.csproj b/src/samples/HelloWorld/HelloWorld.csproj index ec31b78f5c8b..fddc7980db97 100644 --- a/src/samples/HelloWorld/HelloWorld.csproj +++ b/src/samples/HelloWorld/HelloWorld.csproj @@ -1,7 +1,7 @@ Exe - net7.0 + net8.0 enable disable From 497cbe183a9615cd95be480894504ff833d3da2e Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Wed, 21 Feb 2024 17:21:03 +0100 Subject: [PATCH 32/37] Add src and tests directories for projects --- SwiftBindings.sln | 84 +++++++++++++++++++ src/SwiftBindings/SwiftBindings.sln | 48 ----------- src/SwiftBindings/src/SwiftBindings.csproj | 6 +- .../tests/SwiftBindings.Tests.csproj | 5 +- src/SwiftReflector/{ => src}/Enums.cs | 0 src/SwiftReflector/{ => src}/ErrorHandling.cs | 0 .../{ => src}/ExceptionTools/ErrorHelper.cs | 0 .../ExceptionTools/RuntimeException.cs | 0 src/SwiftReflector/{ => src}/Extensions.cs | 0 .../{ => src}/Parser/ISwiftParser.cs | 0 .../Parser/SwiftABIParser/SwiftABIParser.cs | 0 .../Parser/SwiftInterfaceParser/.gitkeep | 0 .../{ => src}/ReflectorError.cs | 0 .../{ => src}/SwiftClassName.cs | 0 src/SwiftReflector/{ => src}/SwiftName.cs | 0 .../{ => src}/SwiftReflector.csproj | 4 +- src/SwiftReflector/{ => src}/SwiftType.cs | 0 .../AssociatedTypeDeclaration.cs | 0 .../AttributeDeclaration.cs | 0 .../SwiftXmlReflection/BaseConstraint.cs | 0 .../SwiftXmlReflection/BaseDeclaration.cs | 0 .../SwiftXmlReflection/ClassDeclaration.cs | 0 .../SwiftXmlReflection/EnumDeclaration.cs | 0 .../SwiftXmlReflection/EnumElement.cs | 0 .../{ => src}/SwiftXmlReflection/Enums.cs | 0 .../ExtensionDeclaration.cs | 0 .../SwiftXmlReflection/ExtensionMethods.cs | 0 .../SwiftXmlReflection/FunctionDeclaration.cs | 0 .../SwiftXmlReflection/GenericDeclaration.cs | 0 .../GenericDeclarationCollection.cs | 0 .../GenericReferenceAssociatedTypeProtocol.cs | 0 .../IXElementConvertible.cs | 0 .../SwiftXmlReflection/Inheritance.cs | 0 .../{ => src}/SwiftXmlReflection/Member.cs | 0 .../SwiftXmlReflection/ModuleDeclaration.cs | 0 .../SwiftXmlReflection/OperatorDeclaration.cs | 0 .../SwiftXmlReflection/ParameterItem.cs | 0 .../SwiftXmlReflection/PropertyDeclaration.cs | 0 .../SwiftXmlReflection/ProtocolDeclaration.cs | 0 .../SwiftXmlReflection/ShamDeclaration.cs | 0 .../SwiftXmlReflection/StructDeclaration.cs | 0 .../SubscriptDeclaration.cs | 0 .../TypeAliasDeclaration.cs | 0 .../SwiftXmlReflection/TypeAliasFolder.cs | 0 .../SwiftXmlReflection/TypeDeclaration.cs | 0 .../{ => src}/SwiftXmlReflection/TypeSpec.cs | 0 .../SwiftXmlReflection/TypeSpecParser.cs | 0 .../SwiftXmlReflection/TypeSpecToken.cs | 0 .../SwiftXmlReflection/TypeSpecTokenizer.cs | 0 .../{ => src}/TypeMapping/Entity.cs | 0 .../{ => src}/TypeMapping/ModuleDatabase.cs | 0 .../{ => src}/TypeMapping/NetParam.cs | 0 .../{ => src}/TypeMapping/NetTypeBundle.cs | 0 .../{ => src}/TypeMapping/TypeDatabase.cs | 0 .../{ => src}/TypeMapping/TypeMapper.cs | 0 src/SwiftReflector/{ => src}/UnicodeMapper.cs | 0 .../tests/SwiftReflector.Tests.csproj | 12 +++ src/SwiftReflector/tests/UnitTest1.cs | 12 +++ .../{ => src}/ISwiftObject.cs | 0 .../{ => src}/SwiftCore.xml | 0 .../{ => src}/SwiftRuntimeLibrary.csproj | 0 .../tests/SwiftRuntimeLibrary.Tests.csproj | 12 +++ src/SwiftRuntimeLibrary/tests/UnitTest1.cs | 12 +++ .../{ => src}/CodeElementCollection.cs | 0 src/SyntaxDynamo/{ => src}/CodeWriter.cs | 0 .../{ => src}/CommaListElementCollection.cs | 0 .../DecoratedCodeElementCollection.cs | 0 .../DelegatedCommaListElementCollection.cs | 0 .../{ => src}/DelegatedSimpleElement.cs | 0 src/SyntaxDynamo/{ => src}/Extensions.cs | 0 src/SyntaxDynamo/{ => src}/ICodeElement.cs | 0 src/SyntaxDynamo/{ => src}/ICodeElementSet.cs | 0 src/SyntaxDynamo/{ => src}/ICodeWriter.cs | 0 .../{ => src}/LabeledCodeElementCollection.cs | 0 .../{ => src}/LineCodeElementCollection.cs | 0 src/SyntaxDynamo/{ => src}/SimpleElement.cs | 0 .../{ => src}/SimpleLineElement.cs | 0 .../SyntaxDynamo.CSLang/CSArgument.cs | 0 .../SyntaxDynamo.CSLang/CSArray1D.cs | 0 .../SyntaxDynamo.CSLang/CSAssignment.cs | 0 .../SyntaxDynamo.CSLang/CSAttribute.cs | 0 .../SyntaxDynamo.CSLang/CSBaseExpression.cs | 0 .../SyntaxDynamo.CSLang/CSBinaryExpression.cs | 0 .../SyntaxDynamo.CSLang/CSBinding.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSClass.cs | 0 .../SyntaxDynamo.CSLang/CSCodeBlock.cs | 0 .../SyntaxDynamo.CSLang/CSComment.cs | 0 .../CSConditionalCompilation.cs | 0 .../SyntaxDynamo.CSLang/CSConstant.cs | 0 .../SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSEnum.cs | 0 .../SyntaxDynamo.CSLang/CSFieldDeclaration.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSFile.cs | 0 .../SyntaxDynamo.CSLang/CSFileBasic.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSFixed.cs | 0 .../SyntaxDynamo.CSLang/CSForEach.cs | 0 .../SyntaxDynamo.CSLang/CSFunctionCall.cs | 0 .../CSGenericConstraint.cs | 0 .../CSGenericTypeDeclaration.cs | 0 .../SyntaxDynamo.CSLang/CSIdentifier.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSIfElse.cs | 0 .../SyntaxDynamo.CSLang/CSIndexExpression.cs | 0 .../SyntaxDynamo.CSLang/CSInheritance.cs | 0 .../SyntaxDynamo.CSLang/CSInitializer.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSInject.cs | 0 .../SyntaxDynamo.CSLang/CSInterface.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSLambda.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSLine.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSMethod.cs | 0 .../SyntaxDynamo.CSLang/CSNamespace.cs | 0 .../SyntaxDynamo.CSLang/CSParameter.cs | 0 .../CSParenthesisExpression.cs | 0 .../SyntaxDynamo.CSLang/CSProperty.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSReturn.cs | 0 .../SyntaxDynamo.CSLang/CSShortCircuit.cs | 0 .../SyntaxDynamo.CSLang/CSTernary.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSThrow.cs | 0 .../SyntaxDynamo.CSLang/CSTryCatch.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSType.cs | 0 .../SyntaxDynamo.CSLang/CSUnaryExpression.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/CSUsing.cs | 0 .../{ => src}/SyntaxDynamo.CSLang/Enums.cs | 0 .../SyntaxDynamo.CSLang/ICSExpression.cs | 0 .../SyntaxDynamo.CSLang/ICSLineable.cs | 0 .../SyntaxDynamo.CSLang/ICSStatement.cs | 0 .../ICSTopLevelDeclaration.cs | 0 .../{ => src}/SyntaxDynamo.csproj | 0 src/SyntaxDynamo/{ => src}/WriteEventArgs.cs | 0 .../tests/SyntaxDynamo.Tests.csproj | 12 +++ src/SyntaxDynamo/tests/UnitTest1.cs | 12 +++ 130 files changed, 165 insertions(+), 54 deletions(-) delete mode 100644 src/SwiftBindings/SwiftBindings.sln rename src/SwiftReflector/{ => src}/Enums.cs (100%) rename src/SwiftReflector/{ => src}/ErrorHandling.cs (100%) rename src/SwiftReflector/{ => src}/ExceptionTools/ErrorHelper.cs (100%) rename src/SwiftReflector/{ => src}/ExceptionTools/RuntimeException.cs (100%) rename src/SwiftReflector/{ => src}/Extensions.cs (100%) rename src/SwiftReflector/{ => src}/Parser/ISwiftParser.cs (100%) rename src/SwiftReflector/{ => src}/Parser/SwiftABIParser/SwiftABIParser.cs (100%) rename src/SwiftReflector/{ => src}/Parser/SwiftInterfaceParser/.gitkeep (100%) rename src/SwiftReflector/{ => src}/ReflectorError.cs (100%) rename src/SwiftReflector/{ => src}/SwiftClassName.cs (100%) rename src/SwiftReflector/{ => src}/SwiftName.cs (100%) rename src/SwiftReflector/{ => src}/SwiftReflector.csproj (69%) rename src/SwiftReflector/{ => src}/SwiftType.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/AssociatedTypeDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/AttributeDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/BaseConstraint.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/BaseDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ClassDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/EnumDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/EnumElement.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/Enums.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ExtensionDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ExtensionMethods.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/FunctionDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/GenericDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/GenericDeclarationCollection.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/IXElementConvertible.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/Inheritance.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/Member.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ModuleDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/OperatorDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ParameterItem.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/PropertyDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ProtocolDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/ShamDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/StructDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/SubscriptDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeAliasDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeAliasFolder.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeDeclaration.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeSpec.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeSpecParser.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeSpecToken.cs (100%) rename src/SwiftReflector/{ => src}/SwiftXmlReflection/TypeSpecTokenizer.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/Entity.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/ModuleDatabase.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/NetParam.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/NetTypeBundle.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/TypeDatabase.cs (100%) rename src/SwiftReflector/{ => src}/TypeMapping/TypeMapper.cs (100%) rename src/SwiftReflector/{ => src}/UnicodeMapper.cs (100%) create mode 100644 src/SwiftReflector/tests/SwiftReflector.Tests.csproj create mode 100644 src/SwiftReflector/tests/UnitTest1.cs rename src/SwiftRuntimeLibrary/{ => src}/ISwiftObject.cs (100%) rename src/SwiftRuntimeLibrary/{ => src}/SwiftCore.xml (100%) rename src/SwiftRuntimeLibrary/{ => src}/SwiftRuntimeLibrary.csproj (100%) create mode 100644 src/SwiftRuntimeLibrary/tests/SwiftRuntimeLibrary.Tests.csproj create mode 100644 src/SwiftRuntimeLibrary/tests/UnitTest1.cs rename src/SyntaxDynamo/{ => src}/CodeElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/CodeWriter.cs (100%) rename src/SyntaxDynamo/{ => src}/CommaListElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/DecoratedCodeElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/DelegatedCommaListElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/DelegatedSimpleElement.cs (100%) rename src/SyntaxDynamo/{ => src}/Extensions.cs (100%) rename src/SyntaxDynamo/{ => src}/ICodeElement.cs (100%) rename src/SyntaxDynamo/{ => src}/ICodeElementSet.cs (100%) rename src/SyntaxDynamo/{ => src}/ICodeWriter.cs (100%) rename src/SyntaxDynamo/{ => src}/LabeledCodeElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/LineCodeElementCollection.cs (100%) rename src/SyntaxDynamo/{ => src}/SimpleElement.cs (100%) rename src/SyntaxDynamo/{ => src}/SimpleLineElement.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSArgument.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSArray1D.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSAssignment.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSAttribute.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSBaseExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSBinaryExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSBinding.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSClass.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSCodeBlock.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSComment.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSConditionalCompilation.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSConstant.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSEnum.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSFieldDeclaration.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSFile.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSFileBasic.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSFixed.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSForEach.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSFunctionCall.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSGenericConstraint.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSIdentifier.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSIfElse.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSIndexExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSInheritance.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSInitializer.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSInject.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSInterface.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSLambda.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSLine.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSMethod.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSNamespace.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSParameter.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSParenthesisExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSProperty.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSReturn.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSShortCircuit.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSTernary.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSThrow.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSTryCatch.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSType.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSUnaryExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/CSUsing.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/Enums.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/ICSExpression.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/ICSLineable.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/ICSStatement.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs (100%) rename src/SyntaxDynamo/{ => src}/SyntaxDynamo.csproj (100%) rename src/SyntaxDynamo/{ => src}/WriteEventArgs.cs (100%) create mode 100644 src/SyntaxDynamo/tests/SyntaxDynamo.Tests.csproj create mode 100644 src/SyntaxDynamo/tests/UnitTest1.cs diff --git a/SwiftBindings.sln b/SwiftBindings.sln index b9fbbaacd06f..29a0abcea382 100644 --- a/SwiftBindings.sln +++ b/SwiftBindings.sln @@ -7,6 +7,18 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings", "src\SwiftB EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings.Tests", "src\SwiftBindings\tests\SwiftBindings.Tests.csproj", "{CE81B6BD-CCCC-4223-9069-B28435A4A5C1}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftReflector.Tests", "src\SwiftReflector\tests\SwiftReflector.Tests.csproj", "{1C381A63-38D7-4801-97CB-5FA7F683E28A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftReflector", "src\SwiftReflector\src\SwiftReflector.csproj", "{EF015979-24E8-490E-B940-F28988EC5C19}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftRuntimeLibrary", "src\SwiftRuntimeLibrary\src\SwiftRuntimeLibrary.csproj", "{8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftRuntimeLibrary.Tests", "src\SwiftRuntimeLibrary\tests\SwiftRuntimeLibrary.Tests.csproj", "{61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyntaxDynamo", "src\SyntaxDynamo\src\SyntaxDynamo.csproj", "{E05ECC4A-7212-4077-AD30-E4183CA3C1AF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyntaxDynamo.Tests", "src\SyntaxDynamo\tests\SyntaxDynamo.Tests.csproj", "{0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -44,5 +56,77 @@ Global {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x64.Build.0 = Release|Any CPU {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.ActiveCfg = Release|Any CPU {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.Build.0 = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|x64.ActiveCfg = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|x64.Build.0 = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|x86.ActiveCfg = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Debug|x86.Build.0 = Debug|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|Any CPU.Build.0 = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|x64.ActiveCfg = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|x64.Build.0 = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|x86.ActiveCfg = Release|Any CPU + {1C381A63-38D7-4801-97CB-5FA7F683E28A}.Release|x86.Build.0 = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|x64.ActiveCfg = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|x64.Build.0 = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|x86.ActiveCfg = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Debug|x86.Build.0 = Debug|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|Any CPU.Build.0 = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|x64.ActiveCfg = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|x64.Build.0 = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|x86.ActiveCfg = Release|Any CPU + {EF015979-24E8-490E-B940-F28988EC5C19}.Release|x86.Build.0 = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|x64.ActiveCfg = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|x64.Build.0 = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|x86.ActiveCfg = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Debug|x86.Build.0 = Debug|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|x64.ActiveCfg = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|x64.Build.0 = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|x86.ActiveCfg = Release|Any CPU + {8E9013BE-01BD-4F4C-8BF7-E8C71FA6608E}.Release|x86.Build.0 = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|x64.ActiveCfg = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|x64.Build.0 = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|x86.ActiveCfg = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Debug|x86.Build.0 = Debug|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|Any CPU.Build.0 = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|x64.ActiveCfg = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|x64.Build.0 = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|x86.ActiveCfg = Release|Any CPU + {61F74BC6-1CCA-49FA-B5B8-6C9EABC1D0AB}.Release|x86.Build.0 = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|x64.ActiveCfg = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|x64.Build.0 = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|x86.ActiveCfg = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Debug|x86.Build.0 = Debug|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|Any CPU.Build.0 = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|x64.ActiveCfg = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|x64.Build.0 = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|x86.ActiveCfg = Release|Any CPU + {E05ECC4A-7212-4077-AD30-E4183CA3C1AF}.Release|x86.Build.0 = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|x64.ActiveCfg = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|x64.Build.0 = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|x86.ActiveCfg = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Debug|x86.Build.0 = Debug|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|Any CPU.Build.0 = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|x64.ActiveCfg = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|x64.Build.0 = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|x86.ActiveCfg = Release|Any CPU + {0C13F0AC-76F1-4FCB-AF42-9CB910A9471B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/src/SwiftBindings/SwiftBindings.sln b/src/SwiftBindings/SwiftBindings.sln deleted file mode 100644 index 039811c309a5..000000000000 --- a/src/SwiftBindings/SwiftBindings.sln +++ /dev/null @@ -1,48 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 -MinimumVisualStudioVersion = 15.0.26124.0 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings", "src\SwiftBindings.csproj", "{B7977360-6671-4707-9A1C-1C29D5BE2674}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwiftBindings.Tests", "tests\SwiftBindings.Tests.csproj", "{CE81B6BD-CCCC-4223-9069-B28435A4A5C1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x64.ActiveCfg = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x64.Build.0 = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x86.ActiveCfg = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Debug|x86.Build.0 = Debug|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|Any CPU.Build.0 = Release|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x64.ActiveCfg = Release|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x64.Build.0 = Release|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x86.ActiveCfg = Release|Any CPU - {B7977360-6671-4707-9A1C-1C29D5BE2674}.Release|x86.Build.0 = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x64.ActiveCfg = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x64.Build.0 = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x86.ActiveCfg = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Debug|x86.Build.0 = Debug|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|Any CPU.Build.0 = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x64.ActiveCfg = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x64.Build.0 = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.ActiveCfg = Release|Any CPU - {CE81B6BD-CCCC-4223-9069-B28435A4A5C1}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/src/SwiftBindings/src/SwiftBindings.csproj b/src/SwiftBindings/src/SwiftBindings.csproj index 08f73f605ad7..9b93fe028d76 100644 --- a/src/SwiftBindings/src/SwiftBindings.csproj +++ b/src/SwiftBindings/src/SwiftBindings.csproj @@ -7,9 +7,9 @@ disable - - - + + + diff --git a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj index 8e450143cb2f..936b41f4f89c 100644 --- a/src/SwiftBindings/tests/SwiftBindings.Tests.csproj +++ b/src/SwiftBindings/tests/SwiftBindings.Tests.csproj @@ -1,12 +1,15 @@ net8.0 + enable + disable + false + true cd $(OutputPath)$(TargetFramework) && cmake $(MSBuildThisFileDirectory) && make - diff --git a/src/SwiftReflector/Enums.cs b/src/SwiftReflector/src/Enums.cs similarity index 100% rename from src/SwiftReflector/Enums.cs rename to src/SwiftReflector/src/Enums.cs diff --git a/src/SwiftReflector/ErrorHandling.cs b/src/SwiftReflector/src/ErrorHandling.cs similarity index 100% rename from src/SwiftReflector/ErrorHandling.cs rename to src/SwiftReflector/src/ErrorHandling.cs diff --git a/src/SwiftReflector/ExceptionTools/ErrorHelper.cs b/src/SwiftReflector/src/ExceptionTools/ErrorHelper.cs similarity index 100% rename from src/SwiftReflector/ExceptionTools/ErrorHelper.cs rename to src/SwiftReflector/src/ExceptionTools/ErrorHelper.cs diff --git a/src/SwiftReflector/ExceptionTools/RuntimeException.cs b/src/SwiftReflector/src/ExceptionTools/RuntimeException.cs similarity index 100% rename from src/SwiftReflector/ExceptionTools/RuntimeException.cs rename to src/SwiftReflector/src/ExceptionTools/RuntimeException.cs diff --git a/src/SwiftReflector/Extensions.cs b/src/SwiftReflector/src/Extensions.cs similarity index 100% rename from src/SwiftReflector/Extensions.cs rename to src/SwiftReflector/src/Extensions.cs diff --git a/src/SwiftReflector/Parser/ISwiftParser.cs b/src/SwiftReflector/src/Parser/ISwiftParser.cs similarity index 100% rename from src/SwiftReflector/Parser/ISwiftParser.cs rename to src/SwiftReflector/src/Parser/ISwiftParser.cs diff --git a/src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs b/src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs similarity index 100% rename from src/SwiftReflector/Parser/SwiftABIParser/SwiftABIParser.cs rename to src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs diff --git a/src/SwiftReflector/Parser/SwiftInterfaceParser/.gitkeep b/src/SwiftReflector/src/Parser/SwiftInterfaceParser/.gitkeep similarity index 100% rename from src/SwiftReflector/Parser/SwiftInterfaceParser/.gitkeep rename to src/SwiftReflector/src/Parser/SwiftInterfaceParser/.gitkeep diff --git a/src/SwiftReflector/ReflectorError.cs b/src/SwiftReflector/src/ReflectorError.cs similarity index 100% rename from src/SwiftReflector/ReflectorError.cs rename to src/SwiftReflector/src/ReflectorError.cs diff --git a/src/SwiftReflector/SwiftClassName.cs b/src/SwiftReflector/src/SwiftClassName.cs similarity index 100% rename from src/SwiftReflector/SwiftClassName.cs rename to src/SwiftReflector/src/SwiftClassName.cs diff --git a/src/SwiftReflector/SwiftName.cs b/src/SwiftReflector/src/SwiftName.cs similarity index 100% rename from src/SwiftReflector/SwiftName.cs rename to src/SwiftReflector/src/SwiftName.cs diff --git a/src/SwiftReflector/SwiftReflector.csproj b/src/SwiftReflector/src/SwiftReflector.csproj similarity index 69% rename from src/SwiftReflector/SwiftReflector.csproj rename to src/SwiftReflector/src/SwiftReflector.csproj index c4ce481df76c..c0f115ffda2a 100644 --- a/src/SwiftReflector/SwiftReflector.csproj +++ b/src/SwiftReflector/src/SwiftReflector.csproj @@ -8,7 +8,7 @@ - - + + diff --git a/src/SwiftReflector/SwiftType.cs b/src/SwiftReflector/src/SwiftType.cs similarity index 100% rename from src/SwiftReflector/SwiftType.cs rename to src/SwiftReflector/src/SwiftType.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/AssociatedTypeDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/AssociatedTypeDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/AssociatedTypeDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/AttributeDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/AttributeDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/AttributeDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs b/src/SwiftReflector/src/SwiftXmlReflection/BaseConstraint.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/BaseConstraint.cs rename to src/SwiftReflector/src/SwiftXmlReflection/BaseConstraint.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/BaseDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/BaseDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/BaseDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/ClassDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ClassDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ClassDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/EnumDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/EnumDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/EnumDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/EnumElement.cs b/src/SwiftReflector/src/SwiftXmlReflection/EnumElement.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/EnumElement.cs rename to src/SwiftReflector/src/SwiftXmlReflection/EnumElement.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/Enums.cs b/src/SwiftReflector/src/SwiftXmlReflection/Enums.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/Enums.cs rename to src/SwiftReflector/src/SwiftXmlReflection/Enums.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/ExtensionDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ExtensionDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ExtensionDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs b/src/SwiftReflector/src/SwiftXmlReflection/ExtensionMethods.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ExtensionMethods.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ExtensionMethods.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/FunctionDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/FunctionDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/FunctionDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/GenericDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/GenericDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/GenericDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs b/src/SwiftReflector/src/SwiftXmlReflection/GenericDeclarationCollection.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/GenericDeclarationCollection.cs rename to src/SwiftReflector/src/SwiftXmlReflection/GenericDeclarationCollection.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs b/src/SwiftReflector/src/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs rename to src/SwiftReflector/src/SwiftXmlReflection/GenericReferenceAssociatedTypeProtocol.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/IXElementConvertible.cs b/src/SwiftReflector/src/SwiftXmlReflection/IXElementConvertible.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/IXElementConvertible.cs rename to src/SwiftReflector/src/SwiftXmlReflection/IXElementConvertible.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/Inheritance.cs b/src/SwiftReflector/src/SwiftXmlReflection/Inheritance.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/Inheritance.cs rename to src/SwiftReflector/src/SwiftXmlReflection/Inheritance.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/Member.cs b/src/SwiftReflector/src/SwiftXmlReflection/Member.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/Member.cs rename to src/SwiftReflector/src/SwiftXmlReflection/Member.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/ModuleDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ModuleDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ModuleDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/OperatorDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/OperatorDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/OperatorDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs b/src/SwiftReflector/src/SwiftXmlReflection/ParameterItem.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ParameterItem.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ParameterItem.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/PropertyDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/PropertyDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/PropertyDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/ProtocolDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ProtocolDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ProtocolDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/ShamDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/ShamDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/ShamDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/StructDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/StructDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/StructDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/SubscriptDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/SubscriptDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/SubscriptDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeAliasDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeAliasDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeAliasDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeAliasFolder.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeAliasFolder.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeAliasFolder.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeDeclaration.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeDeclaration.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeDeclaration.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeSpec.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeSpec.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeSpec.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeSpecParser.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeSpecParser.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeSpecParser.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeSpecToken.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeSpecToken.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeSpecToken.cs diff --git a/src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs b/src/SwiftReflector/src/SwiftXmlReflection/TypeSpecTokenizer.cs similarity index 100% rename from src/SwiftReflector/SwiftXmlReflection/TypeSpecTokenizer.cs rename to src/SwiftReflector/src/SwiftXmlReflection/TypeSpecTokenizer.cs diff --git a/src/SwiftReflector/TypeMapping/Entity.cs b/src/SwiftReflector/src/TypeMapping/Entity.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/Entity.cs rename to src/SwiftReflector/src/TypeMapping/Entity.cs diff --git a/src/SwiftReflector/TypeMapping/ModuleDatabase.cs b/src/SwiftReflector/src/TypeMapping/ModuleDatabase.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/ModuleDatabase.cs rename to src/SwiftReflector/src/TypeMapping/ModuleDatabase.cs diff --git a/src/SwiftReflector/TypeMapping/NetParam.cs b/src/SwiftReflector/src/TypeMapping/NetParam.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/NetParam.cs rename to src/SwiftReflector/src/TypeMapping/NetParam.cs diff --git a/src/SwiftReflector/TypeMapping/NetTypeBundle.cs b/src/SwiftReflector/src/TypeMapping/NetTypeBundle.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/NetTypeBundle.cs rename to src/SwiftReflector/src/TypeMapping/NetTypeBundle.cs diff --git a/src/SwiftReflector/TypeMapping/TypeDatabase.cs b/src/SwiftReflector/src/TypeMapping/TypeDatabase.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/TypeDatabase.cs rename to src/SwiftReflector/src/TypeMapping/TypeDatabase.cs diff --git a/src/SwiftReflector/TypeMapping/TypeMapper.cs b/src/SwiftReflector/src/TypeMapping/TypeMapper.cs similarity index 100% rename from src/SwiftReflector/TypeMapping/TypeMapper.cs rename to src/SwiftReflector/src/TypeMapping/TypeMapper.cs diff --git a/src/SwiftReflector/UnicodeMapper.cs b/src/SwiftReflector/src/UnicodeMapper.cs similarity index 100% rename from src/SwiftReflector/UnicodeMapper.cs rename to src/SwiftReflector/src/UnicodeMapper.cs diff --git a/src/SwiftReflector/tests/SwiftReflector.Tests.csproj b/src/SwiftReflector/tests/SwiftReflector.Tests.csproj new file mode 100644 index 000000000000..c5b3f2ab03e1 --- /dev/null +++ b/src/SwiftReflector/tests/SwiftReflector.Tests.csproj @@ -0,0 +1,12 @@ + + + + net8.0 + enable + enable + + false + true + + + diff --git a/src/SwiftReflector/tests/UnitTest1.cs b/src/SwiftReflector/tests/UnitTest1.cs new file mode 100644 index 000000000000..58909a7e2c56 --- /dev/null +++ b/src/SwiftReflector/tests/UnitTest1.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace SwiftReflector.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} \ No newline at end of file diff --git a/src/SwiftRuntimeLibrary/ISwiftObject.cs b/src/SwiftRuntimeLibrary/src/ISwiftObject.cs similarity index 100% rename from src/SwiftRuntimeLibrary/ISwiftObject.cs rename to src/SwiftRuntimeLibrary/src/ISwiftObject.cs diff --git a/src/SwiftRuntimeLibrary/SwiftCore.xml b/src/SwiftRuntimeLibrary/src/SwiftCore.xml similarity index 100% rename from src/SwiftRuntimeLibrary/SwiftCore.xml rename to src/SwiftRuntimeLibrary/src/SwiftCore.xml diff --git a/src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj b/src/SwiftRuntimeLibrary/src/SwiftRuntimeLibrary.csproj similarity index 100% rename from src/SwiftRuntimeLibrary/SwiftRuntimeLibrary.csproj rename to src/SwiftRuntimeLibrary/src/SwiftRuntimeLibrary.csproj diff --git a/src/SwiftRuntimeLibrary/tests/SwiftRuntimeLibrary.Tests.csproj b/src/SwiftRuntimeLibrary/tests/SwiftRuntimeLibrary.Tests.csproj new file mode 100644 index 000000000000..c5b3f2ab03e1 --- /dev/null +++ b/src/SwiftRuntimeLibrary/tests/SwiftRuntimeLibrary.Tests.csproj @@ -0,0 +1,12 @@ + + + + net8.0 + enable + enable + + false + true + + + diff --git a/src/SwiftRuntimeLibrary/tests/UnitTest1.cs b/src/SwiftRuntimeLibrary/tests/UnitTest1.cs new file mode 100644 index 000000000000..8130d82463b2 --- /dev/null +++ b/src/SwiftRuntimeLibrary/tests/UnitTest1.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace SwiftRuntimeLibrary.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} \ No newline at end of file diff --git a/src/SyntaxDynamo/CodeElementCollection.cs b/src/SyntaxDynamo/src/CodeElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/CodeElementCollection.cs rename to src/SyntaxDynamo/src/CodeElementCollection.cs diff --git a/src/SyntaxDynamo/CodeWriter.cs b/src/SyntaxDynamo/src/CodeWriter.cs similarity index 100% rename from src/SyntaxDynamo/CodeWriter.cs rename to src/SyntaxDynamo/src/CodeWriter.cs diff --git a/src/SyntaxDynamo/CommaListElementCollection.cs b/src/SyntaxDynamo/src/CommaListElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/CommaListElementCollection.cs rename to src/SyntaxDynamo/src/CommaListElementCollection.cs diff --git a/src/SyntaxDynamo/DecoratedCodeElementCollection.cs b/src/SyntaxDynamo/src/DecoratedCodeElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/DecoratedCodeElementCollection.cs rename to src/SyntaxDynamo/src/DecoratedCodeElementCollection.cs diff --git a/src/SyntaxDynamo/DelegatedCommaListElementCollection.cs b/src/SyntaxDynamo/src/DelegatedCommaListElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/DelegatedCommaListElementCollection.cs rename to src/SyntaxDynamo/src/DelegatedCommaListElementCollection.cs diff --git a/src/SyntaxDynamo/DelegatedSimpleElement.cs b/src/SyntaxDynamo/src/DelegatedSimpleElement.cs similarity index 100% rename from src/SyntaxDynamo/DelegatedSimpleElement.cs rename to src/SyntaxDynamo/src/DelegatedSimpleElement.cs diff --git a/src/SyntaxDynamo/Extensions.cs b/src/SyntaxDynamo/src/Extensions.cs similarity index 100% rename from src/SyntaxDynamo/Extensions.cs rename to src/SyntaxDynamo/src/Extensions.cs diff --git a/src/SyntaxDynamo/ICodeElement.cs b/src/SyntaxDynamo/src/ICodeElement.cs similarity index 100% rename from src/SyntaxDynamo/ICodeElement.cs rename to src/SyntaxDynamo/src/ICodeElement.cs diff --git a/src/SyntaxDynamo/ICodeElementSet.cs b/src/SyntaxDynamo/src/ICodeElementSet.cs similarity index 100% rename from src/SyntaxDynamo/ICodeElementSet.cs rename to src/SyntaxDynamo/src/ICodeElementSet.cs diff --git a/src/SyntaxDynamo/ICodeWriter.cs b/src/SyntaxDynamo/src/ICodeWriter.cs similarity index 100% rename from src/SyntaxDynamo/ICodeWriter.cs rename to src/SyntaxDynamo/src/ICodeWriter.cs diff --git a/src/SyntaxDynamo/LabeledCodeElementCollection.cs b/src/SyntaxDynamo/src/LabeledCodeElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/LabeledCodeElementCollection.cs rename to src/SyntaxDynamo/src/LabeledCodeElementCollection.cs diff --git a/src/SyntaxDynamo/LineCodeElementCollection.cs b/src/SyntaxDynamo/src/LineCodeElementCollection.cs similarity index 100% rename from src/SyntaxDynamo/LineCodeElementCollection.cs rename to src/SyntaxDynamo/src/LineCodeElementCollection.cs diff --git a/src/SyntaxDynamo/SimpleElement.cs b/src/SyntaxDynamo/src/SimpleElement.cs similarity index 100% rename from src/SyntaxDynamo/SimpleElement.cs rename to src/SyntaxDynamo/src/SimpleElement.cs diff --git a/src/SyntaxDynamo/SimpleLineElement.cs b/src/SyntaxDynamo/src/SimpleLineElement.cs similarity index 100% rename from src/SyntaxDynamo/SimpleLineElement.cs rename to src/SyntaxDynamo/src/SimpleLineElement.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSArgument.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArgument.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSArgument.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSArray1D.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSArray1D.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSArray1D.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSAssignment.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAssignment.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSAssignment.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSAttribute.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSAttribute.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSAttribute.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBaseExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBaseExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBaseExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBinaryExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinaryExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBinaryExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBinding.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSBinding.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSBinding.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSClass.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSClass.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSClass.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSCodeBlock.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSCodeBlock.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSCodeBlock.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSComment.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSComment.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSComment.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSConditionalCompilation.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConditionalCompilation.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSConditionalCompilation.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSConstant.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSConstant.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSConstant.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSDelegateTypeDecl.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSEnum.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSEnum.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSEnum.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFieldDeclaration.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFieldDeclaration.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFieldDeclaration.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFile.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFile.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFile.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFileBasic.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFileBasic.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFileBasic.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFixed.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFixed.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFixed.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSForEach.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSForEach.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSForEach.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFunctionCall.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSFunctionCall.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSFunctionCall.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSGenericConstraint.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericConstraint.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSGenericConstraint.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSGenericTypeDeclaration.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIdentifier.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIdentifier.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIdentifier.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIfElse.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIfElse.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIfElse.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIndexExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSIndexExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSIndexExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInheritance.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInheritance.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInheritance.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInitializer.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInitializer.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInitializer.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInject.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInject.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInject.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInterface.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSInterface.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSInterface.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSLambda.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLambda.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSLambda.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSLine.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSLine.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSLine.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSMethod.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSMethod.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSMethod.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSNamespace.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSNamespace.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSNamespace.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSParameter.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParameter.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSParameter.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSParenthesisExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSParenthesisExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSParenthesisExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSProperty.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSProperty.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSProperty.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSReturn.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSReturn.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSReturn.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSShortCircuit.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSShortCircuit.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSShortCircuit.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSTernary.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTernary.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSTernary.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSThrow.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSThrow.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSThrow.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSTryCatch.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSTryCatch.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSTryCatch.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSType.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSType.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSType.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSUnaryExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUnaryExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSUnaryExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSUsing.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/CSUsing.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/CSUsing.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/Enums.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/Enums.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/Enums.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSExpression.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSExpression.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSExpression.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSLineable.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSLineable.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSLineable.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSStatement.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSStatement.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSStatement.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs b/src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs rename to src/SyntaxDynamo/src/SyntaxDynamo.CSLang/ICSTopLevelDeclaration.cs diff --git a/src/SyntaxDynamo/SyntaxDynamo.csproj b/src/SyntaxDynamo/src/SyntaxDynamo.csproj similarity index 100% rename from src/SyntaxDynamo/SyntaxDynamo.csproj rename to src/SyntaxDynamo/src/SyntaxDynamo.csproj diff --git a/src/SyntaxDynamo/WriteEventArgs.cs b/src/SyntaxDynamo/src/WriteEventArgs.cs similarity index 100% rename from src/SyntaxDynamo/WriteEventArgs.cs rename to src/SyntaxDynamo/src/WriteEventArgs.cs diff --git a/src/SyntaxDynamo/tests/SyntaxDynamo.Tests.csproj b/src/SyntaxDynamo/tests/SyntaxDynamo.Tests.csproj new file mode 100644 index 000000000000..c5b3f2ab03e1 --- /dev/null +++ b/src/SyntaxDynamo/tests/SyntaxDynamo.Tests.csproj @@ -0,0 +1,12 @@ + + + + net8.0 + enable + enable + + false + true + + + diff --git a/src/SyntaxDynamo/tests/UnitTest1.cs b/src/SyntaxDynamo/tests/UnitTest1.cs new file mode 100644 index 000000000000..6a2bf3f3da9f --- /dev/null +++ b/src/SyntaxDynamo/tests/UnitTest1.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace SyntaxDynamo.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} \ No newline at end of file From aed517c2ddba33373f854eb5baca871c8da7854f Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Thu, 22 Feb 2024 09:48:21 +0100 Subject: [PATCH 33/37] Introduce PInvoke tests --- src/SwiftBindings/src/FunctionCompiler.cs | 4 +- src/SwiftBindings/tests/CMakeLists.txt | 4 +- src/SwiftBindings/tests/PInvokeTests.cs | 3211 +++++++++++++++++ src/SwiftBindings/tests/PInvokeTests.swift | 1700 +++++++++ src/SwiftBindings/tests/SmokeTests.cs | 37 - src/SwiftBindings/tests/SmokeTests.swift | 7 - src/SwiftBindings/tests/TestsHelper.cs | 27 +- .../Parser/SwiftABIParser/SwiftABIParser.cs | 23 +- src/SwiftRuntimeLibrary/src/SwiftCore.xml | 33 +- src/samples/HelloWorld/build.sh | 2 +- 10 files changed, 4963 insertions(+), 85 deletions(-) create mode 100644 src/SwiftBindings/tests/PInvokeTests.cs create mode 100644 src/SwiftBindings/tests/PInvokeTests.swift delete mode 100644 src/SwiftBindings/tests/SmokeTests.cs delete mode 100644 src/SwiftBindings/tests/SmokeTests.swift diff --git a/src/SwiftBindings/src/FunctionCompiler.cs b/src/SwiftBindings/src/FunctionCompiler.cs index 9282ed340cb2..49202bb6e3fd 100644 --- a/src/SwiftBindings/src/FunctionCompiler.cs +++ b/src/SwiftBindings/src/FunctionCompiler.cs @@ -28,8 +28,8 @@ public CSMethod CompileMethod(FunctionDeclaration func, bool isPinvoke) CSType csReturnType = returnType.IsVoid ? CSSimpleType.Void : returnType.ToCSType(packs); var csParams = new CSParameterList(); - if (func.ParameterLists.Count > 0){ - var args = typeMap.MapParameterList(func, func.ParameterLists.Last(), isPinvoke, false, null, null, packs); + if (func.ParameterLists.FirstOrDefault().Count > 0){ + var args = typeMap.MapParameterList(func, func.ParameterLists.FirstOrDefault(), isPinvoke, false, null, null, packs); foreach (var arg in args) { var csType = arg.Type.ToCSType(packs); diff --git a/src/SwiftBindings/tests/CMakeLists.txt b/src/SwiftBindings/tests/CMakeLists.txt index eb0b3634345e..67df1e18a089 100644 --- a/src/SwiftBindings/tests/CMakeLists.txt +++ b/src/SwiftBindings/tests/CMakeLists.txt @@ -1,8 +1,8 @@ cmake_minimum_required(VERSION 3.24) -project(SmokeTests) +project(PInvokeTests) -set(SOURCE SmokeTests) +set(SOURCE PInvokeTests) if (NOT SWIFT_COMPILER_TARGET) set(SWIFT_PLATFORM "macosx") diff --git a/src/SwiftBindings/tests/PInvokeTests.cs b/src/SwiftBindings/tests/PInvokeTests.cs new file mode 100644 index 000000000000..d9d99dfbf256 --- /dev/null +++ b/src/SwiftBindings/tests/PInvokeTests.cs @@ -0,0 +1,3211 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using Xunit; + +namespace SwiftBindings.Tests +{ + public class PInvokeTests + { + [Fact] + public static void TestSwiftFunc0() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc0: "); + long result = PInvokeTests.swiftFunc0(233837, -19649, 949339914140650, 515944430, 3611910812477598, 1366498001922882872, 253, 36322, 9433, 4255310654111403863); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7706330218351441791, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc1() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc1: "); + long result = PInvokeTests.swiftFunc1(86085159640584, 8266931072168309631, 1110349398, 923925690, 37808, unchecked((nint)1505729412738639024), unchecked((nint)5378706168286662479), unchecked((nuint)3649715618139795268), 7849893551470522942, 56451, 91, unchecked((nuint)8878053038747921600), 50562, 51, 1727716, -7397, 1565437348, 5586083, 51673832327441982, 1640275483742190655, 242); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-3202601456867082324, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc2() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc2: "); + long result = PInvokeTests.swiftFunc2(21, 103, 71, 1424520637, 3182953, 59237, 5358256, 185, unchecked((nuint)5971751687364786332), 3252957756581813, 60, 156, 37, 691169209662368818, 619972957, -24591, 1750310134967048045, 3556371, 7350716211230827055, 752486, 13160, 4120692058630618283, 339525547); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(911474180935535301, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc3() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc3: "); + long result = PInvokeTests.swiftFunc3(11017, unchecked((nuint)3300243067329724866), unchecked((nint)2197054130026496019), 7, unchecked((nuint)4243803136497835975)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-6350065034291914241, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc4() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc4: "); + long result = PInvokeTests.swiftFunc4(123, 109509832281030, 771052005, unchecked((nint)949115070174941197), 409146992556708, 142, 8802835909468694407, 117, 1991550650, 355009119770696130, -1465, 77, 4978285795473493480, 29393, 35783, unchecked((nuint)465708604896456642), unchecked((nint)6140690449828087415), unchecked((nuint)54183433686440276)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-9091922861563963282, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc5() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc5: "); + long result = PInvokeTests.swiftFunc5(unchecked((nint)6739098280890594874), unchecked((nuint)3195600522343554291), 6597877, unchecked((nint)4743060745349392976), 47478, 51136, 685135916, 1498506, unchecked((nint)2513390154774344247), unchecked((nint)6264911547639833584), 97, 172, -1012, 2975748462028333845); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-3357359150345247842, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc6() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc6: "); + long result = PInvokeTests.swiftFunc6(352858064, 39960, unchecked((nuint)8213487426461212263), unchecked((nuint)8748652475782254131), 4373843, -89, 7725301, 36, 137871115990745445, 114855981505908); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-581969692498632062, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc7() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc7: "); + long result = PInvokeTests.swiftFunc7(unchecked((nint)2299287859300346739), 1631989942, 1588438125, 46916, -25, unchecked((nint)2434879470176610838), 1297396924186241, 1780608786176839, unchecked((nint)3111883344385004599), 10818, 1339461357, 8225377, 313504081, 795664767, 40); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4054341816496194551, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc8() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc8: "); + long result = PInvokeTests.swiftFunc8(1204549800782266009, -77, 7140941, 5572502, 2067454162041872, 676469398821009314, unchecked((nint)1357719795588198527), -32374, unchecked((nint)3415487707327485172), 3903084861204809, 845624, 90, 1986654521, 114, 214); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-2147505143518021575, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc9() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc9: "); + long result = PInvokeTests.swiftFunc9(unchecked((nint)3705651731235919791), unchecked((nint)8105306104169745115), 6731, 1253260485, unchecked((nuint)8727468328369013450), 5633339905753787255, 651456, 5746290834850613062, 21104, 1670307274); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3533238385513656508, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc10() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc10: "); + long result = PInvokeTests.swiftFunc10(1467110824167985295, 1887615810, 2112733722, 8271177801101005406, 2568471098105086703, 17984, 230, 1774094245, 2124643938); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8515181823957334780, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc11() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc11: "); + long result = PInvokeTests.swiftFunc11(unchecked((nuint)4085636179246671464), 3081, -79, -13000, 6737190552584399571, 204, -103, 69, 1527509527, 174, 2113159904681342052, unchecked((nint)4901826652984790117), 22029, 7006945911615348711, 1812624423); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-5125817077505710853, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc12() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc12: "); + long result = PInvokeTests.swiftFunc12(6965382, 8312380862312650549, unchecked((nint)9165262159588878385), 17928, 1334453663, -18258, 50575, 1175690859854043654, -1563, 1325, -13033, 109, unchecked((nuint)46750205502198598), 22094, 8206581082498717875, 414098, 43, 1413226877351846990, 3077183154579648); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4774074602111830179, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc13() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc13: "); + long result = PInvokeTests.swiftFunc13(435831281, unchecked((nint)9152379611666687932), 2121329568, 6151812, 272083164, -25750, 8363795, 2452785801682149491, 70, 1402553126); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8686515529117439727, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc14() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc14: "); + long result = PInvokeTests.swiftFunc14(2302358859056615, 1148917190, 3948163471413493, 9149629931189885207, unchecked((nuint)8741258279203724116), 1005305, unchecked((nint)4318208587188430868), -120, 3440736986307467027); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(1430703777921650146, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc15() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc15: "); + long result = PInvokeTests.swiftFunc15(257588134824930427, unchecked((nint)8797066708053001900)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7324810059718518437, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc16() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc16: "); + long result = PInvokeTests.swiftFunc16(18083, 526, unchecked((nint)9092800655449909603), unchecked((nuint)1805357597792116718), 77133128, 4273714158070562, 3356842482838205306, 222, 9005246081447186762, 18718, 4779021523298290196, 265082826573210908, 1651590145, unchecked((nuint)2901617451727386196), 31673, unchecked((nuint)4505812232449759257), 2268590068495235382, 3672721177958656411, 4626146, 206, -70); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-2322427926688559587, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc17() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc17: "); + long result = PInvokeTests.swiftFunc17(776236297300099374, unchecked((nuint)83894503467164568), 719637193271577866, 723625097, 8592004555011333063, -3, 160, -45); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-5704419938581148490, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc18() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc18: "); + long result = PInvokeTests.swiftFunc18(245, unchecked((nint)4458327158518645661), 6050907, 76, unchecked((nint)5568159142839627860), 52, 1144555738, unchecked((nint)8239694963746799753), 148); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7333181440701096551, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc19() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc19: "); + long result = PInvokeTests.swiftFunc19(1964143, unchecked((nuint)7587937485891193274), 8151333634567615027, 17, 170165831807253, 870321007, 98, 1362436055, unchecked((nint)3145994526327645870), 1332381167, 27209, 1960414431895653, 3646108149104658576, 29716, 4480774200926903, 3993989, 831696419130641, 16961, unchecked((nint)2895643089791458731), 9040165725126613424, 4805, 2986899981433626); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7514368921355633465, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc20() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc20: "); + long result = PInvokeTests.swiftFunc20(2304932402575035, 6462973, 1769831413330094805, 38814, 62195, 52028, 643381139480, 240813148, 917778415, -11908, 43571, 735513651, -110, 1706933298, 141); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4347999520285809529, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc21() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc21: "); + long result = PInvokeTests.swiftFunc21(8204, -18311, 1428916154170345344, 7071281865190759971, 7843802, unchecked((nint)5442642178249643511), 43131, 210, 0, 61711, 104, 6457, 984084882, unchecked((nint)4275598409331185780), unchecked((nuint)8085691827548356926), 387, 1692895, 61, 6740747923378741876, 1508742654); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9056719667499044372, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc22() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc22: "); + long result = PInvokeTests.swiftFunc22(538154736774388864, 44188, 7266230885340174627, unchecked((nuint)2194770502849252955), 915, 50317); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(2450837469650376012, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc23() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc23: "); + long result = PInvokeTests.swiftFunc23(3154474308016267173, -54, 6973009299557427565, 4709618332502314628, 623782756, 41, 758947939616460266, 38, 2132563794773469419, 696661960811599136, 1159078994, 4596149, 17273, 83, 36422, 3498443323232355); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-6077835106866375633, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc24() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc24: "); + long result = PInvokeTests.swiftFunc24(50216, -31158, 965480864, 31, 1049293008, 8407966859260157806, 20505, 1331992, 4691512, 64675, 7560932795418332291); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7246961535839287248, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc25() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc25: "); + long result = PInvokeTests.swiftFunc25(unchecked((nint)9173857460962505190), 15022, -93, 62197911982761328, 767946476832147, 1436697338, 453782736594733, 8607484193451689185, 1800209635, 6244274, 2230568, 54, 1734973, 4474435427886752355, 668020350438063396, 9113309237687218066); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4681650148273269479, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc26() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc26: "); + long result = PInvokeTests.swiftFunc26(7995355894864936963, 1657769591981037, 5636685, 49073, 1465261410, 4, 118925102, 1262537, 3410729040016453081, 3116369662775677322, 2298252452836462988, unchecked((nuint)1703297916748788633), 41787, 23); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7896710633380101536, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc27() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc27: "); + long result = PInvokeTests.swiftFunc27(1288789349037378, 246, 2006429802, unchecked((nuint)1682808387624676808), 171, 1097881357975166039, -15744, 74, 561093280, unchecked((nuint)2288145815937670417), 1410177917, 3832322133938261341, 247663832, 6775031520610184090, 343414669, 2137107, unchecked((nint)1607566964681057532), 4327003494555178103, -29278, 6636805788201424308, 5472, 610898910012130); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-2413801917489038945, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc28() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc28: "); + long result = PInvokeTests.swiftFunc28(708394762); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-5115695744450024635, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc29() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc29: "); + long result = PInvokeTests.swiftFunc29(2548726, 185, 23, -27650, 28, 51928, unchecked((nuint)2820244979335896113), 1835, 4050255123891795, 9, 28133, 1603010545626232827, 26825, -3699, unchecked((nuint)9016733266665724964), unchecked((nuint)2189002664079576114), 3158963993105122993, unchecked((nuint)644656289758397492), 7484719451100568914, 41399); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7218188220935660367, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc30() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc30: "); + long result = PInvokeTests.swiftFunc30(2476657055966019, 4347333333421575149, unchecked((nint)7035626728730643182), 246, 330548879, 1030645303, 2185, unchecked((nuint)5053178496758927023), -27715, unchecked((nint)3801555871909422480), 191, unchecked((nint)3437128653478702713), 3235, 1144262746, 3278312, 303215206, 23, 7505126148864499061); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3303407505715961682, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc31() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc31: "); + long result = PInvokeTests.swiftFunc31(186, 5011206654908794290, 1339751659, -14, unchecked((nint)213472320278997211), unchecked((nuint)7645863228691077485), 179117817, 195, -105, 11576, -57, 6980306680077378405, 56); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(6926745355509484660, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc32() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc32: "); + long result = PInvokeTests.swiftFunc32(unchecked((nuint)4591110937711003471), 3095346); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8134759728697468421, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc33() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc33: "); + long result = PInvokeTests.swiftFunc33(427594908988451897, 172944849, 2318725425520920129); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8926062754575499112, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc34() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc34: "); + long result = PInvokeTests.swiftFunc34(7575837, -41, 1617235683, -68, 8522361601751102184, 1353310291, 1751998216661839, 236); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3916199453627741495, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc35() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc35: "); + long result = PInvokeTests.swiftFunc35(657240877, -11, 621151963, 3216313916345125, unchecked((nint)4783457933847136272), -12992, 151); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4225631615746848021, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc36() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc36: "); + long result = PInvokeTests.swiftFunc36(unchecked((nint)6825261648432495366), 4924311888837579788, unchecked((nint)2728441732713295124), 8539517680162989134, unchecked((nuint)7911109395014469691), 4271690110707692577); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9029057458451328084, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc37() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc37: "); + long result = PInvokeTests.swiftFunc37(-36, unchecked((nint)95080027562818316), 4100547834833879); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9091326884382848930, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc38() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc38: "); + long result = PInvokeTests.swiftFunc38(5598802284356856503, 3277053653997566283, 59, 153, 3703517767397116, 48); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(2966780901945169708, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc39() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc39: "); + long result = PInvokeTests.swiftFunc39(-86, 1025206765, unchecked((nint)8854120933376595148), -26660, 1421450910, 1171078919, unchecked((nint)7160130076335475540), 4878908, 3905851, 702664134620078, unchecked((nuint)2925732235852901624), 29717, unchecked((nint)5151891595858119552), 5037163689792046960, -4663, 7608014, 9191594607153046781, 5532); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7464446680392812994, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc40() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc40: "); + long result = PInvokeTests.swiftFunc40(9, 1203576001, 2456300054912747306, 60251, 1342361607567757, 1388115385, 3232188961689180037, 54573633, 1934356798, 5319583380828737022, unchecked((nuint)999425289681850697), 792187764); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-3563617050423332895, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc41() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc41: "); + long result = PInvokeTests.swiftFunc41(8474709311929743705, 12394, unchecked((nint)6127564349538668363), 6333136, 4, 446948525, unchecked((nint)5038104703753360766), 26552, 8206136925734873352, -12, 7199240, unchecked((nuint)8318440149659471267), unchecked((nuint)523184722071542187), 398499589, 1325785459276436, 4573239138788995136, 121, 5590899, 617132760792659437); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-2569382956498289470, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc42() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc42: "); + long result = PInvokeTests.swiftFunc42(8982298576385374275, 16564, unchecked((nint)1565617731878871304), 4419651110224616435, unchecked((nint)7891202001623571444)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-1108582741386924293, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc43() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc43: "); + long result = PInvokeTests.swiftFunc43(175); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-5808479907339934850, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc44() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc44: "); + long result = PInvokeTests.swiftFunc44(3189698876625689, -18777, 6476950464046275862, 1358084128, 7417, 17593, 610320965697918775, 241147333, 115248210, 4468818817792272374, 17930, 1481953553, -12287, -43, 5647436063971232926); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-234686925954875908, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc45() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc45: "); + long result = PInvokeTests.swiftFunc45(197, 183, 6515265205839958632, 9815, 5707972, -4010, 67, 82, 1832502602, 1685291427109048803, 23310, unchecked((nuint)4680356630874532717), -19307); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-9083497234002976264, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc46() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc46: "); + long result = PInvokeTests.swiftFunc46(579663255922949977, -114, 61, 950773313, 6516, 1526258723168738010, 6992730720599538682); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7467754277704703568, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc47() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc47: "); + long result = PInvokeTests.swiftFunc47(4289393662241141492, 6772140852363500214, 59427, -98); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7149358155385248658, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc48() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc48: "); + long result = PInvokeTests.swiftFunc48(unchecked((nuint)2785520541460599046), 19124, unchecked((nint)3936154413078833457), 2531598, -22, 7611587982378297798, 4886415070100568562, 53, 168, 47, -12, 1408044606511344677, 586995963, unchecked((nint)877805028374247435), 1735610, 1829192187, 798426250350098200); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8590814201057560160, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc49() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc49: "); + long result = PInvokeTests.swiftFunc49(13797); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(739011484971652047, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc50() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc50: "); + long result = PInvokeTests.swiftFunc50(5240299569070422159, 3980, 4966478767025838285, 126, 1448511, 3783312608878806, -32326, 1325886438, 170091605, 1038937165); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3055246540243887734, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc51() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc51: "); + long result = PInvokeTests.swiftFunc51(153365390); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7917142179400080853, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc52() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc52: "); + long result = PInvokeTests.swiftFunc52(49481, unchecked((nuint)2571534213240358460), 19650, 2104528670, 22899, unchecked((nint)8430209965909078811), -25876, 5387620829724391204, unchecked((nint)1450099608276146285), -18049, unchecked((nint)4326178111882457989), 661345047621579, 62960, 239, 3996267746533686661); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8118257769004209257, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc53() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc53: "); + long result = PInvokeTests.swiftFunc53(147266479862857914, unchecked((nint)8878677607688119219), 8593690468919623905, 985107042289460, 3243214921586572926, -18, 5766204873311264178, 2076283, 153, unchecked((nint)4491578823480651614), 31118, 154, 4113143241935276428, 2668467, 2828111477600924337, -48, 822748310022451525, unchecked((nuint)5732324054981972848), unchecked((nint)2079781176213395340), 3554919, 124, unchecked((nint)928745656441981312), -118); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9075957082830800153, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc54() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc54: "); + long result = PInvokeTests.swiftFunc54(13995, 13570, 7335161404114781494, 21761, 4879059693239079259, 191, -83, 336670981, 5585960, 8626184290788542400, 3677, 1958748094, 127, 3173715667118077320, 33889614420216385, 642796371, 1838551347, 13607283572602918, 6503940653653026899, 52, 4879061834664472526, 4455735786978402948, unchecked((nint)5167060653638148074), -59); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(715458900514912094, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc55() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc55: "); + long result = PInvokeTests.swiftFunc55(2603647622333053765, 4505865605315186666, 109, 96, 10457, 3407618254032143196, 2771970263176123930, 8387065688735342300, 587214218036297943, 47995, -13); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7812796314477300904, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc56() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc56: "); + long result = PInvokeTests.swiftFunc56(unchecked((nuint)4635596573752865036), 872443880, 2315186662326589, 7230035846427727261, 3908289, 400472551, unchecked((nint)1465473227822284563), -31971, unchecked((nuint)2826972572414861403), 3888061765805348, 779414124, 1373494226, 65241, -14, unchecked((nint)800185043394788883), 99, 70223058, -76, 226); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-3660123537755587162, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc57() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc57: "); + long result = PInvokeTests.swiftFunc57(-31909, 6905301, 25023, unchecked((nint)1103857621324234540), 2098823486, 5414734, -11, 926572209, 3200449698799467781, 3679569258896139, 8812281510378648951, unchecked((nuint)4871025154453945009), 152, 62421); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8830493546874923270, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc58() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc58: "); + long result = PInvokeTests.swiftFunc58(unchecked((nint)7967575041279499718), 3232788, 14816036, 3383016995295473, unchecked((nuint)4850027613376762027), unchecked((nint)8327795864754336795), 3340754, -3120, 2761192, 3983147687671529407, 71, 5318708, 1392678309); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(6514055640091085387, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc59() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc59: "); + long result = PInvokeTests.swiftFunc59(44844, unchecked((nuint)1748801304810040008), 30766, unchecked((nuint)4039697629876222207), 1041509849, 58, -4630, 2359663412992532838, 4965740); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(5046324847209516867, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc60() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc60: "); + long result = PInvokeTests.swiftFunc60(1832792349913741, 412903961769194327, 15449); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8176066941526010601, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc61() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc61: "); + long result = PInvokeTests.swiftFunc61(-56, 10, 254, 3947646992575930886, unchecked((nint)1512031355372423197), 376047834, unchecked((nint)1656240652039967673), 22865, 2499705526110532, 44, 1741513168, 221); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8047185703659702100, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc62() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc62: "); + long result = PInvokeTests.swiftFunc62(10, 2075487406, -9981, 168, unchecked((nint)6799443207845790064), 16835, 4246786459783416, 99, 2318900356573254122, 4147579480654007864); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(6758416630263865563, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc63() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc63: "); + long result = PInvokeTests.swiftFunc63(4817099); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-24765264996518815, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc64() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc64: "); + long result = PInvokeTests.swiftFunc64(-31400, 33, 1144995603961263); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4496411701938139124, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc65() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc65: "); + long result = PInvokeTests.swiftFunc65(343468144996369, 1595701486, 691136339, 377795381, unchecked((nuint)8621456802956657380), 387673204, -79, 684151295, 2702822453080893204, 658117164, 1483498070, 19901, 82, 298593782, 498504311); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7620356050748244213, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc66() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc66: "); + long result = PInvokeTests.swiftFunc66(unchecked((nuint)6742646500239271530), 1283101175, unchecked((nuint)971826232915481756), 6531); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-6837183037573462724, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc67() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc67: "); + long result = PInvokeTests.swiftFunc67(2788572937592617, 59180, 200708656, 9131, 1755490561, 258348099, 254, 779012863187640, 1906037567212321, 544676897, 7911267266539149763, 336384219, 575060377, -11136, 1779482464); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3965211134150981679, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc68() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc68: "); + long result = PInvokeTests.swiftFunc68(99561312221799, 1453132808, 1612303761, unchecked((nint)6043673650667392022), unchecked((nuint)560907030475989979)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8645187640386338150, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc69() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc69: "); + long result = PInvokeTests.swiftFunc69(unchecked((nuint)5309972206871421224), 27234, 5023167, 45761, 6425609162827184107); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-2766546132850174765, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc70() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc70: "); + long result = PInvokeTests.swiftFunc70(265213086, 2024995329946372, 99, unchecked((nuint)6130388454564398915), 13675, unchecked((nint)7672787511778724532), 83667695082967, unchecked((nint)8879102379708862673)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-6730251310408327023, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc71() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc71: "); + long result = PInvokeTests.swiftFunc71(unchecked((nuint)7826726408346018358), 3933082761574796313, 1549799158, 1737163241, 4770998022264795192, 3012307, -22318, 174, 3175654294509651, 7095989, unchecked((nint)2671492835533826745), unchecked((nint)4435595869554769711), 3593089457929161, -70, 12103, 1171000858, 142); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-4761426221194945322, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc72() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc72: "); + long result = PInvokeTests.swiftFunc72(6784686274248571763, 104, unchecked((nint)909285983876097936), 6714220880263670485, 7373872626119376832, -23109, -39, 85, 3722567341893906, 5856612, 11316); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8722701469163367659, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc73() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc73: "); + long result = PInvokeTests.swiftFunc73(-31440, 1071353143); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9091436234605144348, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc74() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc74: "); + long result = PInvokeTests.swiftFunc74(8367961236466665848, 3084215, 5133, 881467901, 1349905959, 1058177434, 266815227, 740895977807658292, unchecked((nuint)2510276735562063056), 2731666997695150, 7789234325148051159, 1528039387, 16705, 146766703, 4585584465621462072, 1977); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-4564195959279673945, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc75() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc75: "); + long result = PInvokeTests.swiftFunc75(1027938307, 56236, 88, 98, 27306, 61342909, 2269015579127872, 1031703529, 8402886576148882920, -68, 3807162); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-3369734987080453648, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc76() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc76: "); + long result = PInvokeTests.swiftFunc76(301994950391123, 4344776, 104, 2137807671, 171179011, 3134127914468069876, 6656, 42885, unchecked((nint)7737600182044247158), -120, 1033649432, 129875179286116790); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8920640767423704440, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc77() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc77: "); + long result = PInvokeTests.swiftFunc77(3316166077206800, 3332468478057987249, 1373131825374120, 4918231, 2744065375713515, 3594016966337642259, -60, 20, -106, 2272, 856759296, unchecked((nuint)411883701353980843), unchecked((nint)932327579092391229), 515885, 42, 29247, 2550, 995856082225857); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(6960169366615671879, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc78() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc78: "); + long result = PInvokeTests.swiftFunc78(8691571239579681212, -6331, unchecked((nuint)747809074035744802), unchecked((nint)4660686733629536050), -25591, 6155, 378094, 52, 7080577359538810005, 26362, 1774417260, 144, 5160013); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(4812301631028745377, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc79() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc79: "); + long result = PInvokeTests.swiftFunc79(3768859, 701589732, 49, unchecked((nint)2400132102872573811), 7919338068121439001, 12, 1161810112, 1492596679, 3256298, 150297458, 44, 3359191536348582004, 2501, -3042, 31848, unchecked((nuint)8625178339509965677), 1789284789053154, 6259002624415501110, -23813); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(693619259694162127, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc80() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc80: "); + long result = PInvokeTests.swiftFunc80(2729190792419187, 1585764063, 5117419591579829234, 614117500, 1693556822); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-4631030647197364647, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc81() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc81: "); + long result = PInvokeTests.swiftFunc81(unchecked((nint)8095725324232772887), -11, 1220850298, 2854360776836504, 8343542849265358484, 1016078821622888399, 1083388, 791962662); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8908581242517107527, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc82() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc82: "); + long result = PInvokeTests.swiftFunc82(unchecked((nuint)1174997556571304622), 2990610909261926, 18753, 6253511180087050924, 3058091764587841331, 2842978159455375886); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-1543576629977717704, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc83() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc83: "); + long result = PInvokeTests.swiftFunc83(168003999, 689879558669204554, 3381664931253746938, 82, 2210365248447152, 14007, 50724, 211726992, 4908, 9089, -1517, 793801401, 3942422035006427459, 5203020310498374994, 2464433756321920, 8067802492059811569, 649047218); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-4161389211393419243, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc84() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc84: "); + long result = PInvokeTests.swiftFunc84(5500564689809982598, 8160193010477217516, unchecked((nint)2621562636476726595), 1925518901041551, 833959); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8984640578940854556, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc85() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc85: "); + long result = PInvokeTests.swiftFunc85(1828548277567665, 79, unchecked((nuint)2816133458526686380), 246, unchecked((nuint)8123936957398843594), 1915634045, 4277399425149259, 4236491, 526249560, -1564, 2077376027144570, 96496756, 3426459, unchecked((nuint)4946835975333850900), -16125, 5180091340514231581, 6830, 8017, 16950, 83); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-5603269280984392717, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc86() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc86: "); + long result = PInvokeTests.swiftFunc86(unchecked((nuint)2690514211977331186), 48174, 5251669033533125188, -41, -118, -26036, 46895, 1006135665982533, -25915, 43319, 4016647159010115823, 161); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-756030944410084256, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc87() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc87: "); + long result = PInvokeTests.swiftFunc87(41821, 2106599750261545766, 493830841784699955, unchecked((nint)7791163656720105501), 25, -15830, 286454392, 8274918093536357376, -18788, 6681672249680875943, 49954076158807243, 78, 3875942, -110, 2697976, 2443700317924383, 4382626); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3151224756940080953, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc88() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc88: "); + long result = PInvokeTests.swiftFunc88(12483, 401268929, -24340, 3584682894830208318, 4149, -28723, -18310, 2621165654927965, unchecked((nuint)4216156540440558538), 2006613843, 6015933, unchecked((nuint)4129107791356788363), 34682, 185, 4770291906992587002, -97, 91, 196); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3274371447309987255, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc89() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc89: "); + long result = PInvokeTests.swiftFunc89(154, unchecked((nint)5210339515636897856), unchecked((nint)3761599239105734389), 18, unchecked((nint)72966313290508081), 4265746, unchecked((nuint)8929551288352689384), -24066, 35491, 2551, unchecked((nint)45491645438357652), 715787386644356803, 4473157306905713, 6702547903250883900, 137061596142255, 4385401769623650480, 3378729933484470887, 1873740829, 8574214966744389441, unchecked((nuint)6446163511298821165), unchecked((nuint)6980694483795543674), 1241824808, 23615, 122); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-737269134554333880, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc90() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc90: "); + long result = PInvokeTests.swiftFunc90(79, 14, 1297542167439891848, 7930448, 975812823, 259332537, 21563, 28989); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(3441802633846719073, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc91() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc91: "); + long result = PInvokeTests.swiftFunc91(6278); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(711186144202003795, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc92() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc92: "); + long result = PInvokeTests.swiftFunc92(18225, 35, 24134, 4453695771230697, 3872995088603792387, unchecked((nint)6499933966838367751), 1330188682, 444420882, unchecked((nint)3796465283221572512), 52249, 7652735, 46441, 1927427838, 1860451970, unchecked((nint)4367540142032169587), 4492446); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(9206890599465525240, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc93() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc93: "); + long result = PInvokeTests.swiftFunc93(5748645559017654978, 5012895573340412455, 6009269000723558276, 2036630461492010444, 2436544965066504769, -125, 112, 52799, -8246, 1830045846, 1191186, 16965, 394617474747610321, 2155653386650409489, 4259466864793291, -118, -32470, -47); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7367909694938381646, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc94() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc94: "); + long result = PInvokeTests.swiftFunc94(unchecked((nuint)8677945289555827317), 6313732, 1990822772, unchecked((nuint)7652693732374651003), unchecked((nint)514619182324762120), 48, unchecked((nuint)4099443960025139442), 1897073213, 27911, 227, unchecked((nuint)3629774823693910128), unchecked((nuint)7475134394365608458), 1341041583, 8490306759261258130); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7957085466204676840, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc95() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc95: "); + long result = PInvokeTests.swiftFunc95(767020, -67, 1994628757624347102, 1066179, 675787169564137362, unchecked((nint)9035231335376355925), 647886678, -12302, unchecked((nuint)6982264019182060207), 55835, 7279581463482143007, unchecked((nuint)541979943210980226), 38516, unchecked((nuint)2405396521289532217), 577291409326865, 5810393543186852048, 5570902738989457385, 5, 6674072748987199349, 6807910446229279331, 70704, 749368364527200140); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-8941275780625427292, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc96() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc96: "); + long result = PInvokeTests.swiftFunc96(492870375181451098, 17857, 2042744158, 2550762577962530718, 2130047, unchecked((nint)7683558322808060031), -76, 85, -42, 8057727507941436393, 182, 44022, 8416140399167561318, 1582924161, 8051228828487128057, 968670026, 1); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(2083246537822351760, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc97() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc97: "); + long result = PInvokeTests.swiftFunc97(16235, 12, 29, -112, 8233611281498306459, 19, 23310, 115438575, unchecked((nuint)4258580046730992269)); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(8647824177212049859, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc98() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc98: "); + long result = PInvokeTests.swiftFunc98(4045, 86, 101013943533129, unchecked((nint)7999096616438753438), unchecked((nuint)7026548990347163237), 165, 1089253429, 164, unchecked((nuint)8255391170515879868), 13496, 5513927, 46, 3217265538715926, 717333105, 50429, -9149); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(7040925530630314472, result); + Console.WriteLine("OK"); + } + + [Fact] + public static void TestSwiftFunc99() + { + BindingsTool.GenerateBindings("PInvokeTests.abi.json", ""); + var sourceCode = """ + // Copyright (c) Microsoft Corporation. + // Licensed under the MIT License. + + using System; + using PInvokeTestsBindings; + + namespace Test { + public class MainClass { + public static int Main(string[] args) + { + return 0; + } + public static long getResult() + { + Console.Write("Running SwiftFunc99: "); + long result = PInvokeTests.swiftFunc99(155, unchecked((nuint)1880700265511668237), 1595962890494032981); + return result; + } + } + } + """; + + long result = (long)TestsHelper.CompileAndExecute("PInvokeTestsBindings.cs", sourceCode, "Test.MainClass", "getResult"); + Assert.Equal(-7883825139759684683, result); + Console.WriteLine("OK"); + } + } +} diff --git a/src/SwiftBindings/tests/PInvokeTests.swift b/src/SwiftBindings/tests/PInvokeTests.swift new file mode 100644 index 000000000000..5fb6851306ad --- /dev/null +++ b/src/SwiftBindings/tests/PInvokeTests.swift @@ -0,0 +1,1700 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import Foundation + +struct HasherFNV1a { + + private var hash: UInt = 14_695_981_039_346_656_037 + private let prime: UInt = 1_099_511_628_211 + + mutating func combine(_ val: T) { + for byte in withUnsafeBytes(of: val, Array.init) { + hash ^= UInt(byte) + hash = hash &* prime + } + } + + func finalize() -> Int { + Int(truncatingIfNeeded: hash) + } +} + +public func swiftFunc0(a0: Float, a1: Int16, a2: Double, a3: Int32, a4: Double, a5: UInt64, a6: UInt8, a7: UInt16, a8: Int16, a9: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc1(a0: Double, a1: Int64, a2: UInt32, a3: UInt32, a4: UInt16, a5: Int, a6: Int, a7: UInt, a8: UInt64, a9: UInt16, a10: UInt8, a11: UInt, a12: UInt16, a13: Int8, a14: Float, a15: Int16, a16: Int32, a17: Float, a18: UInt64, a19: Int64, a20: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + return hasher.finalize() +} + +public func swiftFunc2(a0: UInt8, a1: Int8, a2: Int8, a3: Int32, a4: UInt32, a5: UInt16, a6: Float, a7: UInt8, a8: UInt, a9: Double, a10: UInt8, a11: UInt8, a12: Int8, a13: UInt64, a14: UInt32, a15: Int16, a16: UInt64, a17: Float, a18: Int64, a19: Float, a20: Int16, a21: UInt64, a22: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + hasher.combine(a22); + return hasher.finalize() +} + +public func swiftFunc3(a0: Int16, a1: UInt, a2: Int, a3: UInt8, a4: UInt) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc4(a0: UInt8, a1: Double, a2: Int32, a3: Int, a4: Double, a5: UInt8, a6: Int64, a7: Int8, a8: Int32, a9: Int64, a10: Int16, a11: Int8, a12: Int64, a13: UInt16, a14: UInt16, a15: UInt, a16: Int, a17: UInt) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc5(a0: Int, a1: UInt, a2: Float, a3: Int, a4: UInt16, a5: UInt16, a6: UInt32, a7: Float, a8: Int, a9: Int, a10: UInt8, a11: UInt8, a12: Int16, a13: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + return hasher.finalize() +} + +public func swiftFunc6(a0: Int32, a1: UInt16, a2: UInt, a3: UInt, a4: Float, a5: Int8, a6: Float, a7: UInt8, a8: Int64, a9: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc7(a0: Int, a1: Int32, a2: UInt32, a3: UInt16, a4: Int8, a5: Int, a6: Double, a7: Double, a8: Int, a9: UInt16, a10: UInt32, a11: Float, a12: UInt32, a13: Int32, a14: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc8(a0: Int64, a1: Int8, a2: Float, a3: Float, a4: Double, a5: UInt64, a6: Int, a7: Int16, a8: Int, a9: Double, a10: Float, a11: Int8, a12: Int32, a13: Int8, a14: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc9(a0: Int, a1: Int, a2: UInt16, a3: Int32, a4: UInt, a5: Int64, a6: Float, a7: Int64, a8: UInt16, a9: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc10(a0: UInt64, a1: UInt32, a2: UInt32, a3: Int64, a4: UInt64, a5: UInt16, a6: UInt8, a7: Int32, a8: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + return hasher.finalize() +} + +public func swiftFunc11(a0: UInt, a1: UInt16, a2: Int8, a3: Int16, a4: Int64, a5: UInt8, a6: Int8, a7: Int8, a8: UInt32, a9: UInt8, a10: UInt64, a11: Int, a12: Int16, a13: UInt64, a14: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc12(a0: Float, a1: Int64, a2: Int, a3: Int16, a4: Int32, a5: Int16, a6: UInt16, a7: Int64, a8: Int16, a9: UInt16, a10: Int16, a11: UInt8, a12: UInt, a13: UInt16, a14: UInt64, a15: Float, a16: Int8, a17: UInt64, a18: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + return hasher.finalize() +} + +public func swiftFunc13(a0: Int32, a1: Int, a2: UInt32, a3: Float, a4: UInt32, a5: Int16, a6: Float, a7: UInt64, a8: UInt8, a9: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc14(a0: Double, a1: UInt32, a2: Double, a3: UInt64, a4: UInt, a5: Int32, a6: Int, a7: Int8, a8: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + return hasher.finalize() +} + +public func swiftFunc15(a0: UInt64, a1: Int) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + return hasher.finalize() +} + +public func swiftFunc16(a0: Int16, a1: UInt16, a2: Int, a3: UInt, a4: UInt32, a5: Double, a6: UInt64, a7: UInt8, a8: UInt64, a9: Int16, a10: Int64, a11: UInt64, a12: UInt32, a13: UInt, a14: UInt16, a15: UInt, a16: Int64, a17: UInt64, a18: Float, a19: UInt8, a20: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + return hasher.finalize() +} + +public func swiftFunc17(a0: UInt64, a1: UInt, a2: UInt64, a3: UInt32, a4: Int64, a5: Int8, a6: UInt8, a7: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + return hasher.finalize() +} + +public func swiftFunc18(a0: UInt8, a1: Int, a2: Float, a3: UInt8, a4: Int, a5: Int8, a6: UInt32, a7: Int, a8: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + return hasher.finalize() +} + +public func swiftFunc19(a0: Float, a1: UInt, a2: Int64, a3: UInt8, a4: Double, a5: Int32, a6: Int8, a7: Int32, a8: Int, a9: Int32, a10: Int16, a11: Double, a12: Int64, a13: UInt16, a14: Double, a15: Float, a16: Double, a17: Int16, a18: Int, a19: Int64, a20: UInt16, a21: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + return hasher.finalize() +} + +public func swiftFunc20(a0: Double, a1: Float, a2: UInt64, a3: Float, a4: UInt16, a5: UInt16, a6: Double, a7: UInt32, a8: UInt32, a9: Int16, a10: UInt16, a11: Int32, a12: Int8, a13: Int32, a14: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc21(a0: Int16, a1: Int16, a2: UInt64, a3: Int64, a4: Float, a5: Int, a6: UInt16, a7: UInt8, a8: Int8, a9: UInt16, a10: Int8, a11: Int16, a12: Int32, a13: Int, a14: UInt, a15: Int16, a16: Float, a17: UInt8, a18: Int64, a19: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + return hasher.finalize() +} + +public func swiftFunc22(a0: Int64, a1: UInt16, a2: UInt64, a3: UInt, a4: UInt16, a5: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + return hasher.finalize() +} + +public func swiftFunc23(a0: UInt64, a1: Int8, a2: UInt64, a3: Int64, a4: Int32, a5: UInt8, a6: UInt64, a7: Int8, a8: UInt64, a9: Int64, a10: UInt32, a11: Float, a12: Int16, a13: Int8, a14: UInt16, a15: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + return hasher.finalize() +} + +public func swiftFunc24(a0: UInt16, a1: Int16, a2: UInt32, a3: Int8, a4: Int32, a5: Int64, a6: UInt16, a7: Float, a8: Float, a9: UInt16, a10: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + return hasher.finalize() +} + +public func swiftFunc25(a0: Int, a1: Int16, a2: Int8, a3: Int64, a4: Double, a5: UInt32, a6: Double, a7: UInt64, a8: UInt32, a9: Float, a10: Float, a11: Int8, a12: Float, a13: Int64, a14: Int64, a15: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + return hasher.finalize() +} + +public func swiftFunc26(a0: Int64, a1: Double, a2: Float, a3: UInt16, a4: Int32, a5: UInt8, a6: Int32, a7: Float, a8: Int64, a9: Int64, a10: UInt64, a11: UInt, a12: UInt16, a13: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + return hasher.finalize() +} + +public func swiftFunc27(a0: Double, a1: UInt8, a2: UInt32, a3: UInt, a4: UInt8, a5: Int64, a6: Int16, a7: UInt8, a8: UInt32, a9: UInt, a10: UInt32, a11: UInt64, a12: Int32, a13: Int64, a14: Int32, a15: Float, a16: Int, a17: UInt64, a18: Int16, a19: Int64, a20: UInt16, a21: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + return hasher.finalize() +} + +public func swiftFunc28(a0: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc29(a0: Float, a1: UInt8, a2: UInt8, a3: Int16, a4: Int8, a5: UInt16, a6: UInt, a7: Int16, a8: Double, a9: Int8, a10: Int16, a11: UInt64, a12: Int16, a13: Int16, a14: UInt, a15: UInt, a16: Int64, a17: UInt, a18: Int64, a19: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + return hasher.finalize() +} + +public func swiftFunc30(a0: Double, a1: Int64, a2: Int, a3: UInt8, a4: UInt32, a5: Int32, a6: Int16, a7: UInt, a8: Int16, a9: Int, a10: UInt8, a11: Int, a12: Int16, a13: UInt32, a14: Float, a15: UInt32, a16: Int8, a17: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc31(a0: UInt8, a1: Int64, a2: Int32, a3: Int8, a4: Int, a5: UInt, a6: UInt32, a7: UInt8, a8: Int8, a9: Int16, a10: Int8, a11: UInt64, a12: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + return hasher.finalize() +} + +public func swiftFunc32(a0: UInt, a1: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + return hasher.finalize() +} + +public func swiftFunc33(a0: Int64, a1: UInt32, a2: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + return hasher.finalize() +} + +public func swiftFunc34(a0: Float, a1: Int8, a2: UInt32, a3: Int8, a4: UInt64, a5: UInt32, a6: Double, a7: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + return hasher.finalize() +} + +public func swiftFunc35(a0: Int32, a1: Int8, a2: UInt32, a3: Double, a4: Int, a5: Int16, a6: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + return hasher.finalize() +} + +public func swiftFunc36(a0: Int, a1: Int64, a2: Int, a3: UInt64, a4: UInt, a5: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + return hasher.finalize() +} + +public func swiftFunc37(a0: Int8, a1: Int, a2: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + return hasher.finalize() +} + +public func swiftFunc38(a0: UInt64, a1: UInt64, a2: Int8, a3: UInt8, a4: Double, a5: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + return hasher.finalize() +} + +public func swiftFunc39(a0: Int8, a1: UInt32, a2: Int, a3: Int16, a4: Int32, a5: UInt32, a6: Int, a7: Float, a8: Float, a9: Double, a10: UInt, a11: UInt16, a12: Int, a13: UInt64, a14: Int16, a15: Float, a16: Int64, a17: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc40(a0: UInt8, a1: UInt32, a2: Int64, a3: UInt16, a4: Double, a5: UInt32, a6: UInt64, a7: UInt32, a8: UInt32, a9: Int64, a10: UInt, a11: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + return hasher.finalize() +} + +public func swiftFunc41(a0: UInt64, a1: Int16, a2: Int, a3: Float, a4: Int8, a5: UInt32, a6: Int, a7: Int16, a8: UInt64, a9: Int8, a10: Float, a11: UInt, a12: UInt, a13: Int32, a14: Double, a15: Int64, a16: UInt8, a17: Float, a18: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + return hasher.finalize() +} + +public func swiftFunc42(a0: Int64, a1: UInt16, a2: Int, a3: UInt64, a4: Int) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc43(a0: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc44(a0: Double, a1: Int16, a2: Int64, a3: UInt32, a4: Int16, a5: Int16, a6: UInt64, a7: UInt32, a8: UInt32, a9: Int64, a10: UInt16, a11: UInt32, a12: Int16, a13: Int8, a14: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc45(a0: UInt8, a1: UInt8, a2: UInt64, a3: Int16, a4: Float, a5: Int16, a6: Int8, a7: UInt8, a8: Int32, a9: Int64, a10: Int16, a11: UInt, a12: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + return hasher.finalize() +} + +public func swiftFunc46(a0: UInt64, a1: Int8, a2: Int8, a3: Int32, a4: Int16, a5: Int64, a6: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + return hasher.finalize() +} + +public func swiftFunc47(a0: UInt64, a1: UInt64, a2: UInt16, a3: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + return hasher.finalize() +} + +public func swiftFunc48(a0: UInt, a1: Int16, a2: Int, a3: Float, a4: Int8, a5: UInt64, a6: Int64, a7: Int8, a8: UInt8, a9: Int8, a10: Int8, a11: UInt64, a12: UInt32, a13: Int, a14: Float, a15: Int32, a16: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + return hasher.finalize() +} + +public func swiftFunc49(a0: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc50(a0: Int64, a1: UInt16, a2: Int64, a3: UInt8, a4: Float, a5: Double, a6: Int16, a7: UInt32, a8: Int32, a9: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc51(a0: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc52(a0: UInt16, a1: UInt, a2: Int16, a3: Int32, a4: UInt16, a5: Int, a6: Int16, a7: UInt64, a8: Int, a9: Int16, a10: Int, a11: Double, a12: UInt16, a13: UInt8, a14: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc53(a0: UInt64, a1: Int, a2: UInt64, a3: Double, a4: UInt64, a5: Int8, a6: Int64, a7: Float, a8: UInt8, a9: Int, a10: Int16, a11: UInt8, a12: UInt64, a13: Float, a14: UInt64, a15: Int8, a16: Int64, a17: UInt, a18: Int, a19: Float, a20: UInt8, a21: Int, a22: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + hasher.combine(a22); + return hasher.finalize() +} + +public func swiftFunc54(a0: Int16, a1: UInt16, a2: Int64, a3: Int16, a4: Int64, a5: UInt8, a6: Int8, a7: Int32, a8: Float, a9: UInt64, a10: UInt16, a11: UInt32, a12: Int8, a13: UInt64, a14: UInt64, a15: Int32, a16: UInt32, a17: Int64, a18: UInt64, a19: UInt8, a20: UInt64, a21: UInt64, a22: Int, a23: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + hasher.combine(a22); + hasher.combine(a23); + return hasher.finalize() +} + +public func swiftFunc55(a0: UInt64, a1: Int64, a2: UInt8, a3: UInt8, a4: UInt16, a5: Int64, a6: UInt64, a7: UInt64, a8: UInt64, a9: UInt16, a10: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + return hasher.finalize() +} + +public func swiftFunc56(a0: UInt, a1: Int32, a2: Double, a3: UInt64, a4: Float, a5: UInt32, a6: Int, a7: Int16, a8: UInt, a9: Double, a10: UInt32, a11: Int32, a12: UInt16, a13: Int8, a14: Int, a15: Int8, a16: UInt32, a17: Int8, a18: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + return hasher.finalize() +} + +public func swiftFunc57(a0: Int16, a1: Float, a2: UInt16, a3: Int, a4: UInt32, a5: Float, a6: Int8, a7: Int32, a8: UInt64, a9: Double, a10: Int64, a11: UInt, a12: UInt8, a13: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + return hasher.finalize() +} + +public func swiftFunc58(a0: Int, a1: Float, a2: UInt32, a3: Double, a4: UInt, a5: Int, a6: Float, a7: Int16, a8: Float, a9: UInt64, a10: Int8, a11: Float, a12: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + return hasher.finalize() +} + +public func swiftFunc59(a0: UInt16, a1: UInt, a2: UInt16, a3: UInt, a4: UInt32, a5: UInt8, a6: Int16, a7: UInt64, a8: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + return hasher.finalize() +} + +public func swiftFunc60(a0: Double, a1: Int64, a2: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + return hasher.finalize() +} + +public func swiftFunc61(a0: Int8, a1: UInt8, a2: UInt8, a3: UInt64, a4: Int, a5: UInt32, a6: Int, a7: Int16, a8: Double, a9: Int8, a10: Int32, a11: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + return hasher.finalize() +} + +public func swiftFunc62(a0: UInt8, a1: UInt32, a2: Int16, a3: UInt8, a4: Int, a5: Float, a6: Double, a7: Int8, a8: UInt64, a9: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + return hasher.finalize() +} + +public func swiftFunc63(a0: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc64(a0: Int16, a1: Int8, a2: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + return hasher.finalize() +} + +public func swiftFunc65(a0: Double, a1: UInt32, a2: Int32, a3: Int32, a4: UInt, a5: Int32, a6: Int8, a7: Int32, a8: UInt64, a9: UInt32, a10: Int32, a11: Int16, a12: Int8, a13: Int32, a14: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc66(a0: UInt, a1: UInt32, a2: UInt, a3: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + return hasher.finalize() +} + +public func swiftFunc67(a0: Double, a1: UInt16, a2: UInt32, a3: Int16, a4: Int32, a5: UInt32, a6: UInt8, a7: Double, a8: Double, a9: Int32, a10: UInt64, a11: Int32, a12: Int32, a13: Int16, a14: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + return hasher.finalize() +} + +public func swiftFunc68(a0: Double, a1: Int32, a2: Int32, a3: Int, a4: UInt) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc69(a0: UInt, a1: UInt16, a2: Float, a3: UInt16, a4: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc70(a0: UInt32, a1: Double, a2: UInt8, a3: UInt, a4: Int16, a5: Int, a6: Double, a7: Int) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + return hasher.finalize() +} + +public func swiftFunc71(a0: UInt, a1: UInt64, a2: UInt32, a3: UInt32, a4: Int64, a5: Float, a6: Int16, a7: UInt8, a8: Double, a9: Float, a10: Int, a11: Int, a12: Double, a13: Int8, a14: Int16, a15: UInt32, a16: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + return hasher.finalize() +} + +public func swiftFunc72(a0: UInt64, a1: UInt8, a2: Int, a3: Int64, a4: UInt64, a5: Int16, a6: Int8, a7: Int8, a8: Double, a9: Float, a10: UInt16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + return hasher.finalize() +} + +public func swiftFunc73(a0: Int16, a1: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + return hasher.finalize() +} + +public func swiftFunc74(a0: Int64, a1: Float, a2: UInt16, a3: UInt32, a4: Int32, a5: UInt32, a6: Int32, a7: UInt64, a8: UInt, a9: Double, a10: UInt64, a11: Int32, a12: Int16, a13: UInt32, a14: UInt64, a15: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + return hasher.finalize() +} + +public func swiftFunc75(a0: UInt32, a1: UInt16, a2: Int8, a3: UInt8, a4: UInt16, a5: UInt32, a6: Double, a7: Int32, a8: Int64, a9: Int8, a10: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + return hasher.finalize() +} + +public func swiftFunc76(a0: Double, a1: Float, a2: UInt8, a3: UInt32, a4: Int32, a5: Int64, a6: Int16, a7: UInt16, a8: Int, a9: Int8, a10: UInt32, a11: Int64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + return hasher.finalize() +} + +public func swiftFunc77(a0: Double, a1: Int64, a2: Double, a3: Float, a4: Double, a5: Int64, a6: Int8, a7: UInt8, a8: Int8, a9: Int16, a10: UInt32, a11: UInt, a12: Int, a13: Float, a14: Int8, a15: UInt16, a16: Int16, a17: Double) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc78(a0: Int64, a1: Int16, a2: UInt, a3: Int, a4: Int16, a5: UInt16, a6: Float, a7: Int8, a8: Int64, a9: UInt16, a10: Int32, a11: UInt8, a12: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + return hasher.finalize() +} + +public func swiftFunc79(a0: Float, a1: UInt32, a2: Int8, a3: Int, a4: Int64, a5: UInt8, a6: UInt32, a7: UInt32, a8: Float, a9: UInt32, a10: UInt8, a11: UInt64, a12: UInt16, a13: Int16, a14: UInt16, a15: UInt, a16: Double, a17: UInt64, a18: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + return hasher.finalize() +} + +public func swiftFunc80(a0: Double, a1: Int32, a2: UInt64, a3: Int32, a4: UInt32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc81(a0: Int, a1: Int8, a2: UInt32, a3: Double, a4: UInt64, a5: UInt64, a6: Float, a7: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + return hasher.finalize() +} + +public func swiftFunc82(a0: UInt, a1: Double, a2: UInt16, a3: UInt64, a4: Int64, a5: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + return hasher.finalize() +} + +public func swiftFunc83(a0: Int32, a1: Int64, a2: Int64, a3: UInt8, a4: Double, a5: UInt16, a6: UInt16, a7: Int32, a8: UInt16, a9: UInt16, a10: Int16, a11: UInt32, a12: UInt64, a13: Int64, a14: Double, a15: UInt64, a16: Int32) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + return hasher.finalize() +} + +public func swiftFunc84(a0: Int64, a1: Int64, a2: Int, a3: Double, a4: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + return hasher.finalize() +} + +public func swiftFunc85(a0: Double, a1: Int8, a2: UInt, a3: UInt8, a4: UInt, a5: Int32, a6: Double, a7: Float, a8: Int32, a9: Int16, a10: Double, a11: Int32, a12: Float, a13: UInt, a14: Int16, a15: Int64, a16: UInt16, a17: Int16, a18: Int16, a19: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + return hasher.finalize() +} + +public func swiftFunc86(a0: UInt, a1: UInt16, a2: UInt64, a3: Int8, a4: Int8, a5: Int16, a6: UInt16, a7: Double, a8: Int16, a9: UInt16, a10: Int64, a11: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + return hasher.finalize() +} + +public func swiftFunc87(a0: UInt16, a1: UInt64, a2: Int64, a3: Int, a4: Int8, a5: Int16, a6: UInt32, a7: Int64, a8: Int16, a9: Int64, a10: Int64, a11: UInt8, a12: Float, a13: Int8, a14: Float, a15: Double, a16: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + return hasher.finalize() +} + +public func swiftFunc88(a0: UInt16, a1: UInt32, a2: Int16, a3: UInt64, a4: UInt16, a5: Int16, a6: Int16, a7: Double, a8: UInt, a9: Int32, a10: Float, a11: UInt, a12: UInt16, a13: UInt8, a14: UInt64, a15: Int8, a16: UInt8, a17: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc89(a0: UInt8, a1: Int, a2: Int, a3: UInt8, a4: Int, a5: Float, a6: UInt, a7: Int16, a8: UInt16, a9: Int16, a10: Int, a11: UInt64, a12: Double, a13: Int64, a14: Double, a15: UInt64, a16: UInt64, a17: Int32, a18: UInt64, a19: UInt, a20: UInt, a21: UInt32, a22: Int16, a23: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + hasher.combine(a22); + hasher.combine(a23); + return hasher.finalize() +} + +public func swiftFunc90(a0: UInt8, a1: Int8, a2: UInt64, a3: Float, a4: UInt32, a5: UInt32, a6: UInt16, a7: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + return hasher.finalize() +} + +public func swiftFunc91(a0: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + return hasher.finalize() +} + +public func swiftFunc92(a0: UInt16, a1: Int8, a2: Int16, a3: Double, a4: Int64, a5: Int, a6: UInt32, a7: UInt32, a8: Int, a9: UInt16, a10: Float, a11: UInt16, a12: UInt32, a13: UInt32, a14: Int, a15: Float) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + return hasher.finalize() +} + +public func swiftFunc93(a0: Int64, a1: UInt64, a2: UInt64, a3: UInt64, a4: UInt64, a5: Int8, a6: UInt8, a7: UInt16, a8: Int16, a9: Int32, a10: Float, a11: UInt16, a12: Int64, a13: Int64, a14: Double, a15: Int8, a16: Int16, a17: Int8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + return hasher.finalize() +} + +public func swiftFunc94(a0: UInt, a1: Float, a2: UInt32, a3: UInt, a4: Int, a5: UInt8, a6: UInt, a7: UInt32, a8: UInt16, a9: UInt8, a10: UInt, a11: UInt, a12: UInt32, a13: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + return hasher.finalize() +} + +public func swiftFunc95(a0: Float, a1: Int8, a2: Int64, a3: Float, a4: UInt64, a5: Int, a6: UInt32, a7: Int16, a8: UInt, a9: UInt16, a10: UInt64, a11: UInt, a12: UInt16, a13: UInt, a14: Double, a15: Int64, a16: Int64, a17: UInt8, a18: Int64, a19: UInt64, a20: Float, a21: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + hasher.combine(a17); + hasher.combine(a18); + hasher.combine(a19); + hasher.combine(a20); + hasher.combine(a21); + return hasher.finalize() +} + +public func swiftFunc96(a0: UInt64, a1: Int16, a2: UInt32, a3: Int64, a4: Float, a5: Int, a6: Int8, a7: Int8, a8: Int8, a9: UInt64, a10: UInt8, a11: UInt16, a12: UInt64, a13: UInt32, a14: Int64, a15: Int32, a16: UInt8) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + hasher.combine(a16); + return hasher.finalize() +} + +public func swiftFunc97(a0: UInt16, a1: UInt8, a2: UInt8, a3: Int8, a4: Int64, a5: UInt8, a6: UInt16, a7: UInt32, a8: UInt) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + return hasher.finalize() +} + +public func swiftFunc98(a0: UInt16, a1: Int8, a2: Double, a3: Int, a4: UInt, a5: UInt8, a6: UInt32, a7: UInt8, a8: UInt, a9: UInt16, a10: Float, a11: Int8, a12: Double, a13: Int32, a14: UInt16, a15: Int16) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + hasher.combine(a3); + hasher.combine(a4); + hasher.combine(a5); + hasher.combine(a6); + hasher.combine(a7); + hasher.combine(a8); + hasher.combine(a9); + hasher.combine(a10); + hasher.combine(a11); + hasher.combine(a12); + hasher.combine(a13); + hasher.combine(a14); + hasher.combine(a15); + return hasher.finalize() +} + +public func swiftFunc99(a0: UInt8, a1: UInt, a2: UInt64) -> Int { + var hasher = HasherFNV1a() + hasher.combine(a0); + hasher.combine(a1); + hasher.combine(a2); + return hasher.finalize() +} diff --git a/src/SwiftBindings/tests/SmokeTests.cs b/src/SwiftBindings/tests/SmokeTests.cs deleted file mode 100644 index 29ee18d55d1e..000000000000 --- a/src/SwiftBindings/tests/SmokeTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using Xunit; - -namespace SwiftBindings.Tests -{ - public class SmokeTests - { - [Fact] - public void DirectPInvokeVoidVoid() - { - BindingsTool.GenerateBindings("SmokeTests.abi.json", ""); - var sourceCode = """ - // Copyright (c) Microsoft Corporation. - // Licensed under the MIT License. - - using System; - using SmokeTestsBindings; - - namespace Hello { - class MainClass { - public static int Main(string[] args) - { - SmokeTests.SimplePinvokeVoidVoid(); - return 42; - } - } - } - """; - - int result = TestsHelper.CompileAndExecuteFromFileAndString("SmokeTestsBindings.cs", sourceCode); - Assert.Equal(42, result); - } - } -} diff --git a/src/SwiftBindings/tests/SmokeTests.swift b/src/SwiftBindings/tests/SmokeTests.swift deleted file mode 100644 index eb556889f728..000000000000 --- a/src/SwiftBindings/tests/SmokeTests.swift +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -public func SimplePinvokeVoidVoid() -{ - print("Hello world"); -} diff --git a/src/SwiftBindings/tests/TestsHelper.cs b/src/SwiftBindings/tests/TestsHelper.cs index 1ca9e84f43d8..6385b631d7c4 100644 --- a/src/SwiftBindings/tests/TestsHelper.cs +++ b/src/SwiftBindings/tests/TestsHelper.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.Loader; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; @@ -13,22 +14,24 @@ namespace SwiftBindings.Tests { public static class TestsHelper { - public static int CompileAndExecuteFromFileAndString(string filePath, string sourceCode) + public static object CompileAndExecute(string filePath, string sourceCode, string typeName, string methodName) { string fileSourceCode = File.ReadAllText(filePath); var sourceCodes = new[] { fileSourceCode, sourceCode }; - return CompileAndExecute(sourceCodes); + return CompileAndExecute(sourceCodes, typeName, methodName); } - private static int CompileAndExecute(string[] sourceCodes) + private static object CompileAndExecute(string[] sourceCodes, string typeName, string methodName) { var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication); var syntaxTrees = sourceCodes.Select(code => CSharpSyntaxTree.ParseText(code)).ToArray(); + var systemRuntimeAssemblyPath = Assembly.Load("System.Runtime").Location; var references = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Console).Assembly.Location), + MetadataReference.CreateFromFile(systemRuntimeAssemblyPath), }; @@ -53,12 +56,20 @@ private static int CompileAndExecute(string[] sourceCodes) } } - Assembly compiledAssembly = Assembly.LoadFile(assemblyPath); - - MethodInfo entryPoint = compiledAssembly.EntryPoint; - object[] args = entryPoint.GetParameters().Length == 0 ? null : new object[] { new string[0] }; - int result = (int)entryPoint.Invoke(null, args); + AssemblyLoadContext context = new AssemblyLoadContext("", true); + object result = null; + try + { + Assembly compiledAssembly = context.LoadFromAssemblyPath(assemblyPath); + Type targetType = compiledAssembly.GetType("Test.MainClass"); + MethodInfo customMethod = targetType.GetMethod(methodName); + result = customMethod.Invoke(null, new object[] { }); + } + finally + { + context.Unload(); + } return result; } } diff --git a/src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs b/src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs index cd5258f00e03..a2dc0d3040ff 100644 --- a/src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs +++ b/src/SwiftReflector/src/Parser/SwiftABIParser/SwiftABIParser.cs @@ -96,19 +96,16 @@ public FunctionDeclaration CreateFunctionDecl(Node decl) break; } - if (decl.Children.Count == 0) - functionDeclaration.ParameterLists.Add(new List()); - else { - var funcSignature = decl.PrintedName.Split("(")[1].Split(")")[0].Split(":", StringSplitOptions.RemoveEmptyEntries); - for (int i = 1; i < decl.Children.Count; i++) - { - var param = decl.Children[i]; - ParameterItem parameterItem = new ParameterItem(); - parameterItem.TypeSpec = new NamedTypeSpec(param.PrintedName); - if (funcSignature.Length > i - 1) - parameterItem.PublicName = funcSignature[i - 1]; - functionDeclaration.ParameterLists.Add(new List { parameterItem }); - } + functionDeclaration.ParameterLists.Add(new List()); + var funcSignature = decl.PrintedName.Split("(")[1].Split(")")[0].Split(":", StringSplitOptions.RemoveEmptyEntries); + for (int i = 1; i < decl.Children.Count; i++) + { + var param = decl.Children[i]; + ParameterItem parameterItem = new ParameterItem(); + parameterItem.TypeSpec = new NamedTypeSpec(param.PrintedName); + if (funcSignature.Length > i - 1) + parameterItem.PublicName = funcSignature[i - 1]; + functionDeclaration.ParameterLists.FirstOrDefault().Add(parameterItem); } return functionDeclaration; } diff --git a/src/SwiftRuntimeLibrary/src/SwiftCore.xml b/src/SwiftRuntimeLibrary/src/SwiftCore.xml index d7085bb6d412..96066ebbbaa3 100644 --- a/src/SwiftRuntimeLibrary/src/SwiftCore.xml +++ b/src/SwiftRuntimeLibrary/src/SwiftCore.xml @@ -1,18 +1,13 @@ - - - - - + + + - - - @@ -31,21 +26,29 @@ - - - - - - + + + + + + + + + + + + + + @@ -115,7 +118,7 @@ - + diff --git a/src/samples/HelloWorld/build.sh b/src/samples/HelloWorld/build.sh index d89b3859611a..a2e0b30b8a6b 100755 --- a/src/samples/HelloWorld/build.sh +++ b/src/samples/HelloWorld/build.sh @@ -6,7 +6,7 @@ dotnet build ../../SwiftBindings/src/SwiftBindings.csproj if [ $? -eq 0 ]; then echo "Build successful. Running the BindingsTool..." - dotnet ../../../artifacts/bin/SwiftBindings/Debug/net7.0/SwiftBindings.dll -a "./HelloLibrary.abi.json" -o "./" + dotnet ../../../artifacts/bin/SwiftBindings/Debug/net8.0/SwiftBindings.dll -a "./HelloLibrary.abi.json" -o "./" dotnet run else echo "Build failed. Exiting..." From 442d9aee652f6b38646a74ed31295e2b3e9c0c53 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Thu, 22 Feb 2024 10:39:33 +0100 Subject: [PATCH 34/37] Add uniqueId to CompiledAssembly name --- src/SwiftBindings/tests/TestsHelper.cs | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/src/SwiftBindings/tests/TestsHelper.cs b/src/SwiftBindings/tests/TestsHelper.cs index 6385b631d7c4..80546053798f 100644 --- a/src/SwiftBindings/tests/TestsHelper.cs +++ b/src/SwiftBindings/tests/TestsHelper.cs @@ -14,6 +14,7 @@ namespace SwiftBindings.Tests { public static class TestsHelper { + private static int uniqueId = 0; public static object CompileAndExecute(string filePath, string sourceCode, string typeName, string methodName) { string fileSourceCode = File.ReadAllText(filePath); @@ -35,12 +36,12 @@ private static object CompileAndExecute(string[] sourceCodes, string typeName, s }; - var compilation = CSharpCompilation.Create("CompiledAssembly", + var compilation = CSharpCompilation.Create($"CompiledAssembly{uniqueId}", syntaxTrees: syntaxTrees, references: references, options: options); - string assemblyPath = Path.Combine(Path.GetTempPath(), "CompiledAssembly.dll"); + string assemblyPath = Path.Combine(Path.GetTempPath(), $"CompiledAssembly{uniqueId++}.dll"); using (var stream = new FileStream(assemblyPath, FileMode.Create)) { EmitResult emitResult = compilation.Emit(stream); @@ -56,21 +57,10 @@ private static object CompileAndExecute(string[] sourceCodes, string typeName, s } } - AssemblyLoadContext context = new AssemblyLoadContext("", true); - object result = null; - try - { - Assembly compiledAssembly = context.LoadFromAssemblyPath(assemblyPath); - + Assembly compiledAssembly = Assembly.LoadFile(assemblyPath); Type targetType = compiledAssembly.GetType("Test.MainClass"); MethodInfo customMethod = targetType.GetMethod(methodName); - result = customMethod.Invoke(null, new object[] { }); - } - finally - { - context.Unload(); - } - return result; + return customMethod.Invoke(null, new object[] { }); } } } \ No newline at end of file From 0574a8bad7b5d7ebda9f1b0c6a136c3aa4fb2d35 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Thu, 22 Feb 2024 11:03:01 +0100 Subject: [PATCH 35/37] Update runtimelab.yml pipeline configuration --- eng/pipelines/runtimelab.yml | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/eng/pipelines/runtimelab.yml b/eng/pipelines/runtimelab.yml index 2a99576a961e..ca89c58c559c 100644 --- a/eng/pipelines/runtimelab.yml +++ b/eng/pipelines/runtimelab.yml @@ -49,13 +49,32 @@ stages: - stage: build displayName: Build jobs: - - template: /eng/pipelines/templates/build-job.yml - parameters: - osGroup: OSX - archType: x64 - runTests: true - pool: - vmImage: 'macOS-latest' + - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - template: /eng/pipelines/templates/build-job.yml + parameters: + osGroup: OSX + archType: x64 + isOfficialBuild: true + runTests: false + pool: + vmImage: 'macOS-latest' + + - ${{ if or(eq(variables['System.TeamProject'], 'public'), in(variables['Build.Reason'], 'PullRequest')) }}: + - template: /eng/pipelines/templates/build-job.yml + parameters: + osGroup: OSX + archType: arm64 + runTests: true + pool: + vmImage: 'macOS-latest' + + - template: /eng/pipelines/templates/build-job.yml + parameters: + osGroup: Linux + archType: x64 + runTests: true + pool: + vmImage: 'macOS-latest' # Publish and validation steps. Only run in official builds - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: From 919f7ce1cbfa0c6707d2c8df5a5c1dbf3d0a9410 Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Thu, 22 Feb 2024 11:03:52 +0100 Subject: [PATCH 36/37] Change osGroup from Linux to OSX in runtimelab.yml --- eng/pipelines/runtimelab.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/runtimelab.yml b/eng/pipelines/runtimelab.yml index ca89c58c559c..3d3a7752e8c7 100644 --- a/eng/pipelines/runtimelab.yml +++ b/eng/pipelines/runtimelab.yml @@ -70,7 +70,7 @@ stages: - template: /eng/pipelines/templates/build-job.yml parameters: - osGroup: Linux + osGroup: OSX archType: x64 runTests: true pool: From 276918e20ca209310ceaba5e674a0a7c6ad35a0d Mon Sep 17 00:00:00 2001 From: Milos Kotlar Date: Thu, 22 Feb 2024 13:22:57 +0100 Subject: [PATCH 37/37] Add sample bindings to .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index dbcf980bff27..0cc382c65b87 100644 --- a/.gitignore +++ b/.gitignore @@ -200,4 +200,5 @@ launchSettings.json *.dylib # Testing artifacts -testing/ \ No newline at end of file +testing/ +src/samples/**/*Bindings.cs \ No newline at end of file