From 6c23cf74582cefdfad44f07eb38c06dd0a37ece8 Mon Sep 17 00:00:00 2001 From: Will Hawkins Date: Fri, 12 Jun 2026 23:23:35 -0400 Subject: [PATCH] Refactor P4Compiler to P4Parser Signed-off-by: Will Hawkins --- Package.swift | 10 +- Snippets/use-program-instanceswithtypes.swift | 50 -- Snippets/use-program-typeswithtypes.swift | 45 -- Sources/Macros/Macros.swift | 12 +- Sources/P4CodeGen/Serializer.swift | 53 +- Sources/P4Compiler/Protocols.swift | 71 --- Sources/P4Compiler/SpecialCompilers.swift | 240 --------- .../AST.swift => P4Parser/CST.swift} | 231 +++++---- Sources/{P4Compiler => P4Parser}/Common.swift | 6 +- .../{P4Compiler => P4Parser}/Compiler.swift | 22 + .../{P4Compiler => P4Parser}/Feedback.swift | 0 .../Parsers}/Declarations.swift | 486 +++++++++--------- .../Parsers}/Expression.swift | 256 ++++----- .../Parsers}/Parser.swift | 86 +--- Sources/P4Parser/Parsers/Program.swift | 72 +++ Sources/P4Parser/Parsers/SpecialParsers.swift | 67 +++ .../Parsers}/Statement.swift | 290 +++++++---- .../Parsers}/Types.swift | 46 +- Sources/P4Parser/Protocols.swift | 73 +++ .../{P4Compiler => P4Parser}/Visitor.swift | 24 +- Sources/{P4Compiler => P4Parser}/Walker.swift | 0 .../p4rseTests/CodeGenTests/Serializer.swift | 12 +- .../SourceCodeTests/SourceCode.swift | 10 +- 23 files changed, 1042 insertions(+), 1120 deletions(-) delete mode 100644 Snippets/use-program-instanceswithtypes.swift delete mode 100644 Snippets/use-program-typeswithtypes.swift delete mode 100644 Sources/P4Compiler/Protocols.swift delete mode 100644 Sources/P4Compiler/SpecialCompilers.swift rename Sources/{P4Compiler/AST.swift => P4Parser/CST.swift} (67%) rename Sources/{P4Compiler => P4Parser}/Common.swift (85%) rename Sources/{P4Compiler => P4Parser}/Compiler.swift (63%) rename Sources/{P4Compiler => P4Parser}/Feedback.swift (100%) rename Sources/{P4Compiler => P4Parser/Parsers}/Declarations.swift (71%) rename Sources/{P4Compiler => P4Parser/Parsers}/Expression.swift (71%) rename Sources/{P4Compiler => P4Parser/Parsers}/Parser.swift (58%) create mode 100644 Sources/P4Parser/Parsers/Program.swift create mode 100644 Sources/P4Parser/Parsers/SpecialParsers.swift rename Sources/{P4Compiler => P4Parser/Parsers}/Statement.swift (53%) rename Sources/{P4Compiler => P4Parser/Parsers}/Types.swift (66%) create mode 100644 Sources/P4Parser/Protocols.swift rename Sources/{P4Compiler => P4Parser}/Visitor.swift (73%) rename Sources/{P4Compiler => P4Parser}/Walker.swift (100%) diff --git a/Package.swift b/Package.swift index 1b5c79a..dc1d54f 100644 --- a/Package.swift +++ b/Package.swift @@ -10,8 +10,8 @@ let package = Package( products: [ // Products define the executables and libraries a package produces, making them visible to other packages. .library( - name: "P4Compiler", - targets: ["P4Compiler"] + name: "P4Parser", + targets: ["P4Parser"] ), .library( name: "Common", @@ -40,7 +40,7 @@ let package = Package( ], swiftSettings: [.enableExperimentalFeature("CodeItemMacros")]), .target( - name: "P4Compiler", + name: "P4Parser", dependencies: [ .product(name: "SwiftTreeSitter", package: "swift-tree-sitter"), .product(name: "SwiftTreeSitterLayer", package: "swift-tree-sitter"), @@ -70,14 +70,14 @@ let package = Package( .target( name: "P4CodeGen", dependencies: [ - "P4Compiler", "Common", + "P4Parser", "Common", //.product(name: "SwiftProtobuf", package: "swift-protobuf"), ] ), .testTarget( name: "Tests", dependencies: [ - "P4Compiler", "P4CodeGen", "Macros", "TreeSitterExtensions", "Common", + "P4Parser", "P4CodeGen", "Macros", "TreeSitterExtensions", "Common", .product(name: "SystemPackage", package: "swift-system"), ], //swiftSettings: [.enableExperimentalFeature("CodeItemMacros"), .unsafeFlags(["-Xfrontend", "-dump-macro-expansions"])], diff --git a/Snippets/use-program-instanceswithtypes.swift b/Snippets/use-program-instanceswithtypes.swift deleted file mode 100644 index fb46fad..0000000 --- a/Snippets/use-program-instanceswithtypes.swift +++ /dev/null @@ -1,50 +0,0 @@ -// p4rse, Copyright 2026, Will Hawkins -// -// This file is part of p4rse. -// -// This file is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -import Common -import Foundation -import Runtime -import SwiftTreeSitter -import Testing -import TreeSitter -import TreeSitterP4 -import P4Compiler - -let p4_program_with_control_decl = """ - control simple() { - action a() { - } - table t { - key = { - true: exact; - } - } - }; - """ - -/* -// snippet.include -let flter = { (tipe: P4QualifiedType) -> Bool in - switch tipe.baseType(){ - case let c as Control: c.name == "simple" - default: false - } -} -if case .Ok(let program) = SpecialCompilers.ProgramCompiler.Compile(p4_program_with_control_decl) { - print(program.InstancesWithTypes(flter)) -} -*/ \ No newline at end of file diff --git a/Snippets/use-program-typeswithtypes.swift b/Snippets/use-program-typeswithtypes.swift deleted file mode 100644 index 31124cc..0000000 --- a/Snippets/use-program-typeswithtypes.swift +++ /dev/null @@ -1,45 +0,0 @@ -// p4rse, Copyright 2026, Will Hawkins -// -// This file is part of p4rse. -// -// This file is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -import Common -import Foundation -import Runtime -import SwiftTreeSitter -import Testing -import TreeSitter -import TreeSitterP4 -import P4Compiler - -let p4_program_with_struct_decl = """ - struct agg { - int x; - }; - """ - -/* -// snippet.include -let flter = { (tipe: P4Type) -> Bool in - switch tipe { - case let c as P4Struct: c.name == "agg" - default: false - } -} -if case .Ok(let program) = SpecialCompilers.ProgramCompiler.Compile(p4_program_with_struct_decl) { - print(program.TypesWithTypes(flter)) -} - -*/ \ No newline at end of file diff --git a/Sources/Macros/Macros.swift b/Sources/Macros/Macros.swift index b8a4ef3..34b03c4 100644 --- a/Sources/Macros/Macros.swift +++ b/Sources/Macros/Macros.swift @@ -439,7 +439,7 @@ public struct CliTestDeclarationMacro: PeerMacro, Sendable { } } -public enum DeriveCompilableStatement: MemberMacro { +public enum DeriveParsableStatement: MemberMacro { public static func expansion( of: AttributeSyntax, providingMembersOf type: some DeclGroupSyntax, conformingTo: [TypeSyntax], in: some MacroExpansionContext @@ -447,10 +447,10 @@ public enum DeriveCompilableStatement: MemberMacro { let implementation = DeclSyntax( """ - public static func CompileStatement( - node: Node, withContext context: ASTCompilerContext - ) -> Result { - return switch Compile(node: node, withContext: context) { + public static func ParseStatement( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + return switch Parse(node: node, withContext: context) { case .Ok(let res): .Ok(res) case .Error(let e): .Error(e) } @@ -465,6 +465,6 @@ struct P4Macros: CompilerPlugin { var providingMacros: [Macro.Type] = [ RequireResult.self, RequireErrorResult.self, UseOkResult.self, UseErrorResult.self, RequireNodeType.self, SkipUnlessNodeType.self, SkipUnlessNodesTypes.self, RequireNodesType.self, - MustOr.self, CliTestDeclarationMacro.self, DeriveCompilableStatement.self, + MustOr.self, CliTestDeclarationMacro.self, DeriveParsableStatement.self, ] } diff --git a/Sources/P4CodeGen/Serializer.swift b/Sources/P4CodeGen/Serializer.swift index ec82e7c..143ad63 100644 --- a/Sources/P4CodeGen/Serializer.swift +++ b/Sources/P4CodeGen/Serializer.swift @@ -16,50 +16,50 @@ // along with this program. If not, see . import Common -import P4Compiler +import P4Parser -public struct TextSerializer { +public struct CSTTextSerializer { public init() {} } -public struct TextSerializerContext { +public struct CSTTextSerializerContext { public let serialized: String public init(_ serialized: String = "") { self.serialized = serialized } - public func append(_ a: String) -> TextSerializerContext { - return TextSerializerContext(self.serialized + a) + public func append(_ a: String) -> CSTTextSerializerContext { + return CSTTextSerializerContext(self.serialized + a) } } -extension TextSerializer: ASTVisitor { +extension CSTTextSerializer: CSTVisitor { public func visit( - node: P4Compiler.AST.BinaryOperatorExpression, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.BinaryOperatorExpression, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("Binary Operator Expression")) } public func visit( - node: P4Compiler.AST.Literal, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.Literal, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("Literal Expression")) } public func visit( - node: P4Compiler.AST.Identifier, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.Identifier, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("Identifier Expression")) } public func visit( - node: P4Compiler.AST.Parser, driver: P4Compiler.ASTVisitorDriver, context: TextSerializerContext - ) -> Common.Result { + node: CST.Parser, driver: CSTVisitorDriver, context: CSTTextSerializerContext + ) -> Common.Result { var context = context.append("Identifier Expression") for s in node.states.states { switch driver.visit(state: s, visitor: self, context: context) { @@ -72,24 +72,23 @@ extension TextSerializer: ASTVisitor { } public func visit( - node: P4Compiler.AST.ParserStateDirectTransition, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.ParserStateDirectTransition, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("State: Direct Transition")) } public func visit( - node: P4Compiler.AST.ParserStateNoTransition, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.ParserStateNoTransition, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("State: No Transition")) } public func visit( - node: P4Compiler.AST.ParserStateSelectTransition, driver: P4Compiler.ASTVisitorDriver, - context: TextSerializerContext - ) -> Common.Result { + node: CST.ParserStateSelectTransition, driver: CSTVisitorDriver, + context: CSTTextSerializerContext + ) -> Common.Result { return .Ok(context.append("State: Direct Transition")) } - } diff --git a/Sources/P4Compiler/Protocols.swift b/Sources/P4Compiler/Protocols.swift deleted file mode 100644 index abdbeae..0000000 --- a/Sources/P4Compiler/Protocols.swift +++ /dev/null @@ -1,71 +0,0 @@ -// p4rse, Copyright 2026, Will Hawkins -// -// This file is part of p4rse. -// -// This file is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -import Common -import SwiftTreeSitter -import TreeSitterExtensions -import TreeSitterP4 - -public protocol CompilableValue { - static func CompileValue(withValue value: String) -> Result -} - -public protocol MaybeCompilableType { - static func MaybeCompileType( - type: SwiftTreeSitter.Node, withContext: ASTCompilerContext - ) -> Result -} - -public protocol CompilableType { - static func CompileType( - type: SwiftTreeSitter.Node, withContext: ASTCompilerContext - ) -> Result -} -public protocol CompilableExpression { - static func CompileExpression( - node: Node, withContext context: ASTCompilerContext - ) -> Result -} - -public protocol Compilable { - associatedtype C - static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result -} - -public protocol CompilableStatement { - static func CompileStatement( - node: Node, withContext context: ASTCompilerContext - ) -> Result -} - -public protocol ASTVisitor { - associatedtype T - func visit(node: AST.BinaryOperatorExpression, driver: ASTVisitorDriver, context: T) -> Result - func visit(node: AST.Literal, driver: ASTVisitorDriver, context: T) -> Result - func visit(node: AST.Identifier, driver: ASTVisitorDriver, context: T) -> Result - - func visit(node: AST.Parser, driver: ASTVisitorDriver, context: T) -> Result - func visit( - node: AST.ParserStateDirectTransition, driver: ASTVisitorDriver, context: T - ) -> Result - func visit(node: AST.ParserStateNoTransition, driver: ASTVisitorDriver, context: T) -> Result - func visit( - node: AST.ParserStateSelectTransition, driver: ASTVisitorDriver, context: T - ) -> Result -} diff --git a/Sources/P4Compiler/SpecialCompilers.swift b/Sources/P4Compiler/SpecialCompilers.swift deleted file mode 100644 index ed8a0a0..0000000 --- a/Sources/P4Compiler/SpecialCompilers.swift +++ /dev/null @@ -1,240 +0,0 @@ -// p4rse, Copyright 2026, Will Hawkins -// -// This file is part of p4rse. -// -// This file is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -import Common -import SwiftTreeSitter -import TreeSitterExtensions -import TreeSitterP4 - -extension AST.TransitionStatement: Compilable { - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { - - guard let state_identifier = context.lexical_context_name else { - return .Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), - withError: "Cannot parse a transition statement without the name of the containing state." - )) - } - - guard let stmts = context.lexical_context_statements else { - return .Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), - withError: - "Cannot parse a transition statement without statements of the containing state.")) - } - - #RequireNodeType( - node: node, type: "parserTransitionStatement", nice_type_name: "parser transition statement" - ) - - guard let tse_node = node.child(at: 1), - tse_node.nodeType! == "transitionSelectionExpression" - else { - return .Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), - withError: "Could not find transition select expression")) - } - - guard let next_node = tse_node.child(at: 0) else { - return .Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), - withError: "Could not find the next token in a transition selection expression")) - } - - // If the next node is an identifier, we have the simple form ... - if next_node.nodeType == "identifier" { - let maybe_parsed_next_state_id = AST.Identifier.CompileExpression( - node: next_node, withContext: context) - switch maybe_parsed_next_state_id { - case .Ok(let next_state_id): - return .Ok( - AST.ParserStateDirectTransition( - name: (state_identifier), - withNextStateIdentifier: next_state_id as! AST.Identifier, withStatements: stmts)) - case .Error(let e): - return .Error(e) - } - } - - // We know that the next node is a select expression. - return - switch AST.SelectExpression.CompileExpression(node: next_node, withContext: context) - { - case .Ok(let tse): - .Ok( - AST.ParserStateSelectTransition( - name: state_identifier, withTransitionExpression: tse as! AST.SelectExpression, - withStatements: stmts, - ) - ) - case .Error(let e): .Error(e) - } - } -} - -public struct SpecialCompilers { - public struct Statements { - static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result<[AST.AnStatement]> { - if node.nodeType != "statements" && node.nodeType != "parserStatements" { - return Result.Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), withError: "Did not find expected statements")) - } - - var errors: (any Errorable)? = .none - var parsed_s: [AST.AnStatement] = Array() - - node.enumerateNamedChildren { node in - switch AST.Statement.Compile( - node: node, withContext: context) - { - case .Ok(let parsed_statement): - parsed_s.append(parsed_statement) - case .Error(let e): - errors = - if let errors = errors { - errors.append(error: e) - } else { - e - } - } - } - - if let errors = errors { - return .Error(errors) - } - - return Result.Ok(parsed_s) - } - } - - static func CompileParserBody( - withName name: AST.Identifier, withParameters parameters: AST.ParameterList, node: Node, - withContext context: ASTCompilerContext - ) -> Result { - - var parser = AST.Parser(withName: name, withParameters: parameters) - - // Build a state from each one listed. - var errors: (any Errorable)? = .none - - /// TODO: Assert that there is only one. - node.enumerateNamedChildren { parser_state in - if parser_state.nodeType != "parserState" { - return - } - - // Parse a state in a nested scope. - switch AST.ParserState.Compile( - node: parser_state, - withContext: context) - { - case Result.Ok(let state): - // All states are instances inside the parser. - parser.states = parser.states.append(state: state) - case Result.Error(let e): - errors = - if let errors = errors { - errors.append(error: e) - } else { - e - } - } - } - - if let errors = errors { - return .Error(errors) - } - - return .Ok(parser) - } - - public struct ProgramCompiler { - public static func Compile(_ source: String) -> Result { - - let maybe_parser = ConfigureP4Parser() - guard case .Ok(let p) = maybe_parser else { - return .Error(maybe_parser.error()!) - } - - let result = p.parse(source) - guard let tree = result, - !tree.isError(lang: p4lang), - !tree.containsMissing(lang: p4lang) - else { - return Result.Error(Error(withMessage: "Could not compile the P4 program")) - } - - var program = AST.Program() - - // Set up a context for parsing. - let compilation_context = ASTCompilerContext() - - var errors: (any Errorable)? = .none - - // Try to parse all top-level declarations. - result?.rootNode?.enumerateNamedChildren { (declaration_node: Node) in - let declaration_parsers: [String: CompilableStatement.Type] = [ - "declaration": AST.Declaration.self, - "instantiation": AST.Instantiation.self, - ] - - if let parser = declaration_parsers[declaration_node.nodeType!] { - let r = parser.CompileStatement(node: declaration_node, withContext: compilation_context) - switch r { - case .Ok(let compiled): - program.statements = program.statements + [compiled] - case .Error(let e): - errors = - if let errors = errors { - errors.append(error: e) - } else { - e - } - - } - } else { - let e = ErrorWithLocation( - sourceLocation: declaration_node.toSourceLocation(), - withError: - "\(declaration_node.nodeType!) cannot be at a P4 program top level") - errors = - if let errors = errors { - errors.append(error: e) - } else { - e - } - } - } - - if let errors = errors { - return .Error(errors) - } - return Result.Ok(program) - - } - } - -} diff --git a/Sources/P4Compiler/AST.swift b/Sources/P4Parser/CST.swift similarity index 67% rename from Sources/P4Compiler/AST.swift rename to Sources/P4Parser/CST.swift index 10b4965..30ed8f6 100644 --- a/Sources/P4Compiler/AST.swift +++ b/Sources/P4Parser/CST.swift @@ -17,24 +17,31 @@ import Common -extension P4Value: AST.AnExpression {} +extension P4Value: CST.AnExpression {} -public struct AST { +public struct CST { public protocol AnExpression {} - public protocol AnStatement {} + public protocol Statement {} public protocol AnState {} - public struct Statement {} struct Expression {} - public struct VariableDeclarationStatement: AnStatement { + public struct Statements { + public let statements: [Statement] + + public init(_ s: [Statement]) { + self.statements = s + } + } + + public struct VariableDeclarationStatement: Statement { public var initializer: AnExpression? - public var identifier: AST.Identifier - public var tipe: AST.Tipe + public var identifier: CST.Identifier + public var tipe: CST.Tipe public init( - identifier: Identifier, withType tipe: AST.Tipe, withInitializer initializer: AnExpression? + identifier: Identifier, withType tipe: CST.Tipe, withInitializer initializer: AnExpression? ) { self.identifier = identifier self.initializer = initializer @@ -42,20 +49,20 @@ public struct AST { } } - public struct ConditionalStatement: AnStatement { + public struct ConditionalStatement: Statement { public var condition: AnExpression - public var thenn: AnStatement - public var elss: AnStatement? + public var thenn: Statement + public var elss: Statement? - public init(condition: AnExpression, withThen thenn: AnStatement) { + public init(condition: AnExpression, withThen thenn: Statement) { self.condition = condition self.thenn = thenn self.elss = .none } public init( - condition: AnExpression, withThen thenn: AnStatement, - andElse elss: AnStatement + condition: AnExpression, withThen thenn: Statement, + andElse elss: Statement ) { self.condition = condition self.thenn = thenn @@ -63,16 +70,16 @@ public struct AST { } } - public struct BlockStatement: AnStatement { - public var statements: [AnStatement] + public struct BlockStatement: Statement { + public var statements: Statements - public init(_ statements: [AnStatement]) { + public init(_ statements: Statements) { self.statements = statements } } - public struct ReturnStatement: AnStatement { + public struct ReturnStatement: Statement { public let value: AnExpression public init(_ value: AnExpression) { @@ -80,11 +87,11 @@ public struct AST { } } - public struct ApplyStatement: AnStatement { - public let body: AST.BlockStatement? + public struct ApplyStatement: Statement { + public let body: CST.BlockStatement? public init() { self.body = .none } - public init(_ body: AST.BlockStatement) { + public init(_ body: CST.BlockStatement) { self.body = body } } @@ -95,14 +102,14 @@ public struct AST { + "\(self.name) with parameters \(self.params) and body \(String(describing: self.body))" } - public var body: AST.BlockStatement? - public var params: AST.ParameterList - public var name: AST.Identifier + public var body: CST.BlockStatement? + public var params: CST.ParameterList + public var name: CST.Identifier public init( - named name: AST.Identifier = AST.Identifier(Common.Identifier(name: "")), + named name: CST.Identifier = CST.Identifier(Common.Identifier(name: "")), withParameters parameters: ParameterList = ParameterList([]), - withBody body: AST.BlockStatement? = .none + withBody body: CST.BlockStatement? = .none ) { self.name = name self.params = parameters @@ -112,8 +119,8 @@ public struct AST { } public struct Actions: CustomStringConvertible { - public let actions: [AST.Action] - public init(withActions actions: [AST.Action]) { + public let actions: [CST.Action] + public init(withActions actions: [CST.Action]) { self.actions = actions } @@ -130,10 +137,10 @@ public struct AST { } public struct TableKeyEntry: CustomStringConvertible { - public let key: AST.KeysetExpression - public let match_type: AST.TableKeyMatchType + public let key: CST.KeysetExpression + public let match_type: CST.TableKeyMatchType - public init(_ key: AST.KeysetExpression, _ match: AST.TableKeyMatchType) { + public init(_ key: CST.KeysetExpression, _ match: CST.TableKeyMatchType) { self.key = key self.match_type = match } @@ -144,9 +151,9 @@ public struct AST { } public struct TableKeys: CustomStringConvertible { - public let keys: [AST.TableKeyEntry] + public let keys: [CST.TableKeyEntry] - public init(withEntries entries: [AST.TableKeyEntry]) { + public init(withEntries entries: [CST.TableKeyEntry]) { self.keys = entries } public init() { @@ -162,8 +169,8 @@ public struct AST { } public struct TableActionsProperty: CustomStringConvertible { - public let actions: [AST.Identifier] - public init(_ actions: [AST.Identifier] = []) { + public let actions: [CST.Identifier] + public init(_ actions: [CST.Identifier] = []) { self.actions = actions } @@ -176,9 +183,9 @@ public struct AST { } public struct TablePropertyList: CustomStringConvertible { - public let actions: AST.TableActionsProperty - public let keys: AST.TableKeys - public init(withActions actions: AST.TableActionsProperty, withKeys keys: AST.TableKeys) { + public let actions: CST.TableActionsProperty + public let keys: CST.TableKeys + public init(withActions actions: CST.TableActionsProperty, withKeys keys: CST.TableKeys) { self.actions = actions self.keys = keys } @@ -189,13 +196,13 @@ public struct AST { } public struct Table: CustomStringConvertible { - public let properties: AST.TablePropertyList - let name: AST.Identifier - public let entries: [(P4Value, AST.Identifier)] + public let properties: CST.TablePropertyList + let name: CST.Identifier + public let entries: [(P4Value, CST.Identifier)] public init( - withName name: AST.Identifier, withPropertyList property_list: AST.TablePropertyList, - withEntries entries: [(P4Value, AST.Identifier)] = [] + withName name: CST.Identifier, withPropertyList property_list: CST.TablePropertyList, + withEntries entries: [(P4Value, CST.Identifier)] = [] ) { self.name = name self.properties = property_list @@ -210,13 +217,13 @@ public struct AST { /// compared to the entries and the match is assocated with an action /// that is invoked when the match occurs! - public func update(addEntry entry: (P4Value, AST.Identifier)) -> Table { + public func update(addEntry entry: (P4Value, CST.Identifier)) -> Table { return Table( withName: self.name, withPropertyList: self.properties, withEntries: self.entries + [entry]) } } - public protocol AnDeclaration: AnStatement {} + public protocol AnDeclaration: Statement {} public struct Declaration {} @@ -225,24 +232,24 @@ public struct AST { return "Control named \(self._name) \(self.parameters) \(self.actions) \(self.table)" } - public let actions: AST.Actions - public let table: AST.Table - let _parameters: AST.ParameterList - let _name: AST.Identifier - let apply: AST.ApplyStatement + public let actions: CST.Actions + public let table: CST.Table + let _parameters: CST.ParameterList + let _name: CST.Identifier + let apply: CST.ApplyStatement - public var parameters: AST.ParameterList { + public var parameters: CST.ParameterList { _parameters } - public var name: AST.Identifier { + public var name: CST.Identifier { _name } public init( - named: AST.Identifier, withParameters parameters: AST.ParameterList, - withTable table: AST.Table, - withActions actions: AST.Actions, withApply apply: AST.ApplyStatement + named: CST.Identifier, withParameters parameters: CST.ParameterList, + withTable table: CST.Table, + withActions actions: CST.Actions, withApply apply: CST.ApplyStatement ) { self._name = named self._parameters = parameters @@ -251,7 +258,7 @@ public struct AST { self.apply = apply } - public func updateTable(addEntry entry: (P4Value, AST.Identifier)) -> Control { + public func updateTable(addEntry entry: (P4Value, CST.Identifier)) -> Control { let table = self.table.update(addEntry: entry) return Control( @@ -266,9 +273,9 @@ public struct AST { } public struct ExternDeclaration: AnDeclaration { - public let declaration: AST.AnDeclaration + public let declaration: CST.AnDeclaration - public init(_ declaration: AST.AnDeclaration) { + public init(_ declaration: CST.AnDeclaration) { self.declaration = declaration } } @@ -278,15 +285,15 @@ public struct AST { return "Function named \(self.name) that returns \(self.tipe) with parameters \(self.params)" } - public var body: AST.BlockStatement? - public var params: AST.ParameterList - public var name: AST.Identifier - public var tipe: AST.Tipe + public var body: CST.BlockStatement? + public var params: CST.ParameterList + public var name: CST.Identifier + public var tipe: CST.Tipe public init( - named name: AST.Identifier, ofType type: AST.Tipe, - withParameters parameters: AST.ParameterList, - withBody body: AST.BlockStatement? + named name: CST.Identifier, ofType type: CST.Tipe, + withParameters parameters: CST.ParameterList, + withBody body: CST.BlockStatement? ) { self.name = name self.tipe = type @@ -296,22 +303,22 @@ public struct AST { } public struct StructDeclaration: AnDeclaration { - public let fields: [AST.VariableDeclarationStatement] - public let identifier: AST.Identifier - public init(_ id: AST.Identifier, _ fields: [AST.VariableDeclarationStatement]) { + public let fields: [CST.VariableDeclarationStatement] + public let identifier: CST.Identifier + public init(_ id: CST.Identifier, _ fields: [CST.VariableDeclarationStatement]) { self.identifier = id self.fields = fields } } - public struct Instantiation: AnStatement { - public let name: AST.Identifier - public var tipe: AST.Identifier - public let arguments: AST.ArgumentList + public struct Instantiation: Statement { + public let name: CST.Identifier + public var tipe: CST.Identifier + public let arguments: CST.ArgumentList public init( - named name: AST.Identifier, withType tipe: AST.Identifier, - withArguments arguments: AST.ArgumentList + named name: CST.Identifier, withType tipe: CST.Identifier, + withArguments arguments: CST.ArgumentList ) { self.name = name self.arguments = arguments @@ -319,7 +326,7 @@ public struct AST { } } - public struct ExpressionStatement: AnStatement { + public struct ExpressionStatement: Statement { public let expression: AnExpression public init(_ expr: AnExpression) { @@ -347,10 +354,10 @@ public struct AST { } public struct SelectCaseExpression: AnExpression { - public let key: AST.KeysetExpression - public let next_state_identifier: AST.Identifier + public let key: CST.KeysetExpression + public let next_state_identifier: CST.Identifier - public init(withKey key: AST.KeysetExpression, withNextState next_state_id: AST.Identifier) { + public init(withKey key: CST.KeysetExpression, withNextState next_state_id: CST.Identifier) { self.key = key self.next_state_identifier = next_state_id } @@ -358,17 +365,17 @@ public struct AST { public struct SelectExpression: AnExpression { public let selector: AnExpression - public let case_expressions: [AST.SelectCaseExpression] + public let case_expressions: [CST.SelectCaseExpression] public init( withSelector selector: AnExpression, - withSelectCaseExpressions sces: [AST.SelectCaseExpression] + withSelectCaseExpressions sces: [CST.SelectCaseExpression] ) { self.selector = selector self.case_expressions = sces } - public func append_checked_sce(sce: AST.SelectCaseExpression) -> AST.SelectExpression { + public func append_checked_sce(sce: CST.SelectCaseExpression) -> CST.SelectExpression { var new_cses = self.case_expressions new_cses.append(sce) return SelectExpression( @@ -443,7 +450,7 @@ public struct AST { public struct LocalElement {} - public struct ParserAssignmentStatement: AnStatement { + public struct ParserAssignmentStatement: Statement { public let lvalue: AnExpression public let value: AnExpression @@ -458,7 +465,7 @@ public struct AST { /// A P4 Parser State public class ParserState { let name: Identifier - public let statements: [AnStatement] + public let statements: CST.Statements? public var description: String { return "Parser State named \(self.name)" @@ -468,12 +475,12 @@ public struct AST { return self.name } - public func getStatements() -> [AnStatement] { + public func getStatements() -> CST.Statements? { return self.statements } /// Construct a ParserState - public init(_ name: Identifier, _ statements: [AnStatement] = Array()) { + public init(_ name: Identifier, _ statements: CST.Statements? = .none) { self.name = name self.statements = statements } @@ -489,7 +496,7 @@ public struct AST { public init( name: Identifier, withNextStateIdentifier next_state_id: Identifier, - withStatements stmts: [AnStatement] = Array(), + withStatements stmts: CST.Statements? = .none ) { self.next_state_identifier = next_state_id super.init(name, stmts) @@ -499,7 +506,7 @@ public struct AST { public class ParserStateNoTransition: ParserState, AnState { /// Construct a ParserState public init( - name: Identifier, withStatements stmts: [AnStatement] = Array(), + name: Identifier, withStatements stmts: CST.Statements? = .none ) { super.init(name, stmts) } @@ -511,7 +518,7 @@ public struct AST { public init( name: Identifier, withTransitionExpression te: SelectExpression, - withStatements stmts: [AnStatement] = Array() + withStatements stmts: CST.Statements? = .none ) { self.te = te super.init(name, stmts) @@ -572,11 +579,11 @@ public struct AST { } public struct Parameter: CustomStringConvertible { - public var name: AST.Identifier - public var type: AST.Tipe + public var name: CST.Identifier + public var type: CST.Tipe public init( - identifier: Identifier, withType type: AST.Tipe + identifier: Identifier, withType type: CST.Tipe ) { self.name = identifier self.type = type @@ -589,18 +596,18 @@ public struct AST { } public struct ParameterList: CustomStringConvertible { - public var parameters: [AST.Parameter] + public var parameters: [CST.Parameter] public init() { self.parameters = Array() } - public init(_ parameters: [AST.Parameter]) { + public init(_ parameters: [CST.Parameter]) { self.parameters = parameters } - public func addParameter(_ parameter: AST.Parameter) -> AST.ParameterList { - return AST.ParameterList(self.parameters + [parameter]) + public func addParameter(_ parameter: CST.Parameter) -> CST.ParameterList { + return CST.ParameterList(self.parameters + [parameter]) } public var description: String { @@ -612,57 +619,57 @@ public struct AST { } public struct ArgumentList { - public let arguments: [AST.Argument] + public let arguments: [CST.Argument] - public init(_ arguments: [AST.Argument] = []) { + public init(_ arguments: [CST.Argument] = []) { self.arguments = arguments } - public func addArgument(_ argument: AST.Argument) -> AST.ArgumentList { + public func addArgument(_ argument: CST.Argument) -> CST.ArgumentList { return ArgumentList(self.arguments + [argument]) } } public struct Argument { public let index: Int - public let argument: AST.AnExpression + public let argument: CST.AnExpression - public init(_ argument: AST.AnExpression, atIndex index: Int) { + public init(_ argument: CST.AnExpression, atIndex index: Int) { self.argument = argument self.index = index } } public struct Program { - public var statements: [AnStatement] - public init(_ stmts: [AnStatement] = Array()) { + public var statements: Statements + public init(_ stmts: Statements = Statements([])) { self.statements = stmts } } } -public struct ASTCompilerContext { - public let lexical_context_name: AST.Identifier? - public let lexical_context_statements: [AST.AnStatement]? +public struct CSTCompilerContext { + public let lexical_context_name: CST.Identifier? + public let lexical_context_statements: CST.Statements? public let extern_context: Bool public init( - _ name: AST.Identifier? = .none, _ stmts: [AST.AnStatement]? = .none, _ extern: Bool = false + _ name: CST.Identifier? = .none, _ stmts: CST.Statements? = .none, _ extern: Bool = false ) { self.lexical_context_name = name self.lexical_context_statements = stmts self.extern_context = extern } - public func update(withContextName cn: AST.Identifier?) -> ASTCompilerContext { - return ASTCompilerContext(cn, self.lexical_context_statements, self.extern_context) + public func update(withContextName cn: CST.Identifier?) -> CSTCompilerContext { + return CSTCompilerContext(cn, self.lexical_context_statements, self.extern_context) } - public func update(withContextStatements stmts: [AST.AnStatement]?) -> ASTCompilerContext { - return ASTCompilerContext(self.lexical_context_name, stmts, self.extern_context) + public func update(withContextStatements stmts: CST.Statements?) -> CSTCompilerContext { + return CSTCompilerContext(self.lexical_context_name, stmts, self.extern_context) } - public func update(withExtern extern: Bool) -> ASTCompilerContext { - return ASTCompilerContext(self.lexical_context_name, self.lexical_context_statements, extern) + public func update(withExtern extern: Bool) -> CSTCompilerContext { + return CSTCompilerContext(self.lexical_context_name, self.lexical_context_statements, extern) } } diff --git a/Sources/P4Compiler/Common.swift b/Sources/P4Parser/Common.swift similarity index 85% rename from Sources/P4Compiler/Common.swift rename to Sources/P4Parser/Common.swift index b7df1f5..3a8689a 100644 --- a/Sources/P4Compiler/Common.swift +++ b/Sources/P4Parser/Common.swift @@ -26,6 +26,6 @@ extension Node { } } -@attached(member, names: named(CompileStatement)) -public macro deriveCompilableStatement() = - #externalMacro(module: "Macros", type: "DeriveCompilableStatement") +@attached(member, names: named(ParseStatement)) +public macro deriveParsableStatement() = + #externalMacro(module: "Macros", type: "DeriveParsableStatement") diff --git a/Sources/P4Compiler/Compiler.swift b/Sources/P4Parser/Compiler.swift similarity index 63% rename from Sources/P4Compiler/Compiler.swift rename to Sources/P4Parser/Compiler.swift index 45b30cd..606d1f9 100644 --- a/Sources/P4Compiler/Compiler.swift +++ b/Sources/P4Parser/Compiler.swift @@ -33,3 +33,25 @@ public func ConfigureP4Parser() -> Result { return .Ok(p) } + +public func compile(_ s: String) -> Result { + let maybe_parser = ConfigureP4Parser() + guard case .Ok(let p) = maybe_parser else { + return .Error(maybe_parser.error()!) + } + + let result = p.parse(s) + guard let tree = result, + !tree.isError(lang: p4lang), + !tree.containsMissing(lang: p4lang) + else { + return Result.Error(Error(withMessage: "Could not parse the P4 program")) + } + + guard let root = tree.rootNode else { + return Result.Error(Error(withMessage: "No P4 program compiled")) + } + + let compilation_context = CSTCompilerContext() + return CST.Program.Parse(node: root, withContext: compilation_context) +} diff --git a/Sources/P4Compiler/Feedback.swift b/Sources/P4Parser/Feedback.swift similarity index 100% rename from Sources/P4Compiler/Feedback.swift rename to Sources/P4Parser/Feedback.swift diff --git a/Sources/P4Compiler/Declarations.swift b/Sources/P4Parser/Parsers/Declarations.swift similarity index 71% rename from Sources/P4Compiler/Declarations.swift rename to Sources/P4Parser/Parsers/Declarations.swift index d52f342..2ea3b4a 100644 --- a/Sources/P4Compiler/Declarations.swift +++ b/Sources/P4Parser/Parsers/Declarations.swift @@ -20,11 +20,11 @@ import SwiftTreeSitter import TreeSitterExtensions import TreeSitterP4 -extension AST.Declaration: Compilable { - public typealias C = AST.AnDeclaration - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Declaration: Parsable { + public typealias C = CST.AnDeclaration + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { // Be kind to our user -- if we are at a declaration node, dive into it! let declaration_node = @@ -34,13 +34,13 @@ extension AST.Declaration: Compilable { node } - let declaration_compilers: [String: any Compilable.Type] = [ - "function_declaration": AST.FunctionDeclaration.self, - "control_declaration": AST.Control.self, + let declaration_compilers: [String: any Parsable.Type] = [ + "function_declaration": CST.FunctionDeclaration.self, + "control_declaration": CST.Control.self, //"type_declaration": AST.P4Struct.self, - "parserDeclaration": AST.Parser.self, + "parserDeclaration": CST.Parser.self, /// ASSUME: Type declarations are struct declarations. - "extern_declaration": AST.ExternDeclaration.self, + "extern_declaration": CST.ExternDeclaration.self, ] guard let declaration_compiler = declaration_compilers[declaration_node.nodeType!] else { @@ -50,23 +50,23 @@ extension AST.Declaration: Compilable { withError: "Could not find parser for declaration \(declaration_node.nodeType!)")) } - return declaration_compiler.Compile(node: declaration_node, withContext: context).map { + return declaration_compiler.Parse(node: declaration_node, withContext: context).map { result in .Ok(result) } } } -@deriveCompilableStatement -extension AST.Declaration: CompilableStatement {} +@deriveParsableStatement +extension CST.Declaration: ParsableStatement {} -extension AST.FunctionDeclaration: Compilable { - public typealias C = AST.AnDeclaration - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Common.Result { +extension CST.FunctionDeclaration: Parsable { + public typealias C = CST.AnDeclaration + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Common.Result { let function_declaration_node = node - #RequireNodeType( + #RequireNodeType( node: function_declaration_node, type: "function_declaration", nice_type_name: "Function Declaration") @@ -75,12 +75,12 @@ extension AST.FunctionDeclaration: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: function_declaration_node.toSourceLocation(), withError: "Missing function declaration component"))) - let maybe_function_type = AST.Types.CompileType(type: current_node!, withContext: context) + let maybe_function_type = CST.Types.ParseType(type: current_node!, withContext: context) guard case .Ok(let function_type) = maybe_function_type else { return .Error(maybe_function_type.error()!) } @@ -88,12 +88,12 @@ extension AST.FunctionDeclaration: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: function_declaration_node.toSourceLocation(), withError: "Missing function declaration component"))) - let maybe_function_name = AST.Identifier.CompileExpression( + let maybe_function_name = CST.Identifier.ParseExpression( node: current_node!, withContext: context) guard case .Ok(let function_name) = maybe_function_name else { return .Error(maybe_function_name.error()!) @@ -102,23 +102,23 @@ extension AST.FunctionDeclaration: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: function_declaration_node.toSourceLocation(), withError: "Missing function declaration component"))) - let maybe_function_parameters = AST.ParameterList.Compile( + let maybe_function_parameters = CST.ParameterList.Parse( node: current_node!, withContext: context) guard case .Ok(let function_parameters) = maybe_function_parameters else { return .Error(maybe_function_parameters.error()!) } - var function_body: AST.BlockStatement? = .none + var function_body: CST.BlockStatement? = .none walker.next() if let body = walker.getNext() { - let maybe_function_body = AST.BlockStatement.Compile(node: body, withContext: context) + let maybe_function_body = CST.BlockStatement.Parse(node: body, withContext: context) guard case .Ok(let parsed_function_body) = maybe_function_body else { return .Error(maybe_function_body.error()!) @@ -136,8 +136,8 @@ extension AST.FunctionDeclaration: Compilable { } } - let function_declaration = AST.FunctionDeclaration( - named: function_name as! AST.Identifier, ofType: function_type, + let function_declaration = CST.FunctionDeclaration( + named: function_name as! CST.Identifier, ofType: function_type, withParameters: function_parameters, withBody: function_body) @@ -151,16 +151,16 @@ extension AST.FunctionDeclaration: Compilable { } } -extension AST.StructDeclaration: Compilable { - public typealias C = AST.StructDeclaration - static public func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.StructDeclaration: Parsable { + public typealias C = CST.StructDeclaration + static public func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { let struct_declaration_node = node.child(at: 0)! var walker = Walker(node: struct_declaration_node) var currentNode: Node? = .none - #RequireNodeType>( + #RequireNodeType>( node: struct_declaration_node, type: "struct_declaration", nice_type_name: "struct declaration") @@ -168,13 +168,13 @@ extension AST.StructDeclaration: Compilable { walker.next() #MustOr( result: currentNode, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: struct_declaration_node.toSourceLocation(), withError: "Missing function declaration component"))) // The name of the struct type. - let maybe_struct_identifier = AST.Identifier.CompileExpression( + let maybe_struct_identifier = CST.Identifier.ParseExpression( node: currentNode!, withContext: context) guard case Result.Ok(let struct_identifier) = maybe_struct_identifier else { return Result.Error(maybe_struct_identifier.error()!) @@ -185,23 +185,23 @@ extension AST.StructDeclaration: Compilable { walker.next() #MustOr( result: currentNode, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: struct_declaration_node.toSourceLocation(), withError: "Missing function declaration component"))) // If there are no fields, it will be a "}" if currentNode!.nodeType == "}" { - let struc = AST.StructDeclaration(struct_identifier as! AST.Identifier, []) + let struc = CST.StructDeclaration(struct_identifier as! CST.Identifier, []) return Result.Ok(struc) } var parse_errs: (any Errorable)? = .none - var parsed_fields: [AST.VariableDeclarationStatement] = Array() + var parsed_fields: [CST.VariableDeclarationStatement] = Array() if currentNode!.nodeType == "struct_declaration_fields" { currentNode!.enumerateNamedChildren { declaration_field in - switch AST.VariableDeclarationStatement.Compile( + switch CST.VariableDeclarationStatement.Parse( node: declaration_field, withContext: context) { case .Ok(let variable_declaration): @@ -221,25 +221,25 @@ extension AST.StructDeclaration: Compilable { return .Error(ErrorWithLabel("Error(s) parsing select cases", parse_errs)) } - let declared_struct = AST.StructDeclaration(struct_identifier as! AST.Identifier, parsed_fields) + let declared_struct = CST.StructDeclaration(struct_identifier as! CST.Identifier, parsed_fields) return .Ok(declared_struct) } } -extension AST.Parser: Compilable { - public typealias C = AST.AnDeclaration - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Parser: Parsable { + public typealias C = CST.AnDeclaration + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { let parser_node = node - #RequireNodeType>( + #RequireNodeType>( node: parser_node, type: "parserDeclaration", nice_type_name: "parser declaration") var walker = Walker(node: parser_node) var current_node: Node? = .none #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: parser_node.toSourceLocation(), withError: "Missing elements of parser declaration"))) @@ -252,10 +252,10 @@ extension AST.Parser: Compilable { } let type_node = current_node - var parser_name: AST.Identifier? = .none + var parser_name: CST.Identifier? = .none /// TODO: Handle parser parameter lists. - var parameter_list = AST.ParameterList() + var parameter_list = CST.ParameterList() do { var type_node_walker = Walker(node: type_node!) @@ -263,7 +263,7 @@ extension AST.Parser: Compilable { #MustOr( result: type_node_child, thing: type_node_walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: parser_node.toSourceLocation(), withError: "Missing elements of parser type in parser declaration"))) @@ -279,13 +279,13 @@ extension AST.Parser: Compilable { type_node_walker.next() #MustOr( result: type_node_child, thing: type_node_walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: type_node_child!.toSourceLocation(), withError: "Missing name in parser type declaration"))) - switch AST.Identifier.CompileExpression(node: type_node_child!, withContext: context) { - case .Ok(let id): parser_name = (id as! AST.Identifier) + switch CST.Identifier.ParseExpression(node: type_node_child!, withContext: context) { + case .Ok(let id): parser_name = (id as! CST.Identifier) case .Error(let e): return .Error(e) } @@ -293,12 +293,12 @@ extension AST.Parser: Compilable { type_node_walker.next() #MustOr( result: type_node_child, thing: type_node_walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: type_node_child!.toSourceLocation(), withError: "Missing parser parameters"))) - switch AST.ParameterList.Compile(node: type_node_child!, withContext: context) { + switch CST.ParameterList.Parse(node: type_node_child!, withContext: context) { case .Ok(let parsed_parameter_list): parameter_list = parsed_parameter_list case .Error(let e): @@ -309,7 +309,7 @@ extension AST.Parser: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: parser_node.toSourceLocation(), withError: "Missing parser declaration component"))) @@ -317,7 +317,7 @@ extension AST.Parser: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: parser_node.toSourceLocation(), withError: "Missing elements of parser declaration"))) @@ -332,7 +332,7 @@ extension AST.Parser: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: parser_node.toSourceLocation(), withError: "Missing body of parser declaration"))) @@ -341,24 +341,50 @@ extension AST.Parser: Compilable { return .Error(Error(withMessage: "Missing parser states in parser declaration")) } - /// TODO: Handle extern parsers. - switch SpecialCompilers.CompileParserBody( - withName: parser_name!, withParameters: parameter_list, node: current_node!, - withContext: context) - { - case Result.Ok(let parser): return .Ok(parser) - case Result.Error(let error): return .Error(error) + var parser = CST.Parser(withName: parser_name!, withParameters: parameter_list) + + // Build a state from each one listed. + var errors: (any Errorable)? = .none + + /// TODO: Assert that there is only one. + current_node!.enumerateNamedChildren { parser_state in + if parser_state.nodeType != "parserState" { + return + } + + // Parse a state in a nested scope. + switch CST.ParserState.Parse( + node: parser_state, + withContext: context) + { + case Result.Ok(let state): + // All states are instances inside the parser. + parser.states = parser.states.append(state: state) + case Result.Error(let e): + errors = + if let errors = errors { + errors.append(error: e) + } else { + e + } + } } + + if let errors = errors { + return .Error(errors) + } + + return .Ok(parser) } } -extension AST.Control: Compilable { - public typealias C = AST.AnDeclaration - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Common.Result { +extension CST.Control: Parsable { + public typealias C = CST.AnDeclaration + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Common.Result { - #RequireNodeType>( + #RequireNodeType>( node: node, type: "control_declaration", nice_type_name: "control declaration") var walker = Walker(node: node) @@ -367,13 +393,13 @@ extension AST.Control: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing control declaration component"))) guard - case .Ok(let control_name) = AST.Identifier.CompileExpression( + case .Ok(let control_name) = CST.Identifier.ParseExpression( node: current_node!, withContext: context) else { return Result.Error( @@ -383,12 +409,12 @@ extension AST.Control: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing control declaration component"))) - let maybe_control_parameters = AST.ParameterList.Compile( + let maybe_control_parameters = CST.ParameterList.Parse( node: current_node!, withContext: context) guard case .Ok(let control_parameters) = maybe_control_parameters else { @@ -400,21 +426,21 @@ extension AST.Control: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing control declaration component"))) - var actions: [AST.Action] = Array() - var tables: [AST.Table] = Array() - var apply: AST.ApplyStatement? = .none + var actions: [CST.Action] = Array() + var tables: [CST.Table] = Array() + var apply: CST.ApplyStatement? = .none // Because the final child // is the '}'. // \/\/ let body_parse_results = walker.overUntil(n: node.childCount - 1) { current_node in if current_node.nodeType == "action_declaration" { - let maybe_action_declaration = AST.Action.Compile( + let maybe_action_declaration = CST.Action.Parse( node: current_node, withContext: context) guard case .Ok(let action_declaration) = maybe_action_declaration @@ -423,7 +449,7 @@ extension AST.Control: Compilable { } actions.append(action_declaration) } else if current_node.nodeType == "table_declaration" { - let maybe_table_declaration = AST.Table.Compile( + let maybe_table_declaration = CST.Table.Parse( node: current_node, withContext: context) guard case .Ok(let table_declaration) = maybe_table_declaration @@ -433,7 +459,7 @@ extension AST.Control: Compilable { tables.append(table_declaration) } else if current_node.nodeType == "apply_statement" { // When we see an apply, that is it for the actions and the tables. - let maybe_apply_statement = AST.ApplyStatement.Compile( + let maybe_apply_statement = CST.ApplyStatement.Parse( node: current_node, withContext: context) guard case .Ok(let apply_statement) = maybe_apply_statement @@ -478,18 +504,18 @@ extension AST.Control: Compilable { } return .Ok( - AST.Control( - named: control_name as! AST.Identifier, withParameters: control_parameters, + CST.Control( + named: control_name as! CST.Identifier, withParameters: control_parameters, withTable: tables[0], - withActions: AST.Actions(withActions: actions), withApply: apply)) + withActions: CST.Actions(withActions: actions), withApply: apply)) } } -extension AST.Action: Compilable { - public typealias C = AST.Action - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Action: Parsable { + public typealias C = CST.Action + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { #RequireNodeType( node: node, type: "action_declaration", nice_type_name: "Action Declaration") @@ -501,14 +527,14 @@ extension AST.Action: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing action declaration component" )) ) guard - case .Ok(let action_name) = AST.Identifier.CompileExpression( + case .Ok(let action_name) = CST.Identifier.ParseExpression( node: current_node!, withContext: context) else { return Result.Error( @@ -518,13 +544,13 @@ extension AST.Action: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing action declaration component" )) ) - let maybe_action_parameters = AST.ParameterList.Compile( + let maybe_action_parameters = CST.ParameterList.Parse( node: current_node!, withContext: context) guard case .Ok(let action_parameters) = maybe_action_parameters else { @@ -545,13 +571,13 @@ extension AST.Action: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing action declaration component" )) ) - let maybe_action_body = AST.BlockStatement.Compile( + let maybe_action_body = CST.BlockStatement.Parse( node: current_node!, withContext: context) guard case .Ok(let action_body) = maybe_action_body else { return .Error(maybe_action_body.error()!) @@ -560,19 +586,19 @@ extension AST.Action: Compilable { /// TODO: Actions cannot contain switches! return .Ok( - AST.Action( - named: action_name as! AST.Identifier, withParameters: action_parameters, + CST.Action( + named: action_name as! CST.Identifier, withParameters: action_parameters, withBody: action_body)) } } -extension AST.TableKeyEntry: Compilable { - public typealias C = AST.TableKeyEntry - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.TableKeyEntry: Parsable { + public typealias C = CST.TableKeyEntry + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "table_key_entry", nice_type_name: "Table Key Entry") var walker = Walker(node: node) @@ -581,12 +607,12 @@ extension AST.TableKeyEntry: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table key entry declaration component"))) - let maybe_keyset_expression = AST.KeysetExpression.CompileExpression( + let maybe_keyset_expression = CST.KeysetExpression.ParseExpression( node: current_node!, withContext: context) guard case .Ok(let keyset_expression) = maybe_keyset_expression else { return Result.Error(maybe_keyset_expression.error()!) @@ -597,31 +623,31 @@ extension AST.TableKeyEntry: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table key entry declaration component"))) - let maybe_match_type = AST.TableKeyMatchType.Compile( + let maybe_match_type = CST.TableKeyMatchType.Parse( node: current_node!, withContext: context) guard case .Ok(let match_type) = maybe_match_type else { return .Error(maybe_match_type.error()!) } - return .Ok(AST.TableKeyEntry(keyset_expression as! AST.KeysetExpression, match_type)) + return .Ok(CST.TableKeyEntry(keyset_expression as! CST.KeysetExpression, match_type)) } } -extension AST.TableKeyMatchType: Compilable { - public typealias C = AST.TableKeyMatchType - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.TableKeyMatchType: Parsable { + public typealias C = CST.TableKeyMatchType + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "table_key_match_type", nice_type_name: "Table Key Match Type") if node.text! == "exact" { - return .Ok(AST.TableKeyMatchType.Exact) + return .Ok(CST.TableKeyMatchType.Exact) } return .Error( ErrorWithLocation( @@ -630,12 +656,12 @@ extension AST.TableKeyMatchType: Compilable { } } -extension AST.TableKeys: Compilable { - public typealias C = AST.TableKeys - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.TableKeys: Parsable { + public typealias C = CST.TableKeys + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "table_keys", nice_type_name: "Table Keys") var walker = Walker(node: node) @@ -650,14 +676,14 @@ extension AST.TableKeys: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table keys declaration component in control declaration")) ) let (keys, errors) = walker.try_map(n: node.childCount - 1, onlyNamed: true) { current_node in - return switch AST.TableKeyEntry.Compile(node: current_node, withContext: context) { + return switch CST.TableKeyEntry.Parse(node: current_node, withContext: context) { case .Ok(let keyset_expression): .Ok(keyset_expression) case .Error(let e): .Error(e) } @@ -673,16 +699,16 @@ extension AST.TableKeys: Compilable { }.joined(separator: ";")))) } - return .Ok(AST.TableKeys(withEntries: keys)) + return .Ok(CST.TableKeys(withEntries: keys)) } } -extension AST.TableActionsProperty: Compilable { - public typealias C = AST.TableActionsProperty - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.TableActionsProperty: Parsable { + public typealias C = CST.TableActionsProperty + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "table_actions", nice_type_name: "Table Actions") var walker = Walker(node: node) @@ -697,7 +723,7 @@ extension AST.TableActionsProperty: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table actions declaration component in control declaration")) @@ -705,9 +731,9 @@ extension AST.TableActionsProperty: Compilable { let (actions, errors) = walker.try_map(n: node.childCount - 1, onlyNamed: true) { current_node in - switch AST.Identifier.CompileExpression(node: current_node, withContext: context) { + switch CST.Identifier.ParseExpression(node: current_node, withContext: context) { case .Ok(let listed_action): - return .Ok(listed_action as! AST.Identifier) + return .Ok(listed_action as! CST.Identifier) case .Error(let e): return .Error(e) } } @@ -722,31 +748,31 @@ extension AST.TableActionsProperty: Compilable { }.joined(separator: ";")))) } - return .Ok(AST.TableActionsProperty(actions)) + return .Ok(CST.TableActionsProperty(actions)) } } -extension AST.TablePropertyList: Compilable { - public typealias C = AST.TablePropertyList - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.TablePropertyList: Parsable { + public typealias C = CST.TablePropertyList + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "table_property_list", nice_type_name: "Table Property List") - var keys: [AST.TableKeys] = Array() - var actions: [AST.TableActionsProperty] = Array() + var keys: [CST.TableKeys] = Array() + var actions: [CST.TableActionsProperty] = Array() var errors: [any Errorable] = Array() node.enumerateNamedChildren { child in if child.nodeType == "table_keys" { - switch AST.TableKeys.Compile(node: child, withContext: context) { + switch CST.TableKeys.Parse(node: child, withContext: context) { case .Ok(let table_key): keys.append(table_key) case .Error(let e): errors.append(e) } } else if child.nodeType == "table_actions" { - switch AST.TableActionsProperty.Compile(node: child, withContext: context) { + switch CST.TableActionsProperty.Parse(node: child, withContext: context) { case .Ok(let table_action_property): actions.append(table_action_property) case .Error(let e): errors.append(e) @@ -787,22 +813,22 @@ extension AST.TablePropertyList: Compilable { withError: "More than one actions in table property list")) } if actions.isEmpty { - actions.append(AST.TableActionsProperty()) + actions.append(CST.TableActionsProperty()) } - return .Ok(AST.TablePropertyList(withActions: actions[0], withKeys: keys[0])) + return .Ok(CST.TablePropertyList(withActions: actions[0], withKeys: keys[0])) } } -extension AST.Table: Compilable { - public typealias C = AST.Table - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Table: Parsable { + public typealias C = CST.Table + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let table_declaration_node = node - #RequireNodeType( + #RequireNodeType( node: table_declaration_node, type: "table_declaration", nice_type_name: "Table Declaration") var walker = Walker(node: table_declaration_node) @@ -812,13 +838,13 @@ extension AST.Table: Compilable { walker.next() // Skip the XXX? #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table declaration component") )) guard - case .Ok(let table_name) = AST.Identifier.CompileExpression( + case .Ok(let table_name) = CST.Identifier.ParseExpression( node: current_node!, withContext: context) else { return Result.Error( @@ -830,44 +856,44 @@ extension AST.Table: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing table declaration component") )) - let maybe_table_property_list = AST.TablePropertyList.Compile( + let maybe_table_property_list = CST.TablePropertyList.Parse( node: current_node!, withContext: context) guard case .Ok(let table_property_list) = maybe_table_property_list else { return Result.Error(maybe_table_property_list.error()!) } return .Ok( - AST.Table(withName: table_name as! AST.Identifier, withPropertyList: table_property_list)) + CST.Table(withName: table_name as! CST.Identifier, withPropertyList: table_property_list)) } } -extension AST.ExternDeclaration: Compilable { - public typealias C = AST.AnDeclaration - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ExternDeclaration: Parsable { + public typealias C = CST.AnDeclaration + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let extern_declaration_node = node - #RequireNodeType( + #RequireNodeType( node: extern_declaration_node, type: "extern_declaration", nice_type_name: "Extern Declaration") let declaration_node = extern_declaration_node.child(at: 1)! - #RequireNodeType( + #RequireNodeType( node: declaration_node, type: "declaration", nice_type_name: "Declaration") let declarationed_node = declaration_node.child(at: 0)! - let maybe_declared = AST.Declaration.Compile( + let maybe_declared = CST.Declaration.Parse( node: declarationed_node, withContext: context.update(withExtern: true)) guard case .Ok(let declared) = maybe_declared else { return .Error(maybe_declared.error()!) } - let extern_declaration = AST.ExternDeclaration(declared) + let extern_declaration = CST.ExternDeclaration(declared) return .Ok( extern_declaration, @@ -876,25 +902,25 @@ extension AST.ExternDeclaration: Compilable { } func parameter_list_compiler( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext -) -> Common.Result { + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext +) -> Common.Result { var walker = Walker(node: node) var current_node: Node? = .none if node.text == ")" { // There are no parameters! - return Result.Ok(AST.ParameterList([])) + return Result.Ok(CST.ParameterList([])) } - #RequireNodeType( + #RequireNodeType( node: node, type: "parameter_list", nice_type_name: "Parameter List") - var parameters: AST.ParameterList = AST.ParameterList([]) + var parameters: CST.ParameterList = CST.ParameterList([]) #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter list component"))) @@ -909,7 +935,7 @@ func parameter_list_compiler( #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter list component"))) @@ -925,26 +951,26 @@ func parameter_list_compiler( #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter list component"))) // Otherwise, there should be one parameter left! - switch AST.Parameter.Compile(node: current_node!, withContext: context) { + switch CST.Parameter.Parse(node: current_node!, withContext: context) { case .Ok(let parsed_parameter): return Result.Ok(parameters.addParameter(parsed_parameter)) case .Error(let e): return Result.Error(e) } } -extension AST.ParameterList: Compilable { - public typealias C = AST.ParameterList - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ParameterList: Parsable { + public typealias C = CST.ParameterList + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let parameter_node = node - #RequireNodeType( + #RequireNodeType( node: parameter_node, type: "parameters", nice_type_name: "Parameters") var walker = Walker(node: parameter_node) @@ -953,7 +979,7 @@ extension AST.ParameterList: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing '(' in parameter list component"))) @@ -961,7 +987,7 @@ extension AST.ParameterList: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter list component"))) @@ -969,10 +995,10 @@ extension AST.ParameterList: Compilable { } } -extension Direction: Compilable { +extension Direction: Parsable { public typealias C = Direction - public static func Compile( - node: Node, withContext context: ASTCompilerContext + public static func Parse( + node: Node, withContext context: CSTCompilerContext ) -> Result { let direction_node = node #RequireNodeType( @@ -994,13 +1020,13 @@ extension Direction: Compilable { } } -extension AST.Parameter: Compilable { - public typealias C = AST.Parameter - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Parameter: Parsable { + public typealias C = CST.Parameter + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "parameter", nice_type_name: "parameter") var walker = Walker(node: node) @@ -1008,7 +1034,7 @@ extension AST.Parameter: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter declaration component"))) @@ -1024,7 +1050,7 @@ extension AST.Parameter: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter declaration component"))) @@ -1033,7 +1059,7 @@ extension AST.Parameter: Compilable { // Direction? if current_node!.nodeType == "direction" { - let maybe_parsed_direction = Direction.Compile(node: current_node!, withContext: context) + let maybe_parsed_direction = Direction.Parse(node: current_node!, withContext: context) guard case .Ok(let parsed_direction) = maybe_parsed_direction else { return .Error(maybe_parsed_direction.error()!) } @@ -1044,7 +1070,7 @@ extension AST.Parameter: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter declaration component"))) @@ -1057,7 +1083,7 @@ extension AST.Parameter: Compilable { } guard - case .Ok(let parameter_type) = AST.Types.CompileType( + case .Ok(let parameter_type) = CST.Types.ParseType( type: current_node!, withContext: context) else { return Result.Error( @@ -1067,7 +1093,7 @@ extension AST.Parameter: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing parameter declaration component"))) @@ -1080,7 +1106,7 @@ extension AST.Parameter: Compilable { } guard - case .Ok(let parameter_name) = AST.Identifier.CompileExpression( + case .Ok(let parameter_name) = CST.Identifier.ParseExpression( node: current_node!, withContext: context) else { return Result.Error( @@ -1093,32 +1119,32 @@ extension AST.Parameter: Compilable { : parameter_type.tipe return Result.Ok( - AST.Parameter( - identifier: parameter_name as! AST.Identifier, - withType: AST.Tipe(qualified_parameter_type))) + CST.Parameter( + identifier: parameter_name as! CST.Identifier, + withType: CST.Tipe(qualified_parameter_type))) } } func argument_list_compiler( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext -) -> Common.Result { + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext +) -> Common.Result { var walker = Walker(node: node) var current_node: Node? = .none if node.text == ")" { // There are no arguments! - return Result.Ok(AST.ArgumentList([])) + return Result.Ok(CST.ArgumentList([])) } - #RequireNodeType( + #RequireNodeType( node: node, type: "argument_list", nice_type_name: "argument List") - var arguments: AST.ArgumentList = AST.ArgumentList([]) + var arguments: CST.ArgumentList = CST.ArgumentList([]) #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing argument list component"))) @@ -1135,7 +1161,7 @@ func argument_list_compiler( // We may have moved nodes, check/reset current_node. #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing argument list component"))) @@ -1151,27 +1177,27 @@ func argument_list_compiler( #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing argument list component"))) // Otherwise, there should be one argument left! - switch AST.Argument.Compile(node: current_node!, withContext: context) { + switch CST.Argument.Parse(node: current_node!, withContext: context) { case .Ok(let ce): return Result.Ok( - arguments.addArgument(AST.Argument(ce, atIndex: arguments.arguments.count + 1))) + arguments.addArgument(CST.Argument(ce, atIndex: arguments.arguments.count + 1))) case .Error(let e): return Result.Error(e) } } -extension AST.ArgumentList: Compilable { - public typealias C = AST.ArgumentList - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Common.Result { +extension CST.ArgumentList: Parsable { + public typealias C = CST.ArgumentList + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Common.Result { let argument_node = node - #RequireNodeType( + #RequireNodeType( node: argument_node, type: "arguments", nice_type_name: "arguments") var walker = Walker(node: argument_node) @@ -1179,7 +1205,7 @@ extension AST.ArgumentList: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing '(' in argument list component"))) @@ -1188,7 +1214,7 @@ extension AST.ArgumentList: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing argument list component"))) @@ -1196,18 +1222,18 @@ extension AST.ArgumentList: Compilable { } } -extension AST.Argument: Compilable { - public typealias C = AST.AnExpression - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Common.Result { +extension CST.Argument: Parsable { + public typealias C = CST.AnExpression + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Common.Result { let argument_node = node - #RequireNodeType( + #RequireNodeType( node: argument_node, type: "argument", nice_type_name: "argument") let expression_node = node.child(at: 0)! - return switch AST.Expression.Compile(node: expression_node, withContext: context) { + return switch CST.Expression.Parse(node: expression_node, withContext: context) { case .Ok(let compiled_expression): .Ok(compiled_expression) case .Error(let e): .Error(e) } diff --git a/Sources/P4Compiler/Expression.swift b/Sources/P4Parser/Parsers/Expression.swift similarity index 71% rename from Sources/P4Compiler/Expression.swift rename to Sources/P4Parser/Parsers/Expression.swift index 15347b6..9119f9b 100644 --- a/Sources/P4Compiler/Expression.swift +++ b/Sources/P4Parser/Parsers/Expression.swift @@ -19,31 +19,31 @@ import Common import SwiftTreeSitter import TreeSitterP4 -extension AST.Identifier: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Identifier: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "identifier", nice_type_name: "Identifier") /// TODO: If there is a value here, then we can make this a compile-time constant! - return .Ok(AST.Identifier(Common.Identifier(name: node.text!))) + return .Ok(CST.Identifier(Common.Identifier(name: node.text!))) } } -extension P4BooleanValue: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension P4BooleanValue: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let node = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: node, type: "booleanLiteralExpression", nice_type_name: "Boolean Literal Expression") if node.text == "false" { - return .Ok(AST.Literal(P4Value(P4BooleanValue(withValue: false)))) + return .Ok(CST.Literal(P4Value(P4BooleanValue(withValue: false)))) } else if node.text == "true" { - return .Ok(AST.Literal(P4Value(P4BooleanValue(withValue: true)))) + return .Ok(CST.Literal(P4Value(P4BooleanValue(withValue: true)))) } return .Error( @@ -53,13 +53,13 @@ extension P4BooleanValue: CompilableExpression { } } -extension P4IntValue: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension P4IntValue: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let node = node.child(at: 0)! - #RequireNodesType( + #RequireNodesType( nodes: node, type: ["integer", "integer_elaborated"], nice_type_names: ["Integer", "Elaborated Integer"]) @@ -93,7 +93,7 @@ extension P4IntValue: CompilableExpression { } if let parsed_int = Int(value_source) { - return .Ok(AST.Literal(P4Value(P4IntValue(withValue: parsed_int, andWidth: bit_width)))) + return .Ok(CST.Literal(P4Value(P4IntValue(withValue: parsed_int, andWidth: bit_width)))) } else { return .Error( ErrorWithLocation( @@ -103,43 +103,43 @@ extension P4IntValue: CompilableExpression { } } -extension P4StringValue: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext scopes: ASTCompilerContext - ) -> Result { +extension P4StringValue: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext scopes: CSTCompilerContext + ) -> Result { let node = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: node, type: "string_literal", nice_type_name: "String Literal") - return .Ok(AST.Literal(P4Value(P4StringValue(withValue: node.text!)))) + return .Ok(CST.Literal(P4Value(P4StringValue(withValue: node.text!)))) } } -extension AST.Expression: Compilable { - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.Expression: Parsable { + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "expression", nice_type_name: "expression") let expression_node = node.child(at: 0)! - #RequireNodesType( + #RequireNodesType( nodes: expression_node, type: ["grouped_expression", "simple_expression"], nice_type_names: ["grouped expression", "simple expression"]) // If this is a grouped expression, recurse! if expression_node.nodeType == "grouped_expression" { - return AST.Expression.Compile(node: expression_node.child(at: 1)!, withContext: context) + return CST.Expression.Parse(node: expression_node.child(at: 1)!, withContext: context) } - let expression_parsers: [CompilableExpression.Type] = [ - P4BooleanValue.self, P4StringValue.self, P4IntValue.self, AST.Identifier.self, - AST.BinaryOperatorExpression.self, AST.ArrayAccessExpression.self, - AST.FieldAccessExpression.self, - AST.FunctionCall.self, + let expression_parsers: [ParsableExpression.Type] = [ + P4BooleanValue.self, P4StringValue.self, P4IntValue.self, CST.Identifier.self, + CST.BinaryOperatorExpression.self, CST.ArrayAccessExpression.self, + CST.FieldAccessExpression.self, + CST.FunctionCall.self, ] for candidate_expression_parser in expression_parsers { - switch candidate_expression_parser.CompileExpression( + switch candidate_expression_parser.ParseExpression( node: expression_node, withContext: context) { case .Ok(let parsed): return .Ok(parsed) @@ -151,37 +151,37 @@ extension AST.Expression: Compilable { } } -extension AST.KeysetExpression: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.KeysetExpression: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let keyset_expression_node = node.child(at: 0)! - #RequireNodesType( + #RequireNodesType( nodes: keyset_expression_node, type: ["expression", "default_keyset"], nice_type_names: ["expression", "default keyset"]) // If there is a default keyset, that's easy! if keyset_expression_node.nodeType == "default_keyset" { - return .Ok(AST.KeysetExpression.Default) + return .Ok(CST.KeysetExpression.Default) } // Compile the expression: - let maybe_compiled_set_expression = AST.Expression.Compile( + let maybe_compiled_set_expression = CST.Expression.Parse( node: keyset_expression_node, withContext: context) guard case .Ok(let compiled_expression) = maybe_compiled_set_expression else { return .Error(maybe_compiled_set_expression.error()!) } - return .Ok(AST.KeysetExpression.Value(compiled_expression)) + return .Ok(CST.KeysetExpression.Value(compiled_expression)) } } -extension AST.SelectExpression: CompilableExpression { - public static func CompileExpression( - node: Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.SelectExpression: ParsableExpression { + public static func ParseExpression( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "selectExpression", nice_type_name: "parser select expression") guard let selector_node = node.child(at: 2), @@ -201,7 +201,7 @@ extension AST.SelectExpression: CompilableExpression { withError: "Could not find select expression body")) } - let maybe_selector = AST.Expression.Compile(node: selector_node, withContext: context) + let maybe_selector = CST.Expression.Parse(node: selector_node, withContext: context) guard case .Ok(let selector) = maybe_selector else { return .Error( ErrorWithLocation( @@ -211,14 +211,14 @@ extension AST.SelectExpression: CompilableExpression { )) } - var sces: [AST.SelectCaseExpression] = Array() + var sces: [CST.SelectCaseExpression] = Array() var sces_errors: (any Errorable)? = .none select_body_node.enumerateNamedChildren { current_node in - let maybe_parsed_cse = AST.SelectCaseExpression.CompileExpression( + let maybe_parsed_cse = CST.SelectCaseExpression.ParseExpression( node: current_node, withContext: context) switch maybe_parsed_cse { - case .Ok(let parsed_cse): sces.append(parsed_cse as! AST.SelectCaseExpression) + case .Ok(let parsed_cse): sces.append(parsed_cse as! CST.SelectCaseExpression) case .Error(let e): sces_errors = if let sces_errors = sces_errors { @@ -234,17 +234,17 @@ extension AST.SelectExpression: CompilableExpression { } return .Ok( - AST.SelectExpression(withSelector: selector, withSelectCaseExpressions: sces), + CST.SelectExpression(withSelector: selector, withSelectCaseExpressions: sces), ) } } -extension AST.SelectCaseExpression: CompilableExpression { - public static func CompileExpression( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.SelectCaseExpression: ParsableExpression { + public static func ParseExpression( + node: Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "selectCase", nice_type_name: "Select Case") guard let keysetexpression_node = node.child(at: 0), @@ -259,34 +259,34 @@ extension AST.SelectCaseExpression: CompilableExpression { return Result.Error(Error(withMessage: "Missing target state in select case")) } - let maybe_parsed_keysetexpression = AST.KeysetExpression.CompileExpression( + let maybe_parsed_keysetexpression = CST.KeysetExpression.ParseExpression( node: keysetexpression_node, withContext: context) guard case Result.Ok(let maybe_keysetexpression) = maybe_parsed_keysetexpression else { return Result.Error(maybe_parsed_keysetexpression.error()!) } - let keysetexpression = maybe_keysetexpression as! AST.KeysetExpression + let keysetexpression = maybe_keysetexpression as! CST.KeysetExpression - let maybe_parsed_targetstate = AST.Identifier.CompileExpression( + let maybe_parsed_targetstate = CST.Identifier.ParseExpression( node: targetstate_node, withContext: context) guard case .Ok(let targetstate) = maybe_parsed_targetstate else { return Result.Error(maybe_parsed_targetstate.error()!) } return .Ok( - AST.SelectCaseExpression( - withKey: keysetexpression, withNextState: targetstate as! AST.Identifier) + CST.SelectCaseExpression( + withKey: keysetexpression, withNextState: targetstate as! CST.Identifier) ) } } -extension AST.BinaryOperatorExpression: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.BinaryOperatorExpression: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let expression = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: expression, type: "binaryOperatorExpression", nice_type_name: "Binary Operator Expression") let binary_operator_expression_node = expression.child(at: 0)! @@ -295,20 +295,20 @@ extension AST.BinaryOperatorExpression: CompilableExpression { var current_node: Node? = .none #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Malformed binary operator expression" ))) /// TODO: This macro cannot handle new lines in the arrays // swift-format-ignore - #RequireNodesType( + #RequireNodesType( nodes: binary_operator_expression_node, type: ["binaryEqualOperatorExpression", "binaryLessThanOperatorExpression", "binaryLessThanEqualOperatorExpression", "binaryGreaterThanOperatorExpression", "binaryGreaterThanEqualOperatorExpression", "binaryAndOperatorExpression", "binaryOrOperatorExpression", "binaryAddOperatorExpression", "binarySubtractOperatorExpression", "binaryMultiplyOperatorExpression", "binaryDivideOperatorExpression"], nice_type_names: [ "binary equal operator", "binary less than operator", "binary less than or equal to operator", "binary greater than operator", "binary greater than or equal to operator", "binary and operator", "binary or operator", "binary add operator", "binary subtract operator", "binary multiply operator", "binary divide operator"]) #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing LHS for binary operator expression"))) @@ -318,7 +318,7 @@ extension AST.BinaryOperatorExpression: CompilableExpression { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing binary operator for binary operator expression"))) @@ -326,69 +326,69 @@ extension AST.BinaryOperatorExpression: CompilableExpression { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing RHS for binary operator expression"))) let right_hand_side_raw = current_node! - let maybe_left_hand_side = AST.Expression.Compile( + let maybe_left_hand_side = CST.Expression.Parse( node: left_hand_side_raw, withContext: context) guard case Result.Ok(let left_hand_side) = maybe_left_hand_side else { return Result.Error(maybe_left_hand_side.error()!) } - let maybe_right_hand_side = AST.Expression.Compile( + let maybe_right_hand_side = CST.Expression.Parse( node: right_hand_side_raw, withContext: context) guard case Result.Ok(let right_hand_side) = maybe_right_hand_side else { return Result.Error(maybe_right_hand_side.error()!) } - let evaluators: [String: (String, P4QualifiedType, AST.BinaryOperatorExpressionType)] = [ + let evaluators: [String: (String, P4QualifiedType, CST.BinaryOperatorExpressionType)] = [ "binaryEqualOperatorExpression": ( "Binary Equal", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Eq + CST.BinaryOperatorExpressionType.Eq ), "binaryLessThanOperatorExpression": ( "Binary Less Than", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Lt + CST.BinaryOperatorExpressionType.Lt ), "binaryLessThanEqualOperatorExpression": ( "Binary Less Than Or Equal", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Lte + CST.BinaryOperatorExpressionType.Lte ), "binaryGreaterThanOperatorExpression": ( "Binary Greater Than", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Gt + CST.BinaryOperatorExpressionType.Gt ), "binaryGreaterThanEqualOperatorExpression": ( "Binary Greater Than Or Equal", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Gte + CST.BinaryOperatorExpressionType.Gte ), "binaryAndOperatorExpression": ( "Binary Or", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.And + CST.BinaryOperatorExpressionType.And ), "binaryOrOperatorExpression": ( "Binary And", P4QualifiedType(P4Boolean()), - AST.BinaryOperatorExpressionType.Or + CST.BinaryOperatorExpressionType.Or ), "binaryAddOperatorExpression": ( "Binary Add", P4QualifiedType(P4Int()), - AST.BinaryOperatorExpressionType.Add + CST.BinaryOperatorExpressionType.Add ), "binarySubtractOperatorExpression": ( "Binary Subtract", P4QualifiedType(P4Int()), - AST.BinaryOperatorExpressionType.Subtract + CST.BinaryOperatorExpressionType.Subtract ), "binaryMultiplyOperatorExpression": ( "Binary Multiply", P4QualifiedType(P4Int()), - AST.BinaryOperatorExpressionType.Multiply + CST.BinaryOperatorExpressionType.Multiply ), "binaryDivideOperatorExpression": ( "Binary Divide", P4QualifiedType(P4Int()), - AST.BinaryOperatorExpressionType.Divide + CST.BinaryOperatorExpressionType.Divide ), ] @@ -398,19 +398,19 @@ extension AST.BinaryOperatorExpression: CompilableExpression { } return .Ok( - AST.BinaryOperatorExpression( + CST.BinaryOperatorExpression( withType: selected_evaluator.2, withLhs: left_hand_side, withRhs: right_hand_side)) } } -extension AST.ArrayAccessExpression: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ArrayAccessExpression: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let expression = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: expression, type: "arrayAccessExpression", nice_type_name: "Array Access Expression") let array_access_expression_node = expression @@ -419,11 +419,11 @@ extension AST.ArrayAccessExpression: CompilableExpression { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Malformed array access expression"))) - #RequireNodeType( + #RequireNodeType( node: current_node!, type: "expression", nice_type_name: "array identifier expression") let array_access_identifier_node = current_node! @@ -431,7 +431,7 @@ extension AST.ArrayAccessExpression: CompilableExpression { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing [ for array access expression"))) @@ -440,42 +440,42 @@ extension AST.ArrayAccessExpression: CompilableExpression { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing indexor expression for array access expression"))) - #RequireNodeType( + #RequireNodeType( node: current_node!, type: "expression", nice_type_name: "array indexor expression") let array_access_indexor_node = current_node! - let maybe_array_identifier = AST.Expression.Compile( + let maybe_array_identifier = CST.Expression.Parse( node: array_access_identifier_node, withContext: context) guard case Result.Ok(let array_identifier) = maybe_array_identifier else { return Result.Error(maybe_array_identifier.error()!) } - let maybe_array_indexor = AST.Expression.Compile( + let maybe_array_indexor = CST.Expression.Parse( node: array_access_indexor_node, withContext: context) guard case Result.Ok(let array_indexor) = maybe_array_indexor else { return Result.Error(maybe_array_indexor.error()!) } return .Ok( - AST.ArrayAccessExpression( + CST.ArrayAccessExpression( withName: array_identifier, withIndexor: array_indexor)) } } -extension AST.FieldAccessExpression: CompilableExpression { - public static func CompileExpression( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.FieldAccessExpression: ParsableExpression { + public static func ParseExpression( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let expression = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: expression, type: "fieldAccessExpression", nice_type_name: "Array Access Expression") let field_access_expression_node = expression @@ -485,11 +485,11 @@ extension AST.FieldAccessExpression: CompilableExpression { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Malformed field access expression"))) - #RequireNodeType( + #RequireNodeType( node: current_node!, type: "expression", nice_type_name: "struct identifier expression") let struct_identifier_node = current_node! @@ -497,7 +497,7 @@ extension AST.FieldAccessExpression: CompilableExpression { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing . for field access expression"))) @@ -505,44 +505,44 @@ extension AST.FieldAccessExpression: CompilableExpression { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing field name for field access expression"))) - #RequireNodeType( + #RequireNodeType( node: current_node!, type: "identifier", nice_type_name: "field name") let field_name_node = current_node! // Make sure that the identifier really identifies a struct. - let maybe_struct_identifier = AST.Expression.Compile( + let maybe_struct_identifier = CST.Expression.Parse( node: struct_identifier_node, withContext: context) guard case Result.Ok(let struct_identifier) = maybe_struct_identifier else { return Result.Error(maybe_struct_identifier.error()!) } - let maybe_field_name = AST.Identifier.CompileExpression( + let maybe_field_name = CST.Identifier.ParseExpression( node: field_name_node, withContext: context) guard case Result.Ok(let field_name) = maybe_field_name else { return Result.Error(maybe_field_name.error()!) } return .Ok( - AST.FieldAccessExpression( + CST.FieldAccessExpression( withStruct: struct_identifier, - withField: field_name as! AST.Identifier)) + withField: field_name as! CST.Identifier)) } } -extension AST.FunctionCall: CompilableExpression { - public static func CompileExpression( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.FunctionCall: ParsableExpression { + public static func ParseExpression( + node: Node, withContext context: CSTCompilerContext + ) -> Result { let expression = node.child(at: 0)! - #RequireNodeType( + #RequireNodeType( node: expression, type: "function_call", nice_type_name: "Function Call") var walker = Walker(node: expression) @@ -550,11 +550,11 @@ extension AST.FunctionCall: CompilableExpression { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing function call component"))) - let maybe_callee_name = AST.Identifier.CompileExpression( + let maybe_callee_name = CST.Identifier.ParseExpression( node: current_node!, withContext: context) guard case .Ok(let callee_name) = maybe_callee_name else { return Result.Error(maybe_callee_name.error()!) @@ -563,15 +563,15 @@ extension AST.FunctionCall: CompilableExpression { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing function call component"))) - let maybe_argument_list = AST.ArgumentList.Compile(node: current_node!, withContext: context) + let maybe_argument_list = CST.ArgumentList.Parse(node: current_node!, withContext: context) guard case .Ok(let arguments) = maybe_argument_list else { return .Error(maybe_argument_list.error()!) } - return .Ok(AST.FunctionCall(callee_name as! AST.Identifier, withArguments: arguments)) + return .Ok(CST.FunctionCall(callee_name as! CST.Identifier, withArguments: arguments)) } } diff --git a/Sources/P4Compiler/Parser.swift b/Sources/P4Parser/Parsers/Parser.swift similarity index 58% rename from Sources/P4Compiler/Parser.swift rename to Sources/P4Parser/Parsers/Parser.swift index f6b95e7..42c902d 100644 --- a/Sources/P4Compiler/Parser.swift +++ b/Sources/P4Parser/Parsers/Parser.swift @@ -20,55 +20,13 @@ import SwiftTreeSitter import TreeSitterExtensions import TreeSitterP4 -extension AST.Statement: Compilable { - public typealias C = AST.AnStatement - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - - if node.nodeType != "parserStatement" && node.nodeType != "statement" { - return Result.Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), withError: "Missing expected parser statement") - ) - } - - let statement = node.child(at: 0)! - - let statementParsers: [String: CompilableStatement.Type] = [ - "assignmentStatement": AST.ParserAssignmentStatement.self, - "expressionStatement": AST.ExpressionStatement.self, - "variableDeclaration": AST.VariableDeclarationStatement.self, - "conditionalStatement": AST.ConditionalStatement.self, - "blockStatement": AST.BlockStatement.self, - "return_statement": AST.ReturnStatement.self, - ] - guard let parser = statementParsers[statement.nodeType ?? ""] else { - return Result.Error( - ErrorWithLocation( - sourceLocation: statement.toSourceLocation(), - withError: - "Unparseable statement type (\(statement.nodeType ?? "Unknown Statement Type"))")) - } - switch parser.CompileStatement(node: statement, withContext: context) { - case Result.Ok(let parsed): - return .Ok(parsed) - case Result.Error(let e): - return .Error( - ErrorWithLocation( - sourceLocation: node.toSourceLocation(), - withError: "Failed to parse a statement element: \(e)")) - } - } -} - -extension AST.LocalElements: Compilable { - public typealias C = AST.AnStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { - let localElementsParsers: [String: CompilableStatement.Type] = [ - "variableDeclaration": AST.VariableDeclarationStatement.self +extension CST.LocalElements: Parsable { + public typealias C = CST.Statement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + let localElementsParsers: [String: ParsableStatement.Type] = [ + "variableDeclaration": CST.VariableDeclarationStatement.self ] guard let parser = localElementsParsers[node.nodeType ?? ""] else { @@ -78,7 +36,7 @@ extension AST.LocalElements: Compilable { withError: "Unparseable statement type (\(node.nodeType ?? "Unknown Statement Type"))")) } - switch parser.CompileStatement(node: node, withContext: context) { + switch parser.ParseStatement(node: node, withContext: context) { case Result.Ok(let parsed): return Result.Ok(parsed) case Result.Error(let e): @@ -87,11 +45,11 @@ extension AST.LocalElements: Compilable { } } -extension AST.ParserState: Compilable { - public typealias C = AST.AnState - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ParserState: Parsable { + public typealias C = CST.AnState + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { var walker = Walker(node: node) var current_node: Node? = .none @@ -107,7 +65,7 @@ extension AST.ParserState: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing elements in parser state declaration"))) @@ -125,12 +83,12 @@ extension AST.ParserState: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing elements in parser state declaration"))) - let maybe_state_identifier = AST.Identifier.CompileExpression( + let maybe_state_identifier = CST.Identifier.ParseExpression( node: current_node!, withContext: context) guard case Result.Ok(let state_identifier) = maybe_state_identifier else { return Result.Error(maybe_state_identifier.error()!) @@ -141,16 +99,16 @@ extension AST.ParserState: Compilable { walker.next() #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing body of state declaration") )) var errors: (any Errorable)? = .none - var parsed_s: [AST.AnStatement] = Array() + var parsed_s: CST.Statements? = .none if current_node!.nodeType == "parserStatements" { - switch SpecialCompilers.Statements.Compile( + switch CST.Statements.Parse( node: current_node!, withContext: context) { case .Ok(let state_statements): @@ -172,14 +130,14 @@ extension AST.ParserState: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing transition statement of state declaration"))) - let updated_context = context.update(withContextName: (state_identifier as! AST.Identifier)) + let updated_context = context.update(withContextName: (state_identifier as! CST.Identifier)) .update(withContextStatements: parsed_s) - return AST.TransitionStatement.Compile(node: current_node!, withContext: updated_context) + return CST.TransitionStatement.Parse(node: current_node!, withContext: updated_context) } } diff --git a/Sources/P4Parser/Parsers/Program.swift b/Sources/P4Parser/Parsers/Program.swift new file mode 100644 index 0000000..6ecfda9 --- /dev/null +++ b/Sources/P4Parser/Parsers/Program.swift @@ -0,0 +1,72 @@ +// p4rse, Copyright 2026, Will Hawkins +// +// This file is part of p4rse. +// +// This file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +import Common +import SwiftTreeSitter + +extension CST.Program: Parsable { + public typealias C = CST.Program + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Common.Result { + + var statements: [CST.Statement] = Array() + + var errors: (any Errorable)? = .none + + // Try to parse all top-level declarations. + node.enumerateNamedChildren { (declaration_node: Node) in + let declaration_parsers: [String: ParsableStatement.Type] = [ + "declaration": CST.Declaration.self, + "instantiation": CST.Instantiation.self, + ] + + if let parser = declaration_parsers[declaration_node.nodeType!] { + let r = parser.ParseStatement(node: declaration_node, withContext: context) + switch r { + case .Ok(let compiled): + statements.append(compiled) + case .Error(let e): + errors = + if let errors = errors { + errors.append(error: e) + } else { + e + } + + } + } else { + let e = ErrorWithLocation( + sourceLocation: declaration_node.toSourceLocation(), + withError: + "\(declaration_node.nodeType!) cannot be at a P4 program top level") + errors = + if let errors = errors { + errors.append(error: e) + } else { + e + } + } + } + + if let errors = errors { + return .Error(errors) + } + return Result.Ok(CST.Program(CST.Statements(statements))) + + } +} diff --git a/Sources/P4Parser/Parsers/SpecialParsers.swift b/Sources/P4Parser/Parsers/SpecialParsers.swift new file mode 100644 index 0000000..fd41477 --- /dev/null +++ b/Sources/P4Parser/Parsers/SpecialParsers.swift @@ -0,0 +1,67 @@ +// p4rse, Copyright 2026, Will Hawkins +// +// This file is part of p4rse. +// +// This file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +import Common +import SwiftTreeSitter +import TreeSitterExtensions +import TreeSitterP4 + +public struct SpecialParsers { + public struct Statement {} +} + +extension SpecialParsers.Statement: Parsable { + public typealias C = CST.Statement + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + + if node.nodeType != "parserStatement" && node.nodeType != "statement" { + return Result.Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), withError: "Missing expected parser statement") + ) + } + + let statement = node.child(at: 0)! + + let statementParsers: [String: ParsableStatement.Type] = [ + "assignmentStatement": CST.ParserAssignmentStatement.self, + "expressionStatement": CST.ExpressionStatement.self, + "variableDeclaration": CST.VariableDeclarationStatement.self, + "conditionalStatement": CST.ConditionalStatement.self, + "blockStatement": CST.BlockStatement.self, + "return_statement": CST.ReturnStatement.self, + ] + guard let parser = statementParsers[statement.nodeType ?? ""] else { + return Result.Error( + ErrorWithLocation( + sourceLocation: statement.toSourceLocation(), + withError: + "Unparseable statement type (\(statement.nodeType ?? "Unknown Statement Type"))")) + } + switch parser.ParseStatement(node: statement, withContext: context) { + case Result.Ok(let parsed): + return .Ok(parsed) + case Result.Error(let e): + return .Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), + withError: "Failed to parse a statement element: \(e)")) + } + } +} diff --git a/Sources/P4Compiler/Statement.swift b/Sources/P4Parser/Parsers/Statement.swift similarity index 53% rename from Sources/P4Compiler/Statement.swift rename to Sources/P4Parser/Parsers/Statement.swift index ee6df5e..8c8cd19 100644 --- a/Sources/P4Compiler/Statement.swift +++ b/Sources/P4Parser/Parsers/Statement.swift @@ -20,11 +20,11 @@ import SwiftTreeSitter import TreeSitterExtensions import TreeSitterP4 -extension AST.BlockStatement: Compilable { - public typealias C = AST.BlockStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.BlockStatement: Parsable { + public typealias C = CST.BlockStatement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { /* #RequireNodeType( node: node, type: "blockStatement", nice_type_name: "block statement") @@ -56,7 +56,7 @@ extension AST.BlockStatement: Compilable { sourceLocation: node.toSourceLocation(), withError: "Malformed block statement"))) if current_node!.nodeType == "statements" { - switch SpecialCompilers.Statements.Compile( + switch SpecialCompilers.Statements.Parse( node: current_node!, withContext: context) { case .Ok(let parsed_statements): @@ -87,20 +87,20 @@ extension AST.BlockStatement: Compilable { return .Ok(AST.BlockStatement(statements)) */ - return .Ok(AST.BlockStatement([])) + return .Ok(CST.BlockStatement(CST.Statements([]))) } } -@deriveCompilableStatement -extension AST.BlockStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.BlockStatement: ParsableStatement {} -extension AST.ConditionalStatement: Compilable { - public typealias C = AST.ConditionalStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ConditionalStatement: Parsable { + public typealias C = CST.ConditionalStatement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "conditionalStatement", nice_type_name: "conditional statement") let maybe_condition_expression = node.child(at: 2) @@ -124,7 +124,7 @@ extension AST.ConditionalStatement: Compilable { } guard - case .Ok(let condition) = AST.Expression.Compile( + case .Ok(let condition) = CST.Expression.Parse( node: condition_expression, withContext: context) else { return Result.Error( @@ -132,7 +132,7 @@ extension AST.ConditionalStatement: Compilable { } guard - case .Ok(let thenns) = AST.Statement.Compile( + case .Ok(let thenns) = SpecialParsers.Statement.Parse( node: thens, withContext: context) else { return Result.Error( @@ -141,10 +141,10 @@ extension AST.ConditionalStatement: Compilable { "Could not parse the then block in a conditional statement")) } - let optional_elss: Result? = + let optional_elss: Result? = if let elss = node.child(at: 6) { .some( - AST.Statement.Compile( + SpecialParsers.Statement.Parse( node: elss, withContext: context)) } else { .none @@ -160,22 +160,22 @@ extension AST.ConditionalStatement: Compilable { "Could not parse the else block in a conditional statement")) } return .Ok( - AST.ConditionalStatement(condition: condition, withThen: thenns, andElse: elss)) + CST.ConditionalStatement(condition: condition, withThen: thenns, andElse: elss)) } - return .Ok(AST.ConditionalStatement(condition: condition, withThen: thenns)) + return .Ok(CST.ConditionalStatement(condition: condition, withThen: thenns)) } } -@deriveCompilableStatement -extension AST.ConditionalStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.ConditionalStatement: ParsableStatement {} -extension AST.VariableDeclarationStatement: Compilable { - public typealias C = AST.VariableDeclarationStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.VariableDeclarationStatement: Parsable { + public typealias C = CST.VariableDeclarationStatement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "variableDeclaration", nice_type_name: "variable declaration statement") let maybe_typeref = node.child(at: 0) @@ -201,7 +201,7 @@ extension AST.VariableDeclarationStatement: Compilable { let maybe_rvalue = node.childCount > 3 ? node.child(at: 3) : .none guard - case .Ok(let parsed_variablename) = AST.Identifier.CompileExpression( + case .Ok(let parsed_variablename) = CST.Identifier.ParseExpression( node: variablename, withContext: context) else { return Result.Error( @@ -209,13 +209,13 @@ extension AST.VariableDeclarationStatement: Compilable { } guard - case .Ok(let declaration_p4_type) = AST.Types.CompileType(type: typeref, withContext: context) + case .Ok(let declaration_p4_type) = CST.Types.ParseType(type: typeref, withContext: context) else { return Result.Error( Error(withMessage: "Could not parse a P4 type from \(typeref.text!)")) } - var initializer: AST.AnExpression? = .none + var initializer: CST.AnExpression? = .none // If there is an initializer, it must be an expression. if let initializer_expression = maybe_rvalue { @@ -226,7 +226,7 @@ extension AST.VariableDeclarationStatement: Compilable { withError: "initial value for declaration statement is not an expression")) } - let maybe_parsed_rvalue = AST.Expression.Compile( + let maybe_parsed_rvalue = CST.Expression.Parse( node: initializer_expression, withContext: context) guard case .Ok(let parsed_rvalue) = maybe_parsed_rvalue @@ -238,43 +238,43 @@ extension AST.VariableDeclarationStatement: Compilable { } return Result.Ok( - AST.VariableDeclarationStatement( - identifier: parsed_variablename as! AST.Identifier, withType: declaration_p4_type, + CST.VariableDeclarationStatement( + identifier: parsed_variablename as! CST.Identifier, withType: declaration_p4_type, withInitializer: initializer), ) } } -@deriveCompilableStatement -extension AST.VariableDeclarationStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.VariableDeclarationStatement: ParsableStatement {} -extension AST.ExpressionStatement: Compilable { - public typealias C = AST.ExpressionStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ExpressionStatement: Parsable { + public typealias C = CST.ExpressionStatement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { #RequireNodeType( node: node, type: "expressionStatement", nice_type_name: "expression statement") let expression_node = node.child(at: 0)! - return switch AST.Expression.Compile(node: expression_node, withContext: context) { - case .Ok(let expression): .Ok(AST.ExpressionStatement(expression)) + return switch CST.Expression.Parse(node: expression_node, withContext: context) { + case .Ok(let expression): .Ok(CST.ExpressionStatement(expression)) case .Error(let e): .Error(e) } } } -@deriveCompilableStatement -extension AST.ExpressionStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.ExpressionStatement: ParsableStatement {} -extension AST.ParserAssignmentStatement: Compilable { - public typealias C = AST.ParserAssignmentStatement - public static func Compile( - node: Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.ParserAssignmentStatement: Parsable { + public typealias C = CST.ParserAssignmentStatement + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { - #RequireNodeType( + #RequireNodeType( node: node, type: "assignmentStatement", nice_type_name: "assignment statement") guard let lvalue_node = node.child(at: 0), @@ -295,77 +295,77 @@ extension AST.ParserAssignmentStatement: Compilable { withError: "Missing rvalue in assignment statement")) } - let maybe_parsed_rvalue = AST.Expression.Compile( + let maybe_parsed_rvalue = CST.Expression.Parse( node: rvalue_node, withContext: context) guard case Result.Ok(let rvalue) = maybe_parsed_rvalue else { return Result.Error(maybe_parsed_rvalue.error()!) } - let maybe_parsed_lvalue = AST.Expression.Compile(node: lvalue_node, withContext: context) + let maybe_parsed_lvalue = CST.Expression.Parse(node: lvalue_node, withContext: context) guard case .Ok(let lvalue) = maybe_parsed_lvalue else { return Result.Error(maybe_parsed_lvalue.error()!) } return Result.Ok( - AST.ParserAssignmentStatement( + CST.ParserAssignmentStatement( withLValue: lvalue, withValue: rvalue )) } } -@deriveCompilableStatement -extension AST.ParserAssignmentStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.ParserAssignmentStatement: ParsableStatement {} -extension AST.ReturnStatement: Compilable { - public typealias C = AST.ReturnStatement - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.ReturnStatement: Parsable { + public typealias C = CST.ReturnStatement + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "return_statement", nice_type_name: "return statement") let expression_node = node.child(at: 1)! - return switch AST.Expression.Compile(node: expression_node, withContext: context) { - case .Ok(let result): .Ok(AST.ReturnStatement(result)) + return switch CST.Expression.Parse(node: expression_node, withContext: context) { + case .Ok(let result): .Ok(CST.ReturnStatement(result)) case .Error(let e): .Error(e) } } } -@deriveCompilableStatement -extension AST.ReturnStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.ReturnStatement: ParsableStatement {} -extension AST.ApplyStatement: Compilable { - public typealias C = AST.ApplyStatement - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - #RequireNodeType( +extension CST.ApplyStatement: Parsable { + public typealias C = CST.ApplyStatement + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + #RequireNodeType( node: node, type: "apply_statement", nice_type_name: "apply statement") let expression_node = node.child(at: 1)! - return switch AST.BlockStatement.Compile(node: expression_node, withContext: context) { + return switch CST.BlockStatement.Parse(node: expression_node, withContext: context) { case .Ok(let statement): - .Ok(AST.ApplyStatement(statement)) + .Ok(CST.ApplyStatement(statement)) case .Error(let e): .Error(e) } } } -@deriveCompilableStatement -extension AST.ApplyStatement: CompilableStatement {} +@deriveParsableStatement +extension CST.ApplyStatement: ParsableStatement {} -extension AST.Instantiation: Compilable { - public typealias C = AST.Instantiation - public static func Compile( - node: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { +extension CST.Instantiation: Parsable { + public typealias C = CST.Instantiation + public static func Parse( + node: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { let expression = node - #RequireNodeType( + #RequireNodeType( node: expression, type: "instantiation", nice_type_name: "instantiation statement") var walker = Walker(node: expression) @@ -373,11 +373,11 @@ extension AST.Instantiation: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing function call component"))) - let maybe_instantiated_type_name = AST.Identifier.CompileExpression( + let maybe_instantiated_type_name = CST.Identifier.ParseExpression( node: current_node!, withContext: context) guard case .Ok(let instantiated_type_name) = maybe_instantiated_type_name else { return Result.Error(maybe_instantiated_type_name.error()!) @@ -386,11 +386,11 @@ extension AST.Instantiation: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing instantiation component"))) - let maybe_argument_list = AST.ArgumentList.Compile(node: current_node!, withContext: context) + let maybe_argument_list = CST.ArgumentList.Parse(node: current_node!, withContext: context) guard case .Ok(let arguments) = maybe_argument_list else { return .Error(maybe_argument_list.error()!) @@ -400,21 +400,125 @@ extension AST.Instantiation: Compilable { #MustOr( result: current_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: node.toSourceLocation(), withError: "Missing instantiation name"))) - let name = AST.Identifier.CompileExpression(node: current_node!, withContext: context) + let name = CST.Identifier.ParseExpression(node: current_node!, withContext: context) guard case .Ok(let name) = name else { return .Error(name.error()!) } return .Ok( - AST.Instantiation( - named: name as! AST.Identifier, withType: instantiated_type_name as! AST.Identifier, + CST.Instantiation( + named: name as! CST.Identifier, withType: instantiated_type_name as! CST.Identifier, withArguments: arguments)) } } -@deriveCompilableStatement -extension AST.Instantiation: CompilableStatement {} +@deriveParsableStatement +extension CST.Instantiation: ParsableStatement {} + +extension CST.Statements: Parsable { + public typealias C = CST.Statements + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + if node.nodeType != "statements" && node.nodeType != "parserStatements" { + return Result.Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), withError: "Did not find expected statements")) + } + + var errors: (any Errorable)? = .none + var parsed_s: [CST.Statement] = Array() + + node.enumerateNamedChildren { node in + switch SpecialParsers.Statement.Parse( + node: node, withContext: context) + { + case .Ok(let parsed_statement): + parsed_s.append(parsed_statement) + case .Error(let e): + errors = + if let errors = errors { + errors.append(error: e) + } else { + e + } + } + } + + if let errors = errors { + return .Error(errors) + } + + return Result.Ok(CST.Statements(parsed_s)) + } +} + +extension CST.TransitionStatement: Parsable { + public static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result { + + guard let state_identifier = context.lexical_context_name else { + return .Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), + withError: "Cannot parse a transition statement without the name of the containing state." + )) + } + + let stmts = context.lexical_context_statements + + #RequireNodeType( + node: node, type: "parserTransitionStatement", nice_type_name: "parser transition statement" + ) + + guard let tse_node = node.child(at: 1), + tse_node.nodeType! == "transitionSelectionExpression" + else { + return .Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), + withError: "Could not find transition select expression")) + } + + guard let next_node = tse_node.child(at: 0) else { + return .Error( + ErrorWithLocation( + sourceLocation: node.toSourceLocation(), + withError: "Could not find the next token in a transition selection expression")) + } + + // If the next node is an identifier, we have the simple form ... + if next_node.nodeType == "identifier" { + let maybe_parsed_next_state_id = CST.Identifier.ParseExpression( + node: next_node, withContext: context) + switch maybe_parsed_next_state_id { + case .Ok(let next_state_id): + return .Ok( + CST.ParserStateDirectTransition( + name: (state_identifier), + withNextStateIdentifier: next_state_id as! CST.Identifier, withStatements: stmts)) + case .Error(let e): + return .Error(e) + } + } + + // We know that the next node is a select expression. + return + switch CST.SelectExpression.ParseExpression(node: next_node, withContext: context) + { + case .Ok(let tse): + .Ok( + CST.ParserStateSelectTransition( + name: state_identifier, withTransitionExpression: tse as! CST.SelectExpression, + withStatements: stmts, + ) + ) + case .Error(let e): .Error(e) + } + } +} diff --git a/Sources/P4Compiler/Types.swift b/Sources/P4Parser/Parsers/Types.swift similarity index 66% rename from Sources/P4Compiler/Types.swift rename to Sources/P4Parser/Parsers/Types.swift index 8c4f437..08f7805 100644 --- a/Sources/P4Compiler/Types.swift +++ b/Sources/P4Parser/Parsers/Types.swift @@ -20,18 +20,18 @@ import SwiftTreeSitter import TreeSitterExtensions import TreeSitterP4 -extension P4Boolean: MaybeCompilableType { - public static func MaybeCompileType( - type: SwiftTreeSitter.Node, withContext: ASTCompilerContext - ) -> Common.Result<(AST.Tipe)?> { - return type.text == "bool" ? .Ok(AST.Tipe(P4QualifiedType(P4Boolean()))) : .Ok(.none) +extension P4Boolean: MaybeParsableType { + public static func MaybeParseType( + type: SwiftTreeSitter.Node, withContext: CSTCompilerContext + ) -> Common.Result<(CST.Tipe)?> { + return type.text == "bool" ? .Ok(CST.Tipe(P4QualifiedType(P4Boolean()))) : .Ok(.none) } } -extension P4Int: MaybeCompilableType { - public static func MaybeCompileType( - type: SwiftTreeSitter.Node, withContext: ASTCompilerContext - ) -> Common.Result<(AST.Tipe)?> { +extension P4Int: MaybeParsableType { + public static func MaybeParseType( + type: SwiftTreeSitter.Node, withContext: CSTCompilerContext + ) -> Common.Result<(CST.Tipe)?> { // Drill down, as appropriate. let base_type_node = type.child(at: 0)! @@ -48,7 +48,7 @@ extension P4Int: MaybeCompilableType { #MustOr( result: int_node, thing: walker.getNext(), - or: Result.Error( + or: Result.Error( ErrorWithLocation( sourceLocation: type_node.toSourceLocation(), withError: "Missing elements in int type declaration"))) @@ -65,29 +65,29 @@ extension P4Int: MaybeCompilableType { sourceLocation: bit_width_node.toSourceLocation(), withError: "Could not parse \(bit_width_node.text!) into integer")) } - return .Ok(AST.Tipe(P4QualifiedType(P4Int(BitWidth.Width(bit_width))))) + return .Ok(CST.Tipe(P4QualifiedType(P4Int(BitWidth.Width(bit_width))))) } - return .Ok(AST.Tipe(P4QualifiedType(P4Int(BitWidth.Infinite)))) + return .Ok(CST.Tipe(P4QualifiedType(P4Int(BitWidth.Infinite)))) } } -extension P4String: MaybeCompilableType { - public static func MaybeCompileType( - type: SwiftTreeSitter.Node, withContext: ASTCompilerContext - ) -> Common.Result<(AST.Tipe)?> { - return type.text == "string" ? .Ok(AST.Tipe(P4QualifiedType(P4String()))) : .Ok(.none) +extension P4String: MaybeParsableType { + public static func MaybeParseType( + type: SwiftTreeSitter.Node, withContext: CSTCompilerContext + ) -> Common.Result<(CST.Tipe)?> { + return type.text == "string" ? .Ok(CST.Tipe(P4QualifiedType(P4String()))) : .Ok(.none) } } -extension AST.Types: CompilableType { - public static func CompileType( - type: SwiftTreeSitter.Node, withContext context: ASTCompilerContext - ) -> Result { - let type_parsers: [MaybeCompilableType.Type] = [ +extension CST.Types: ParsableType { + public static func ParseType( + type: SwiftTreeSitter.Node, withContext context: CSTCompilerContext + ) -> Result { + let type_parsers: [MaybeParsableType.Type] = [ P4Boolean.self, P4Int.self, P4String.self, /*P4Struct.self,*/ ] for type_parser in type_parsers { - switch type_parser.MaybeCompileType(type: type, withContext: context) { + switch type_parser.MaybeParseType(type: type, withContext: context) { case .Ok(.some(let type)): return .Ok(type) case .Ok(.none): continue case .Error(let e): return .Error(e) diff --git a/Sources/P4Parser/Protocols.swift b/Sources/P4Parser/Protocols.swift new file mode 100644 index 0000000..c181e53 --- /dev/null +++ b/Sources/P4Parser/Protocols.swift @@ -0,0 +1,73 @@ +// p4rse, Copyright 2026, Will Hawkins +// +// This file is part of p4rse. +// +// This file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +import Common +import SwiftTreeSitter +import TreeSitterExtensions +import TreeSitterP4 + +/* +public protocol CompilableValue { + static func CompileValue(withValue value: String) -> Result +} +*/ + +public protocol MaybeParsableType { + static func MaybeParseType( + type: SwiftTreeSitter.Node, withContext: CSTCompilerContext + ) -> Result +} + +public protocol ParsableType { + static func ParseType( + type: SwiftTreeSitter.Node, withContext: CSTCompilerContext + ) -> Result +} +public protocol ParsableExpression { + static func ParseExpression( + node: Node, withContext context: CSTCompilerContext + ) -> Result +} + +public protocol Parsable { + associatedtype C + static func Parse( + node: Node, withContext context: CSTCompilerContext + ) -> Result +} + +public protocol ParsableStatement { + static func ParseStatement( + node: Node, withContext context: CSTCompilerContext + ) -> Result +} + +public protocol CSTVisitor { + associatedtype T + func visit(node: CST.BinaryOperatorExpression, driver: CSTVisitorDriver, context: T) -> Result + func visit(node: CST.Literal, driver: CSTVisitorDriver, context: T) -> Result + func visit(node: CST.Identifier, driver: CSTVisitorDriver, context: T) -> Result + + func visit(node: CST.Parser, driver: CSTVisitorDriver, context: T) -> Result + func visit( + node: CST.ParserStateDirectTransition, driver: CSTVisitorDriver, context: T + ) -> Result + func visit(node: CST.ParserStateNoTransition, driver: CSTVisitorDriver, context: T) -> Result + func visit( + node: CST.ParserStateSelectTransition, driver: CSTVisitorDriver, context: T + ) -> Result +} diff --git a/Sources/P4Compiler/Visitor.swift b/Sources/P4Parser/Visitor.swift similarity index 73% rename from Sources/P4Compiler/Visitor.swift rename to Sources/P4Parser/Visitor.swift index 4f212da..1f66bdf 100644 --- a/Sources/P4Compiler/Visitor.swift +++ b/Sources/P4Parser/Visitor.swift @@ -17,49 +17,49 @@ import Common -public struct ASTVisitorDriver { +public struct CSTVisitorDriver { public init() {} public func visit( - expression: any AST.AnExpression, visitor: any ASTVisitor, context: T + expression: any CST.AnExpression, visitor: any CSTVisitor, context: T ) -> Result { return switch expression { - case let e as AST.BinaryOperatorExpression: + case let e as CST.BinaryOperatorExpression: visitor.visit(node: e, driver: self, context: context) - case let e as AST.Literal: visitor.visit(node: e, driver: self, context: context) + case let e as CST.Literal: visitor.visit(node: e, driver: self, context: context) default: .Error(Error(withMessage: "AST Expression Element Is Not Visitable")) } } public func visit( - state: any AST.AnState, visitor: any ASTVisitor, context: T + state: any CST.AnState, visitor: any CSTVisitor, context: T ) -> Result { return switch state { - case let s as AST.ParserStateDirectTransition: + case let s as CST.ParserStateDirectTransition: visitor.visit(node: s, driver: self, context: context) - case let s as AST.ParserStateNoTransition: + case let s as CST.ParserStateNoTransition: visitor.visit(node: s, driver: self, context: context) - case let s as AST.ParserStateSelectTransition: + case let s as CST.ParserStateSelectTransition: visitor.visit(node: s, driver: self, context: context) default: .Error(Error(withMessage: "AST State Element (\(state)) Is Not Visitable")) } } public func visit( - statement: any AST.AnStatement, visitor: any ASTVisitor, context: T + statement: any CST.Statement, visitor: any CSTVisitor, context: T ) -> Result { return switch statement { - case let s as AST.Parser: visitor.visit(node: s, driver: self, context: context) + case let s as CST.Parser: visitor.visit(node: s, driver: self, context: context) default: .Error(Error(withMessage: "AST Statement Element Is Not Visitable")) } } public func visit( - program: AST.Program, visitor: any ASTVisitor, context: T + program: CST.Program, visitor: any CSTVisitor, context: T ) -> Result { var context = context - for s in program.statements { + for s in program.statements.statements { switch visit(statement: s, visitor: visitor, context: context) { case .Ok(let c): context = c case .Error(let e): return .Error(e) diff --git a/Sources/P4Compiler/Walker.swift b/Sources/P4Parser/Walker.swift similarity index 100% rename from Sources/P4Compiler/Walker.swift rename to Sources/P4Parser/Walker.swift diff --git a/Tests/p4rseTests/CodeGenTests/Serializer.swift b/Tests/p4rseTests/CodeGenTests/Serializer.swift index f633c1c..c83be4a 100644 --- a/Tests/p4rseTests/CodeGenTests/Serializer.swift +++ b/Tests/p4rseTests/CodeGenTests/Serializer.swift @@ -22,9 +22,9 @@ import SwiftTreeSitter import Testing import TreeSitter import TreeSitterP4 -import P4CodeGen -@testable import P4Compiler +@testable import P4Parser +@testable import P4CodeGen @Test func test_text_serializer() async throws { let simple_parser_declaration = """ @@ -42,9 +42,9 @@ import P4CodeGen }; """ - let program = try #UseOkResult(SpecialCompilers.ProgramCompiler.Compile(simple_parser_declaration)) - let v = TextSerializer() - let c = TextSerializerContext(); - let vd = ASTVisitorDriver(); + let program = try #UseOkResult(compile(simple_parser_declaration)) + let v = CSTTextSerializer() + let c = CSTTextSerializerContext(); + let vd = CSTVisitorDriver(); #expect(#RequireOkResult((vd.visit(program: program, visitor: v, context: c)))) } diff --git a/Tests/p4rseTests/SourceCodeTests/SourceCode.swift b/Tests/p4rseTests/SourceCodeTests/SourceCode.swift index 925c56b..1b62f77 100644 --- a/Tests/p4rseTests/SourceCodeTests/SourceCode.swift +++ b/Tests/p4rseTests/SourceCodeTests/SourceCode.swift @@ -17,7 +17,6 @@ import Foundation import Macros -import P4Compiler import SwiftTreeSitter import SystemPackage import Testing @@ -25,6 +24,7 @@ import TreeSitter import TreeSitterP4 @testable import Common +@testable import P4Parser @Test func test_preprocessor() async throws { let sm = SourceManager(["./TestData/Sources/"]) @@ -32,7 +32,7 @@ import TreeSitterP4 let file = FilePath.init(stringLiteral: "simple.p4") let source = try! (#UseOkResult(prep.preprocess(file))) - #expect(#RequireOkResult(SpecialCompilers.ProgramCompiler.Compile(source.getSource()))) + #expect(#RequireOkResult(compile(source.getSource()))) #expect(source.getLocations().getPath() == file) } @@ -42,7 +42,7 @@ import TreeSitterP4 let file = FilePath.init(stringLiteral: "simple.p4") let source = try! (#UseOkResult(prep.preprocess(file))) - #expect(#RequireOkResult(SpecialCompilers.ProgramCompiler.Compile(source.getSource()))) + #expect(#RequireOkResult(compile(source.getSource()))) #expect(source.getLocations().getPath() == file) } @@ -54,7 +54,7 @@ import TreeSitterP4 #expect(#RequireOkResult(prep.preprocess(file))) let source = try! (#UseOkResult(prep.preprocess(file))) - #expect(#RequireOkResult(SpecialCompilers.ProgramCompiler.Compile(source.getSource()))) + #expect(#RequireOkResult(compile(source.getSource()))) #expect(source.getLocations().getPath() == file) } @@ -66,7 +66,7 @@ import TreeSitterP4 #expect(#RequireOkResult(prep.preprocess(file))) let source = try! (#UseOkResult(prep.preprocess(file))) - #expect(#RequireOkResult(SpecialCompilers.ProgramCompiler.Compile(source.getSource()))) + #expect(#RequireOkResult(compile(source.getSource()))) #expect(source.getLocations().getPath() == file) }