compiler, language, runtime: Separate Parser Type From Instances
Continuous Integration / Grammar Tests (push) Successful in 4m2s
Continuous Integration / Library Format Tests (push) Successful in 5m0s
Continuous Integration / Library Tests (push) Successful in 8m1s

In P4, parsers are considered types. Those parsers are instantiated.
The instantiated parsers are values. Previously, gp4 treated a parser
type and a parser value as identical. This PR makes that difference
clear _and_ sets the stage for the future.

TODO: Make the same distinction between control and action types and
values.

Signed-off-by: Will Hawkins <hawkinsw@obs.cr>
This commit is contained in:
Will Hawkins
2026-05-27 05:41:23 -04:00
parent 925f20a13b
commit 61d8f601e8
36 changed files with 1058 additions and 796 deletions
+6
View File
@@ -257,6 +257,12 @@ public typealias VarValueScope = Scope<P4Value>
/// Scopes that resolves variable identifiers to their values.
public typealias VarValueScopes = Scopes<P4Value>
/// A scope that resolves variable identifiers to their values.
public typealias StaticVarValueScope = Scope<(P4QualifiedType, P4Value?)>
/// Scopes that resolves variable identifiers to their values.
public typealias StaticVarValueScopes = Scopes<(P4QualifiedType, P4Value?)>
/// Indicate the control flow result of a particular statement.
public enum ControlFlow {
case Next
+1 -1
View File
@@ -52,7 +52,7 @@ public protocol EvaluatableLValueExpression: EvaluatableExpression {
func set(
to: P4Value, inScopes scopes: VarValueScopes, duringExecution execution: ProgramExecution
) -> Result<(VarValueScopes, P4Value)>
func check(to: EvaluatableExpression, inScopes scopes: VarTypeScopes) -> Result<()>
func check(to: EvaluatableExpression, inScopes scopes: StaticVarValueScopes) -> Result<()>
}
public protocol ProgramExecutionEvaluator {
+5 -5
View File
@@ -46,7 +46,7 @@ public func ConfigureP4Parser() -> Result<SwiftTreeSitter.Parser> {
/// knowledge of an expected type. For instance, when compiling a return statement, the
/// compiler must know the return type of the function to type check.
public struct CompilerContext {
let instances: VarTypeScopes
let instances: StaticVarValueScopes
let types: TypeTypeScopes
let externs: TypeTypeScopes
let ffis: [P4FFI]
@@ -54,7 +54,7 @@ public struct CompilerContext {
let extern_context: Bool
public init() {
instances = VarTypeScopes().enter()
instances = StaticVarValueScopes().enter()
types = TypeTypeScopes().enter()
externs = TypeTypeScopes().enter()
expected_type = .none
@@ -62,7 +62,7 @@ public struct CompilerContext {
ffis = Array()
}
public init(withInstances _instances: VarTypeScopes, withTypes _types: TypeTypeScopes) {
public init(withInstances _instances: StaticVarValueScopes, withTypes _types: TypeTypeScopes) {
instances = _instances
types = _types
externs = TypeTypeScopes().enter()
@@ -72,7 +72,7 @@ public struct CompilerContext {
}
public init(
withInstances _instances: VarTypeScopes, withTypes _types: TypeTypeScopes,
withInstances _instances: StaticVarValueScopes, withTypes _types: TypeTypeScopes,
withExpectation expectation: P4QualifiedType?, withExtern extern: Bool,
withExterns externs: TypeTypeScopes, withFFIs foreigns: [P4FFI]
) {
@@ -90,7 +90,7 @@ public struct CompilerContext {
///
/// - Parameter instances: a ``VarTypeScopes`` with the updated instances for the newly created compiler context.
/// - Returns: A new compiler context based on the current but new instances.
public func update(newInstances instances: VarTypeScopes) -> CompilerContext {
public func update(newInstances instances: StaticVarValueScopes) -> CompilerContext {
return CompilerContext(
withInstances: instances, withTypes: self.types, withExpectation: self.expected_type,
withExtern: self.extern_context, withExterns: self.externs, withFFIs: self.ffis)
+20 -15
View File
@@ -105,7 +105,7 @@ extension FunctionDeclaration: CompilableDeclaration {
var function_scope = context.instances.enter()
for parameter in function_parameters.parameters {
function_scope = function_scope.declare(
identifier: parameter.name, withValue: parameter.type)
identifier: parameter.name, withValue: (parameter.type, .none))
}
let maybe_function_body = BlockStatement.Compile(
@@ -342,7 +342,7 @@ extension P4Lang.Parser: CompilableDeclaration {
for parameter in parameter_list.parameters {
current_context = current_context.update(
newInstances: current_context.instances.declare(
identifier: parameter.name, withValue: parameter.type))
identifier: parameter.name, withValue: (parameter.type, .none)))
}
walker.next()
@@ -380,6 +380,7 @@ extension P4Lang.Parser: CompilableDeclaration {
return .Error(Error(withMessage: "Missing parser states in parser declaration"))
}
/// TODO: Handle extern parsers.
switch Parser.Compile(
withName: parser_name!, withParameters: parameter_list, node: current_node!,
withContext: current_context)
@@ -392,10 +393,11 @@ extension P4Lang.Parser: CompilableDeclaration {
(
parser_declaration,
context.extern_context
? context
: context.update(
newInstances: updated_context.instances.declare(
identifier: parser.name, withValue: parser_declaration.identifier.type))
? updated_context.update(
newExterns: updated_context.externs.declare(
identifier: parser.name, withValue: parser_declaration))
: updated_context.update(
newTypes: updated_context.types.declare(identifier: parser.name, withValue: parser))
))
case Result.Error(let error): return .Error(error)
}
@@ -450,7 +452,7 @@ extension Control: CompilableDeclaration {
var control_scope = local_context.instances.enter()
for parameter in control_parameters.parameters {
control_scope = control_scope.declare(
identifier: parameter.name, withValue: parameter.type)
identifier: parameter.name, withValue: (parameter.type, .none))
}
local_context = local_context.update(newInstances: control_scope)
@@ -543,14 +545,15 @@ extension Control: CompilableDeclaration {
))
}
let control = Control(
named: control_name, withParameters: control_parameters, withTable: tables[0],
withActions: Actions(withActions: actions), withApply: apply)
let declared_control =
Declaration(
TypedIdentifier(
id: control_name,
withType: P4QualifiedType(
Control(
named: control_name, withParameters: control_parameters, withTable: tables[0],
withActions: Actions(withActions: actions), withApply: apply))))
withType: P4QualifiedType(control)))
// Don't forget to add the newly declared Control to the instance that we were given
// (and not the one that we entered to do the parsing of this Control).
@@ -558,10 +561,12 @@ extension Control: CompilableDeclaration {
(
declared_control,
context.extern_context
? context
? context.update(
newTypes: context.externs.declare(
identifier: control_name, withValue: declared_control))
: context.update(
newInstances: context.instances.declare(
identifier: control_name, withValue: declared_control.identifier.type))
newTypes: context.types.declare(
identifier: control_name, withValue: control))
))
}
}
@@ -638,7 +643,7 @@ extension Action: Compilable {
var function_scope = context.instances.enter()
for parameter in action_parameters.parameters {
function_scope = function_scope.declare(
identifier: parameter.name, withValue: parameter.type)
identifier: parameter.name, withValue: (parameter.type, .none))
}
let maybe_action_body = BlockStatement.Compile(
+2 -1
View File
@@ -51,7 +51,8 @@ extension TypedIdentifier: CompilableExpression {
sourceLocation: node.toSourceLocation(), withError: "Cannot find \(node.text!) in scope"))
}
return .Ok(TypedIdentifier(name: node.text!, withType: type))
/// TODO: If there is a value here, then we can make this a compile-time constant!
return .Ok(TypedIdentifier(name: node.text!, withType: type.0))
}
}
+38 -16
View File
@@ -90,7 +90,7 @@ public struct Parser {
static func Compile(
node: Node, forState state_identifier: Common.Identifier,
withStatements stmts: [EvaluatableStatement], withContext context: CompilerContext
) -> Result<(InstantiatedParserState, CompilerContext)> {
) -> Result<(ParserState, CompilerContext)> {
#RequireNodeType<Node, (EvaluatableStatement, CompilerContext)>(
node: node, type: "parserTransitionStatement", nice_type_name: "parser transition statement"
@@ -114,19 +114,40 @@ public struct Parser {
// If the next node is an identifier, we have the simple form ...
if next_node.nodeType == "identifier" {
let maybe_parsed_next_state = Identifier.Compile(
let maybe_parsed_next_state_id = Identifier.Compile(
node: next_node, withContext: context)
if case .Ok(let next_state) = maybe_parsed_next_state {
return .Ok(
(
ParserStateDirectTransition(
name: state_identifier, withStatements: stmts, withNextState: next_state), context
))
if case .Ok(let next_state_id) = maybe_parsed_next_state_id {
if case .Ok(let next_state) = context.instances.lookup(identifier: next_state_id) {
switch next_state {
case (_, .some(let instance)):
return .Ok(
(
ParserStateDirectTransition(
name: state_identifier,
withNextState: instance.dataValue() as! InstantiatedParserState,
withStatements: stmts), context
))
case (_, .none):
return .Ok(
(
ParserStateDirectTransition(
name: state_identifier,
withNextStateIdentifier: next_state_id, withStatements: stmts), context
))
}
} else {
return .Error(
Error(
withMessage:
"\(next_state_id) does not name a parser state in scope"
))
}
} else {
return .Error(
Error(
withMessage:
"Could not parse the next state in a transition statement: \(maybe_parsed_next_state.error()!)"
"Could not parse the next state in a transition statement: \(maybe_parsed_next_state_id.error()!)"
))
}
}
@@ -139,8 +160,9 @@ public struct Parser {
.Ok(
(
ParserStateSelectTransition(
name: state_identifier, withStatements: stmts,
withTransitioniExpression: tse as! SelectExpression), context
name: state_identifier, withTransitionExpression: tse as! SelectExpression,
withStatements: stmts,
), context
))
case .Error(let e): .Error(e)
}
@@ -189,7 +211,7 @@ public struct Parser {
public struct State {
static func Compile(
node: Node, withContext context: CompilerContext
) -> Result<(InstantiatedParserState, CompilerContext)> {
) -> Result<(ParserState, CompilerContext)> {
var walker = Walker(node: node)
var current_node: Node? = .none
@@ -205,7 +227,7 @@ public struct Parser {
#MustOr(
result: current_node, thing: walker.getNext(),
or: Result<(InstantiatedParserState, CompilerContext)>.Error(
or: Result<(ParserState, CompilerContext)>.Error(
ErrorWithLocation(
sourceLocation: node.toSourceLocation(),
withError: "Missing elements in parser state declaration")))
@@ -223,7 +245,7 @@ public struct Parser {
walker.next()
#MustOr(
result: current_node, thing: walker.getNext(),
or: Result<(InstantiatedParserState, CompilerContext)>.Error(
or: Result<(ParserState, CompilerContext)>.Error(
ErrorWithLocation(
sourceLocation: node.toSourceLocation(),
withError: "Missing elements in parser state declaration")))
@@ -239,7 +261,7 @@ public struct Parser {
walker.next()
#MustOr(
result: current_node, thing: walker.getNext(),
or: Result<(InstantiatedParserState, CompilerContext)>.Error(
or: Result<(ParserState, CompilerContext)>.Error(
ErrorWithLocation(
sourceLocation: node.toSourceLocation(), withError: "Missing body of state declaration")
))
@@ -272,7 +294,7 @@ public struct Parser {
#MustOr(
result: current_node, thing: walker.getNext(),
or: Result<(InstantiatedParserState, CompilerContext)>.Error(
or: Result<(ParserState, CompilerContext)>.Error(
ErrorWithLocation(
sourceLocation: node.toSourceLocation(),
withError: "Missing transition statement of state declaration")))
+19 -5
View File
@@ -24,18 +24,30 @@ import TreeSitterP4
public struct Program {
public static func Compile(_ source: String) -> Result<P4Lang.Program> {
return Program.Compile(source, withGlobalInstances: .none, withGlobalTypes: .none, withFFIs: [])
// Certain names are always in scope during compilation.
var globals = StaticVarValueScopes().enter()
globals = globals.declare(
identifier: accept.state().getName(),
withValue: (P4QualifiedType(accept.type()), P4Value(accept))
)
.declare(
identifier: reject.state.getName(),
withValue: (P4QualifiedType(reject.type()), P4Value(reject)))
return Program.Compile(
source, withGlobalInstances: globals, withGlobalTypes: .none, withFFIs: [])
}
public static func Compile(
_ source: String, withGlobalInstances globalInstances: VarTypeScopes
_ source: String, withGlobalInstances globalInstances: StaticVarValueScopes
) -> Result<P4Lang.Program> {
return Program.Compile(
source, withGlobalInstances: globalInstances, withGlobalTypes: .none, withFFIs: [])
}
public static func Compile(
_ source: String, withGlobalInstances globalInstances: VarTypeScopes?,
_ source: String, withGlobalInstances globalInstances: StaticVarValueScopes?,
withGlobalTypes globalTypes: TypeTypeScopes?, withFFIs ffis: [P4FFI] = Array()
) -> Result<P4Lang.Program> {
@@ -122,8 +134,10 @@ public struct Program {
// Any of the instances that are in the top-level scope should go into the program!
program.instances = Array(
compilation_context.instances.map { (_, v) in
v
compilation_context.instances.filter { (_, v) in
v.1 != nil
}.map { (_, v) in
v.1!
})
// Any of the types that are in the top-level scope should go into the program!
+1 -1
View File
@@ -255,7 +255,7 @@ extension VariableDeclarationStatement: CompilableStatement {
// Context with updated names to include the newly declared name.
context.update(
newInstances: context.instances.declare(
identifier: parsed_variablename, withValue: declaration_p4_type))
identifier: parsed_variablename, withValue: (declaration_p4_type, .none)))
)
)
}
+229 -193
View File
@@ -41,209 +41,234 @@ public struct ParserAssignmentStatement {
///
/// Note: A P4 Parser State is both a type and a value.
/// This "bare" parser state represents the state more as a type than a value.
public class ParserState: P4Type, P4DataValue, Equatable, CustomStringConvertible {
public class ParserState: P4Type, Equatable, CustomStringConvertible {
let name: Identifier
public let statements: [EvaluatableStatement]
public static func == (lhs: ParserState, rhs: ParserState) -> Bool {
// Two "bare" parser states are always equal.
return true
return lhs.eq(rhs: rhs)
}
public func eq(rhs: any Common.P4Type) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
public func type() -> any Common.P4Type {
return self
}
// Any operation between two "bare" parser states is always true.
public func eq(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
public func lt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
public func lte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
public func gt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
public func gte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case is ParserState: true
case let rrhs as ParserState: self.name == rrhs.name
default: false
}
}
public var description: String {
return "Bare Parser State"
return "Parser State named \(self.name)"
}
public func getName() -> Identifier {
return self.name
}
public func getStatements() -> [EvaluatableStatement] {
return self.statements
}
/// Construct a ParserState
public init() {}
public init(_ name: Identifier, _ statements: [EvaluatableStatement] = Array()) {
self.name = name
self.statements = statements
}
public func def() -> P4DataValue? {
return .none
}
public func instantiate(_ name: Identifier) -> InstantiatedParserState? {
return .none
}
}
/// Instantiated Parser State
///
/// A parser state is both a type and a value. The Instantiated
/// Parser State is the base class for parser states that act more
/// as a value than a type.
public class InstantiatedParserState: ParserState {
public static func == (lhs: InstantiatedParserState, rhs: InstantiatedParserState) -> Bool {
return lhs.state == rhs.state
}
public class _AnyParserState: ParserState {
public override func eq(rhs: any Common.P4Type) -> Bool {
return switch rhs {
case is ParserState: true
default: false
}
}
}
public override func type() -> any Common.P4Type {
return self
nonisolated(unsafe) public let AnyParserState = _AnyParserState(Identifier(name: "AnyParserState"))
public class ParserStateDirectTransition: ParserState {
public let next_state: InstantiatedParserState?
public let next_state_identifier: Identifier?
/// Construct a ParserState
public init(
name: Identifier, withNextState next_state: InstantiatedParserState,
withStatements stmts: [EvaluatableStatement] = Array(),
) {
self.next_state = next_state
self.next_state_identifier = .none
super.init(name, stmts)
}
public override func eq(rhs: any Common.P4DataValue) -> Bool {
public init(
name: Identifier, withNextStateIdentifier next_state_id: Identifier,
withStatements stmts: [EvaluatableStatement] = Array(),
) {
self.next_state = .none
self.next_state_identifier = next_state_id
super.init(name, stmts)
}
public override func instantiate(_ name: Identifier) -> InstantiatedParserState? {
return if let next_state = self.next_state {
ParserStateDirectTransitionValue(name: name, withState: self, withNextState: next_state)
} else {
ParserStateDirectTransitionValue(
name: name, withState: self, withNextStateIdentifier: self.next_state_identifier!)
}
}
}
public class ParserStateNoTransition: ParserState {
/// Construct a ParserState
public init(
name: Identifier, withStatements stmts: [EvaluatableStatement] = Array(),
) {
super.init(name, stmts)
}
public override func instantiate(_ name: Identifier) -> InstantiatedParserState? {
return ParserStateNoTransitionValue(name: name, withState: self)
}
}
public class ParserStateSelectTransition: ParserState {
public let te: SelectExpression
public init(
name: Identifier, withTransitionExpression te: SelectExpression,
withStatements stmts: [EvaluatableStatement] = Array()
) {
self.te = te
super.init(name, stmts)
}
public override func instantiate(_ name: Identifier) -> InstantiatedParserState? {
return ParserStateSelectTransitionValue(name: name, withState: self, withSelectExpression: te)
}
}
/// Instantiated Parser State
///
public class InstantiatedParserState: P4DataValue {
public static func == (lhs: InstantiatedParserState, rhs: InstantiatedParserState) -> Bool {
return lhs.state == rhs.state
}
public func type() -> any Common.P4Type {
return self.state
}
public func eq(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let other as InstantiatedParserState: self.state == other.state
default: false
}
}
public override func lt(rhs: any Common.P4DataValue) -> Bool {
public func lt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let other as InstantiatedParserState: self.state < other.state
case let other as InstantiatedParserState: self.state.getName() < other.state.getName()
default: false
}
}
public override func lte(rhs: any Common.P4DataValue) -> Bool {
public func lte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let other as InstantiatedParserState: self.state <= other.state
case let other as InstantiatedParserState: self.state.getName() <= other.state.getName()
default: false
}
}
public override func gt(rhs: any Common.P4DataValue) -> Bool {
public func gt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let other as InstantiatedParserState: self.state > other.state
case let other as InstantiatedParserState: self.state.getName() > other.state.getName()
default: false
}
}
public override func gte(rhs: any Common.P4DataValue) -> Bool {
public func gte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let other as InstantiatedParserState: self.state >= other.state
case let other as InstantiatedParserState: self.state.getName() >= other.state.getName()
default: false
}
}
public private(set) var state: Identifier
public private(set) var statements: [EvaluatableStatement]
public private(set) var state: ParserState
public private(set) var name: Identifier
public override var description: String {
return "Name: \(state)"
public var description: String {
return "Instance of state of type \(state) named \(name)"
}
/// Construct a ParserState
public init(
name: Identifier, withStatements stmts: [EvaluatableStatement],
) {
state = name
statements = stmts
}
/// (private) constructor (no transition)
///
/// accept and reject are the only final states and they are constructed internally.
private init(name: Identifier) {
state = name
statements = Array()
}
public override func def() -> any P4DataValue {
return InstantiatedParserState(name: Identifier(name: ""))
public init(_ name: Identifier, _ state: ParserState) {
self.name = name
self.state = state
}
}
public class ParserStateDirectTransition: InstantiatedParserState {
private let next_state: Identifier
public class ParserStateDirectTransitionValue: InstantiatedParserState {
public let next_state: InstantiatedParserState?
public let next_state_identifier: Identifier?
public init(
name: Identifier, withStatements stmts: [EvaluatableStatement],
withNextState next_state: Identifier
name: Identifier, withState state: ParserStateDirectTransition,
withNextState next_state: InstantiatedParserState
) {
self.next_state = next_state
super.init(name: name, withStatements: stmts)
}
public override var description: String {
return "State (Name: \(super.state) (direct transition))"
}
public func get_next_state() -> Identifier {
return self.next_state
}
}
public class ParserStateNoTransition: InstantiatedParserState {
public override init(name: Identifier, withStatements stmts: [any EvaluatableStatement]) {
super.init(name: name, withStatements: stmts)
}
public override var description: String {
return "State (Name: \(super.state) (no transition))"
}
}
public class ParserStateSelectTransition: InstantiatedParserState {
public let selectExpression: SelectExpression
public override var description: String {
return "State (Name: \(super.state) (select transition))"
self.next_state_identifier = .none
super.init(name, state)
}
public init(
name: Identifier, withStatements stmts: [any EvaluatableStatement],
withTransitioniExpression te: SelectExpression
name: Identifier, withState state: ParserStateDirectTransition,
withNextStateIdentifier next_state_id: Identifier
) {
self.selectExpression = te
super.init(name: name, withStatements: stmts)
self.next_state = .none
self.next_state_identifier = next_state_id
super.init(name, state)
}
}
nonisolated(unsafe) public let accept = ParserStateNoTransition(
public class ParserStateNoTransitionValue: InstantiatedParserState {
public init(name: Identifier, withState state: ParserStateNoTransition) {
super.init(name, state)
}
}
public class ParserStateSelectTransitionValue: InstantiatedParserState {
public let te: SelectExpression
public init(
name: Identifier, withState state: ParserStateSelectTransition,
withSelectExpression te: SelectExpression
) {
self.te = te
super.init(name, state)
}
}
nonisolated(unsafe) private let accept_type = ParserStateNoTransition(
name: Identifier(name: "accept"), withStatements: [])
nonisolated(unsafe) public let reject = ParserStateNoTransition(
nonisolated(unsafe) private let reject_type = ParserStateNoTransition(
name: Identifier(name: "reject"), withStatements: [])
nonisolated(unsafe) public let accept = ParserStateNoTransitionValue(
name: Identifier(name: "accept"), withState: accept_type)
nonisolated(unsafe) public let reject = ParserStateNoTransitionValue(
name: Identifier(name: "reject"), withState: reject_type)
public struct ParserStates {
public var states: [InstantiatedParserState] = Array()
public var states: [ParserState] = Array()
public func count() -> Int {
return states.count
@@ -251,71 +276,28 @@ public struct ParserStates {
public func find(withIdentifier id: Identifier) -> ParserState? {
for state in states {
if state.state == id {
if state.getName() == id {
return .some(state)
}
}
return .none
}
public init() {
self.states = Array()
}
private init(withStates states: [InstantiatedParserState]) {
public init(_ states: [ParserState] = Array()) {
self.states = states
}
public func append(state: InstantiatedParserState) -> ParserStates {
public func append(state: ParserState) -> ParserStates {
var new_states = self.states
new_states.append(state)
return ParserStates(withStates: new_states)
return ParserStates(new_states)
}
}
/// A P4 Parser
///
/// Note: A Parser is both a type _and_ a value.
public struct Parser: P4Type, P4DataValue {
public func type() -> any Common.P4Type {
return self
}
public func eq(rhs: any Common.P4Type) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name == parser_rhs.name
default: false
}
}
public func lt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name < parser_rhs.name
default: false
}
}
public func lte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name <= parser_rhs.name
default: false
}
}
public func gt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name > parser_rhs.name
default: false
}
}
public func gte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name >= parser_rhs.name
default: false
}
}
/// Note: A Parser is a type
public struct Parser: P4Type {
public var states: ParserStates
public var name: Identifier
@@ -334,19 +316,7 @@ public struct Parser: P4Type, P4DataValue {
}
public func findStartState() -> ParserState? {
for state in states.states {
if state.state == Identifier(name: "start") {
return state
}
}
return .none
}
public func eq(rhs: any P4DataValue) -> Bool {
return switch rhs {
case let other as Parser: self.name == other.name
default: false
}
return self.states.find(withIdentifier: Identifier(name: "start"))
}
public var description: String {
@@ -356,9 +326,75 @@ public struct Parser: P4Type, P4DataValue {
public func def() -> P4DataValue? {
return .none
}
public func eq(rhs: any Common.P4Type) -> Bool {
return switch rhs {
case let parser_rhs as Parser: self.name == parser_rhs.name
default: false
}
}
public func instantiate(_ name: Identifier) -> ParserValue {
return ParserValue(self, name)
}
}
/// Launder a parser state into an instantiated parser state.
public func AsInstantiatedParserState(_ state: ParserState) -> InstantiatedParserState {
return state as! InstantiatedParserState
/// A instance of a P4 Parser
///
public struct ParserValue: P4DataValue {
public func type() -> P4Type {
return self.tipe
}
public func eq(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let rrhs as ParserValue: rrhs.type().eq(rhs: self.type()) && self.name == rrhs.name
default: false
}
}
public func lt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let rrhs as ParserValue: rrhs.type().eq(rhs: self.type()) && self.name < rrhs.name
default: false
}
}
public func lte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let rrhs as ParserValue: rrhs.type().eq(rhs: self.type()) && self.name <= rrhs.name
default: false
}
}
public func gt(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let rrhs as ParserValue: rrhs.type().eq(rhs: self.type()) && self.name > rrhs.name
default: false
}
}
public func gte(rhs: any Common.P4DataValue) -> Bool {
return switch rhs {
case let rrhs as ParserValue: rrhs.type().eq(rhs: self.type()) && self.name >= rrhs.name
default: false
}
}
public var tipe: Parser
public var name: Identifier
public init(_ tipe: Parser, _ name: Identifier) {
self.tipe = tipe
self.name = name
}
public var description: String {
return "Parser \(self.name) of type \(self.tipe)"
}
public func def() -> P4DataValue? {
return self.tipe.def()
}
}
+6 -6
View File
@@ -28,7 +28,7 @@ public struct ExpressionStatement {
public struct Program {
public var types: [P4Type] = Array()
public var externs: [P4Type] = Array()
public var instances: [P4QualifiedType] = Array()
public var instances: [P4Value] = Array()
/// Type of closure for filtering results from ``Program/InstancesWithTypes(_:)``
public typealias TypeFilter = (P4QualifiedType) -> Bool
@@ -36,7 +36,7 @@ public struct Program {
public typealias DataTypeFilter = (P4Type) -> Bool
/// Retrieve global instances in the compiled P4 program.
public func InstancesWithTypes() -> [P4QualifiedType] {
public func InstancesWithTypes() -> [P4Value] {
return self.instances
}
@@ -52,9 +52,9 @@ public struct Program {
///
/// @Snippet(path: "use-program-instanceswithtypes", slice: "include")
///
public func InstancesWithTypes(_ filter: TypeFilter) -> [P4QualifiedType] {
public func InstancesWithTypes(_ filter: TypeFilter) -> [P4Value] {
return self.instances.filter { instance in
filter(instance)
filter(instance.type())
}
}
@@ -112,8 +112,8 @@ public struct Program {
}
public func find_parser(withName name: Identifier) -> Result<Parser> {
for instance in self.instances {
guard let parser = instance.baseType() as? Parser else {
for instance in self.types {
guard let parser = instance as? Parser else {
continue
}
if parser.name == name {
+12 -5
View File
@@ -72,14 +72,16 @@ public struct CodeGenerator: LanguageVisitor {
}
}
/// TODO: Handle instances.
/*
result = Fold(
input: v.instances, initial: result
) { (current, acc) in
return switch acc {
case .Ok(let acc): acc.getVisitorDriver().visit(current.baseType(), context: acc)
case .Ok(let acc): acc.getVisitorDriver().visit(current, context: acc)
case .Error(let e): .Error(e)
}
}
}*/
result = result.map {
.Ok($0.next(uc: $0.getUserContext().append("]")))
@@ -115,7 +117,7 @@ public struct CodeGenerator: LanguageVisitor {
}
public func visit(
_ v: InstantiatedParserState, _ c: VisitorContext<Generated>
_ v: ParserState, _ c: VisitorContext<Generated>
) -> Result<VisitorContext<Generated>> {
let direct_transition_codegen = {
(
@@ -135,14 +137,14 @@ public struct CodeGenerator: LanguageVisitor {
(
state: ParserStateSelectTransition, c: VisitorContext<Generated>
) -> Result<VisitorContext<Generated>> in
return switch self.visit(state.selectExpression, c.next(uc: c.getUserContext().append("["))) {
return switch self.visit(state.te, c.next(uc: c.getUserContext().append("["))) {
case .Ok(let res): .Ok(res.next(uc: res.getUserContext().append("]")))
case .Error(let e): .Error(e)
}
}
var initial = "{"
initial += "name: \"\(v.state)\","
initial += "name: \"\(v.getName())\","
initial += "transitions: "
let result: Result<VisitorContext<Generated>> =
@@ -281,4 +283,9 @@ public struct CodeGenerator: LanguageVisitor {
) -> Result<VisitorContext<Generated>> {
return .Ok(c)
}
public func visit(
_ parser_state: P4Lang.InstantiatedParserState, _ c: P4Lang.VisitorContext<Generated>
) -> Common.Result<P4Lang.VisitorContext<Generated>> {
return .Ok(c)
}
}
+7 -7
View File
@@ -24,7 +24,7 @@ extension SelectCaseExpression: EvaluatableExpression {
}
public func type() -> P4QualifiedType {
return P4QualifiedType(ParserState())
return P4QualifiedType(AnyParserState)
}
}
@@ -50,7 +50,7 @@ extension SelectExpression: EvaluatableExpression {
}
public func type() -> P4QualifiedType {
return P4QualifiedType(ParserState())
return P4QualifiedType(AnyParserState)
}
}
@@ -79,18 +79,18 @@ extension TypedIdentifier: EvaluatableLValueExpression {
}
public func check(
to: any Common.EvaluatableExpression, inScopes scopes: Common.VarTypeScopes
to: any Common.EvaluatableExpression, inScopes scopes: Common.StaticVarValueScopes
) -> Result<()> {
guard case .Ok(let type) = scopes.lookup(identifier: self) else {
return .Error(Error(withMessage: "Cannot assign to identifier not in scope"))
}
return switch type.assignableFromType(to.type()) {
return switch type.0.assignableFromType(to.type()) {
case TypeCheckResults.IncompatibleTypes:
.Error(
Error(
withMessage:
"Cannot assign value with type \(to.type()) to identifier \(self) with type \(type)"))
"Cannot assign value with type \(to.type()) to identifier \(self) with type \(type.0)"))
case TypeCheckResults.ReadOnly:
.Error(
Error(
@@ -318,7 +318,7 @@ extension ArrayAccessExpression: EvaluatableLValueExpression {
}
public func check(
to: any Common.EvaluatableExpression, inScopes scopes: Common.VarTypeScopes
to: any Common.EvaluatableExpression, inScopes scopes: Common.StaticVarValueScopes
) -> Common.Result<()> {
return switch self.type.value_type().assignableFromType(to.type()) {
@@ -426,7 +426,7 @@ extension FieldAccessExpression: EvaluatableLValueExpression {
}
public func check(
to: any Common.EvaluatableExpression, inScopes scopes: Common.VarTypeScopes
to: any Common.EvaluatableExpression, inScopes scopes: Common.StaticVarValueScopes
) -> Common.Result<()> {
return switch self.field.type().assignableFromType(to.type()) {
case TypeCheckResults.IncompatibleTypes:
+27 -31
View File
@@ -39,14 +39,14 @@ extension ParserAssignmentStatement: EvaluatableStatement {
}
}
extension ParserStateDirectTransition: EvaluatableParserState {
extension ParserStateDirectTransitionValue: EvaluatableParserState {
public func execute(
program: Common.ProgramExecution
) -> (any EvaluatableParserState, Common.ProgramExecution) {
var program = program.enter_scope()
let (control_flow, next_execution) = program.evaluator.ExecuteStatements(
statements, inExecution: program)
self.state.statements, inExecution: program)
switch control_flow {
case .Next: program = next_execution
@@ -59,17 +59,7 @@ extension ParserStateDirectTransition: EvaluatableParserState {
)
}
let res = program.scopes.lookup(identifier: get_next_state())
if case .Ok(let value) = res {
if value.type().baseType().eq(rhs: self) {
return (value.dataValue() as! EvaluatableParserState, program.exit_scope())
}
}
program = program.setError(error: res.error()!).exit_scope()
return (self, program.exit_scope())
return (self.next_state as! EvaluatableParserState, program.exit_scope())
}
public func done() -> Bool {
@@ -77,11 +67,11 @@ extension ParserStateDirectTransition: EvaluatableParserState {
}
public func state() -> P4Lang.ParserState {
return self
return self.state
}
}
extension ParserStateNoTransition: EvaluatableParserState {
extension ParserStateNoTransitionValue: EvaluatableParserState {
public func execute(
program: Common.ProgramExecution
) -> (any EvaluatableParserState, Common.ProgramExecution) {
@@ -93,18 +83,18 @@ extension ParserStateNoTransition: EvaluatableParserState {
}
public func state() -> P4Lang.ParserState {
return self
return self.state
}
}
extension ParserStateSelectTransition: EvaluatableParserState {
extension ParserStateSelectTransitionValue: EvaluatableParserState {
public func execute(
program: Common.ProgramExecution
) -> (any EvaluatableParserState, Common.ProgramExecution) {
var program = program.enter_scope()
let (control_flow, next_execution) = program.evaluator.ExecuteStatements(
statements, inExecution: program)
self.state.statements, inExecution: program)
switch control_flow {
case .Next: program = next_execution
case .Error: return (reject, next_execution.exit_scope())
@@ -116,10 +106,9 @@ extension ParserStateSelectTransition: EvaluatableParserState {
)
}
//switch self.selectExpression.evaluate(execution: program) {
switch program.evaluator.EvaluateExpression(self.selectExpression, inExecution: program) {
switch program.evaluator.EvaluateExpression(self.te, inExecution: program) {
case (.Ok(let value), let program):
if value.type().baseType().eq(rhs: self) {
if AnyParserState.eq(rhs: value.type().baseType()) {
return (value.dataValue() as! EvaluatableParserState, program.exit_scope())
} else {
return (
@@ -137,11 +126,11 @@ extension ParserStateSelectTransition: EvaluatableParserState {
}
public func state() -> P4Lang.ParserState {
return self
return self.state
}
}
extension Parser: LibraryCallable {
extension ParserValue: LibraryCallable {
public typealias T = InstantiatedParserState
public func call(
execution: Common.ProgramExecution, arguments: ArgumentList
@@ -149,10 +138,10 @@ extension Parser: LibraryCallable {
var execution = execution.enter_scope()
execution = execution.declare(
identifier: AsInstantiatedParserState(accept.state()).state,
identifier: accept.state().getName(),
withValue: P4Value(accept, P4QualifiedType.ReadOnly(accept.type())))
execution = execution.declare(
identifier: AsInstantiatedParserState(reject.state()).state,
identifier: reject.state().getName(),
withValue: P4Value(reject, P4QualifiedType.ReadOnly(reject.type())))
// Add initial values to the global scope
@@ -161,13 +150,20 @@ extension Parser: LibraryCallable {
}
// First, add every state to the scope!
for state in self.states.states {
for state in self.tipe.states.states {
guard let instantiated_state = state.instantiate(state.getName()) else {
return (
reject,
execution.setError(error: Error(withMessage: "Could not instantiate \(state.getName())"))
)
}
execution = execution.declare(
identifier: state.state, withValue: P4Value(state))
identifier: state.getName(), withValue: P4Value(instantiated_state))
}
guard let _current_state = self.findStartState(),
var current_state = _current_state as? EvaluatableParserState
guard let _current_state = self.tipe.findStartState(),
var current_state = _current_state.instantiate(Identifier(name: "start"))
as? EvaluatableParserState
else {
return (
reject, execution.setError(error: Error(withMessage: "Could not find the start state"))
@@ -181,12 +177,12 @@ extension Parser: LibraryCallable {
while !current_state.done() && !current_execution.hasError() {
(current_state, current_execution) = current_state.execute(program: current_execution)
}
return (.Ok(P4Value(AsInstantiatedParserState(current_state.state()))), current_execution)
return (.Ok(P4Value((current_state))), current_execution)
}
return
switch Call(
body: call_body, withArguments: arguments, withParameters: parameters,
body: call_body, withArguments: arguments, withParameters: self.tipe.parameters,
inExecution: execution)
{
case (.Ok(let value), let updated_execution):
+5 -4
View File
@@ -37,18 +37,19 @@ public struct Runtime<U, T: LibraryCallable<U>>: CustomStringConvertible {
/// Create a parser runtime from a P4 program
public static func create(
program: P4Lang.Program
) -> Result<Runtime<InstantiatedParserState, Parser>> {
) -> Result<Runtime<InstantiatedParserState, ParserValue>> {
return Runtime.create(program: program, withGlobalValues: .none)
}
public static func create(
program: P4Lang.Program, withGlobalValues initial: VarValueScopes?
) -> Result<Runtime<InstantiatedParserState, Parser>> {
) -> Result<Runtime<InstantiatedParserState, ParserValue>> {
return switch program.starting_parser() {
case .Ok(let parser):
.Ok(
P4Runtime.Runtime<InstantiatedParserState, Parser>(
callable: parser, withGlobalValues: initial))
P4Runtime.Runtime<InstantiatedParserState, ParserValue>(
callable: parser.instantiate(Identifier(name: "starting_parser")),
withGlobalValues: initial))
case .Error(let error): .Error(error)
}
}