Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing compiler changes #789

Merged
merged 1 commit into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Src/PChecker/CheckerCore/Actors/Events/Event.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
[DataContract]
public abstract class Event
{
public int Loc { get; set; }
public string? Sender;

Check warning on line 14 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 14 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 14 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Windows

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 14 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 14 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
public string? Receiver;

Check warning on line 15 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 15 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 15 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Windows

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 15 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 15 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
public string? State;

Check warning on line 16 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 16 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-MacOS

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 16 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Windows

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 16 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 16 in Src/PChecker/CheckerCore/Actors/Events/Event.cs

View workflow job for this annotation

GitHub Actions / Build-And-Test-Ubuntu

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
public int Index;
}
Expand Down
8 changes: 3 additions & 5 deletions Src/PChecker/CheckerCore/PRuntime/PEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ namespace PChecker.PRuntime
{
public class PEvent : Event, IPrtValue
{
public PEvent(int loc) : base()
public PEvent() : base()
{
Loc = loc;
}

public PEvent(IPrtValue payload, int loc) : base()
public PEvent(IPrtValue payload) : base()
{
Payload = payload;
Loc = loc;
}

public IPrtValue Payload { get; }
Expand Down Expand Up @@ -52,7 +50,7 @@ public override string ToString()

public class PHalt : PEvent
{
public PHalt(IPrtValue payload, int loc) : base(payload, loc)
public PHalt(IPrtValue payload) : base(payload)
{
}
}
Expand Down
8 changes: 4 additions & 4 deletions Src/PChecker/CheckerCore/PRuntime/PMachine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public void TrySendEvent(PMachineValue target, Event ev, object payload = null)
Assert(target.Permissions.Contains(ev.GetType().Name),
$"Event {ev.GetType().Name} is not in the permissions set of the target machine");
var oneArgConstructor = ev.GetType().GetConstructors().First(x => x.GetParameters().Length > 0);
ev = (Event)oneArgConstructor.Invoke(new[] { payload , ev.Loc});
ev = (Event)oneArgConstructor.Invoke(new[] { payload });

ev.Sender = Id.ToString();
ev.Receiver = target.Id.ToString();
Expand All @@ -96,7 +96,7 @@ public void TryRaiseEvent(Event ev, object payload = null)
{
Assert(ev != null, "Machine cannot raise a null event");
var oneArgConstructor = ev.GetType().GetConstructors().First(x => x.GetParameters().Length > 0);
ev = (Event)oneArgConstructor.Invoke(new[] { payload, ev.Loc });
ev = (Event)oneArgConstructor.Invoke(new[] { payload });
RaiseEvent(ev);
throw new PNonStandardReturnException { ReturnKind = NonStandardReturn.Raise };
}
Expand Down Expand Up @@ -190,7 +190,7 @@ public void Announce(Event ev, object payload = null)
}

var oneArgConstructor = ev.GetType().GetConstructors().First(x => x.GetParameters().Length > 0);
var @event = (Event)oneArgConstructor.Invoke(new[] { payload, ev.Loc });
var @event = (Event)oneArgConstructor.Invoke(new[] { payload });
var pText = payload == null ? "" : $" with payload {((IPrtValue)payload).ToEscapedString()}";

Logger.WriteLine($"<AnnounceLog> '{Id}' announced event '{ev.GetType().Name}'{pText}.");
Expand Down Expand Up @@ -255,7 +255,7 @@ public object ToDict()

public class InitializeParametersEvent : PEvent
{
public InitializeParametersEvent(InitializeParameters payload) : base(payload, 0)
public InitializeParametersEvent(InitializeParameters payload) : base(payload)
{
}
}
Expand Down
105 changes: 17 additions & 88 deletions Src/PCompiler/CompilerCore/Backend/CSharp/CSharpCodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ public class CSharpCodeGenerator : ICodeGenerator
/// </summary>
public bool HasCompilationStage => true;

private int _sendEventIndex = 0;

public void Compile(ICompilerConfiguration job)
{
var csprojName = $"{job.ProjectName}.csproj";
Expand Down Expand Up @@ -486,8 +484,8 @@ private void WriteEvent(CompilationContext context, StringWriter output, PEvent
var payloadType = GetCSharpType(pEvent.PayloadType, true);
context.WriteLine(output, $"internal partial class {declName} : PEvent");
context.WriteLine(output, "{");
context.WriteLine(output, $"public {declName}() : base(-1) {{}}");
context.WriteLine(output, $"public {declName}({payloadType} payload, int loc): base(payload, loc)" + "{ }");
context.WriteLine(output, $"public {declName}() : base() {{}}");
context.WriteLine(output, $"public {declName} ({payloadType} payload): base(payload)" + "{ }");
context.WriteLine(output, $"public override IPrtValue Clone() {{ return new {declName}();}}");
context.WriteLine(output, "}");

Expand All @@ -512,12 +510,12 @@ private void WriteMachine(CompilationContext context, StringWriter output, Machi
var cTorType = GetCSharpType(machine.PayloadType, true);
context.Write(output, "public class ConstructorEvent : PEvent");
context.Write(output, "{");
context.Write(output, $"public ConstructorEvent({cTorType} val, int loc) : base(val, loc) {{ }}");
context.Write(output, $"public ConstructorEvent({cTorType} val) : base(val) {{ }}");
context.WriteLine(output, "}");
context.WriteLine(output);

context.WriteLine(output,
$"protected override Event GetConstructorEvent(IPrtValue value) {{ return new ConstructorEvent(({cTorType})value, {_sendEventIndex++}); }}");
$"protected override Event GetConstructorEvent(IPrtValue value) {{ return new ConstructorEvent(({cTorType})value); }}");

// create the constructor to initialize the sends, creates and receives list
WriteMachineConstructor(context, output, machine);
Expand Down Expand Up @@ -708,7 +706,7 @@ private void WriteFunction(CompilationContext context, StringWriter output, Func

var staticKeyword = isStatic ? "static " : "";
var asyncKeyword = isAsync ? "async " : "";
var returnType = function.Role != FunctionRole.Scenario ? GetCSharpType(signature.ReturnType) : "int";
var returnType = GetCSharpType(signature.ReturnType);

if (isAsync)
{
Expand All @@ -721,10 +719,6 @@ private void WriteFunction(CompilationContext context, StringWriter output, Func
{
functionParameters = "Event currentMachine_dequeuedEvent";
}
else if (function.Role == FunctionRole.Scenario)
{
functionParameters = "List<Event> events";
}
else
{
functionParameters = string.Join(
Expand All @@ -733,7 +727,7 @@ private void WriteFunction(CompilationContext context, StringWriter output, Func
$"{GetCSharpType(param.Type)} {context.Names.GetNameForDecl(param)}"));
}

if (isStatic && function.Role != FunctionRole.Scenario) // then we need to generate two versions of the function
if (isStatic) // then we need to generate two versions of the function
{
// for machine
var seperator = functionParameters == "" ? "" : ", ";
Expand Down Expand Up @@ -789,69 +783,14 @@ private void WriteFunctionBody(CompilationContext context, StringWriter output,
$"{GetCSharpType(type, true)} {context.Names.GetNameForDecl(local)} = {GetDefaultValue(type)};");
}

if (function.Role != FunctionRole.Scenario)
{
foreach (var bodyStatement in function.Body.Statements)
{
WriteStmt(context: context, output: output, function: function, stmt: bodyStatement);
}
}
else
{
WriteScenario(context, output, function);
}


context.WriteLine(output, "}");
}

private void WriteScenario(CompilationContext context, StringWriter output, Function function)
{
int numOfStmt = function.Body.Statements.Count + 1;
context.WriteLine(output, $"int state = {numOfStmt};");
var eventPredicates = string.Join(" or ", function.Signature.ParameterEvents.Select(it => it.Name));
context.WriteLine(output, $"events = events.Where(it => it is {eventPredicates}).ToList();");
WriteConstraintsRecursive(context, output, function, 0, new HashSet<Variable>(), 0);
context.WriteLine(output, "return state;");
}

private void WriteConstraintsRecursive(CompilationContext context, StringWriter output, Function function, int index, HashSet<Variable> visitedVariables, int satisfiedConstraints)
{
if (index >= function.Signature.Parameters.Count)
{
context.WriteLine(output, "return 1;");
return;
}
var param = function.Signature.Parameters[index];
var e = function.Signature.ParameterEvents[index];
visitedVariables.Add(param);
var start = index == 0 ? "0" : $"i{index - 1} + 1";
var paramName = context.Names.GetNameForDecl(param);
context.WriteLine(output, $"for (var i{index} = {start} ; i{index} < events.Count; i{index} ++) " + "{");
context.WriteLine(output, $"var {paramName}_obj = events[i{index}];");
context.WriteLine(output, $"if ({paramName}_obj is not {e.Name}) continue;");
context.WriteLine(output, $"var {paramName} = ((PEvent) {paramName}_obj).Payload;");

foreach (var bodyStatement in function.Body.Statements)
{
if (bodyStatement is ConstraintStmt stmt)
{
var variables = ConstraintVariableCollector.FindVariablesRecursive(stmt.Constraint);
if (variables.Contains(param) && visitedVariables.IsSupersetOf(variables))
{
context.Write(output, $"if (!(");
WriteExpr(context, output, stmt.Constraint);
context.WriteLine(output, $")) continue;");
satisfiedConstraints += 1;
context.WriteLine(output, $"state = Math.Min({function.Body.Statements.Count - satisfiedConstraints + 1}, state);");
}
}
WriteStmt(context: context, output: output, function: function, stmt: bodyStatement);
}
WriteConstraintsRecursive(context, output, function, index + 1, visitedVariables, satisfiedConstraints);

context.WriteLine(output, "}");
}


private void WriteStmt(CompilationContext context, StringWriter output, Function function, IPStmt stmt)
{
switch (stmt)
Expand Down Expand Up @@ -1240,19 +1179,9 @@ private void WriteLValue(CompilationContext context, StringWriter output, IPExpr
break;

case NamedTupleAccessExpr namedTupleAccessExpr:
if (ExprVisitor.ReservedEventFeilds.ContainsValue(namedTupleAccessExpr.Entry))
{
var type = GetCSharpType(namedTupleAccessExpr.Entry.Type);
context.Write(output, $"(({type}) (");
WriteExpr(context, output, namedTupleAccessExpr.SubExpr);
context.Write(output, $"_obj).{namedTupleAccessExpr.FieldName})");
}
else
{
context.Write(output, "((PrtNamedTuple)");
WriteExpr(context, output, namedTupleAccessExpr.SubExpr);
context.Write(output, $")[\"{namedTupleAccessExpr.FieldName}\"]");
}
context.Write(output, "((PrtNamedTuple)");
WriteExpr(context, output, namedTupleAccessExpr.SubExpr);
context.Write(output, $")[\"{namedTupleAccessExpr.FieldName}\"]");
break;

case SeqAccessExpr seqAccessExpr:
Expand Down Expand Up @@ -1296,9 +1225,9 @@ private void WriteExpr(CompilationContext context, StringWriter output, IPExpr p
context.Write(output, $"({negate}PrtValues.SafeEquals(");
if (PLanguageType.TypeIsOfKind(binOpExpr.Lhs.Type, TypeKind.Enum))
{
context.Write(output, "PrtValues.Box((long) ((PrtInt)");
context.Write(output, "PrtValues.Box((long) ");
WriteExpr(context, output, binOpExpr.Lhs);
context.Write(output, ")),");
context.Write(output, "),");
}
else
{
Expand All @@ -1308,9 +1237,9 @@ private void WriteExpr(CompilationContext context, StringWriter output, IPExpr p

if (PLanguageType.TypeIsOfKind(binOpExpr.Rhs.Type, TypeKind.Enum))
{
context.Write(output, "PrtValues.Box((long) ((PrtInt)");
context.Write(output, "PrtValues.Box((long) ");
WriteExpr(context, output, binOpExpr.Rhs);
context.Write(output, "))");
context.Write(output, ")");
}
else
{
Expand Down Expand Up @@ -1459,7 +1388,7 @@ private void WriteExpr(CompilationContext context, StringWriter output, IPExpr p
switch (eventName)
{
case "Halt":
context.Write(output, "new PHalt(" + _sendEventIndex++ + ")");
context.Write(output, "new PHalt()");
break;

case "DefaultEvent":
Expand All @@ -1468,7 +1397,7 @@ private void WriteExpr(CompilationContext context, StringWriter output, IPExpr p

default:
var payloadExpr = GetDefaultValue(eventRefExpr.Value.PayloadType);
context.Write(output, $"new {eventName}({payloadExpr}, {_sendEventIndex++})");
context.Write(output, $"new {eventName}({payloadExpr})");
break;
}

Expand Down
3 changes: 0 additions & 3 deletions Src/PCompiler/CompilerCore/Backend/IRTransformer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -567,9 +567,6 @@ private List<IPStmt> SimplifyStatement(IPStmt statement)
condCheck.Concat(SimplifyStatement(whileStmt.Body)));

return new List<IPStmt> { new WhileStmt(location, new BoolLiteralExpr(location, true), loopBody) };
// We do not rewrite constraint statements for now.
case ConstraintStmt constraintStmt:
return new List<IPStmt>() { constraintStmt };

default:
throw new ArgumentOutOfRangeException(nameof(statement));
Expand Down
1 change: 0 additions & 1 deletion Src/PCompiler/CompilerCore/Parser/PLexer.g4
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ MODULE : 'module' ;
IMPLEMENTATION : 'implementation' ;
TEST : 'test' ;
REFINES : 'refines' ;
SCENARIO : 'scenario' ;

// module constructors
COMPOSE : 'compose' ;
Expand Down
8 changes: 0 additions & 8 deletions Src/PCompiler/CompilerCore/Parser/PParser.g4
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ topDecl : typeDefDecl
| namedModuleDecl
| testDecl
| implementationDecl
| scenarioDecl
;


Expand Down Expand Up @@ -108,13 +107,6 @@ funDecl : FUN name=iden LPAREN funParamList? RPAREN (COLON type)? (CREATES inter
| FUN name=iden LPAREN funParamList? RPAREN (COLON type)? functionBody # PFunDecl
;

scenarioDecl : SCENARIO scenarioName=iden LPAREN scenarioParamList RPAREN scenarioBody;

scenarioParamList: scenarioParam (COMMA scenarioParam)*;
scenarioParam : name=iden COLON nonDefaultEvent;
scenarioBody : LBRACE expr (COMMA expr)* RBRACE;


stateDecl : START? temperature=(HOT | COLD)? STATE name=iden LBRACE stateBodyItem* RBRACE ;

stateBodyItem : ENTRY anonEventHandler # StateEntry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ public enum FunctionRole
EventHandler = 1 << 4,
ExitHandler = 1 << 5,
ReceiveHandler = 1 << 6,
Foreign = 1 << 7,
Scenario = 1 << 8,
Foreign = 1 << 7
}

public class Function : IPDecl, IHasScope
Expand All @@ -33,8 +32,7 @@ sourceNode is PParser.AnonEventHandlerContext ||
sourceNode is PParser.NoParamAnonEventHandlerContext ||
sourceNode is PParser.ReceiveStmtContext ||
sourceNode is PParser.WhileStmtContext ||
sourceNode is PParser.ForeachStmtContext ||
sourceNode is PParser.ScenarioDeclContext);
sourceNode is PParser.ForeachStmtContext);
Name = name;
SourceLocation = sourceNode;
CanCreate = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ namespace Plang.Compiler.TypeChecker.AST.Declarations
public class FunctionSignature
{
public List<Variable> Parameters { get; } = new List<Variable>();
// This is only used by scenarios.
public List<PEvent> ParameterEvents { get; } = new();
public IEnumerable<PLanguageType> ParameterTypes => Parameters.Select(ty => ty.Type);
public PLanguageType ReturnType { get; set; } = PrimitiveType.Null;
}
Expand Down

This file was deleted.

9 changes: 1 addition & 8 deletions Src/PCompiler/CompilerCore/TypeChecker/Analyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,7 @@ private static Scope BuildGlobalScope(ICompilerConfiguration config, PParser.Pro
{
DeclarationVisitor.PopulateDeclarations(config.Handler, globalScope, programUnit, nodesToDeclarations);
}

// Step 3: Assign param types for scenario events. We have do this after all events are initialized.
foreach (var function in globalScope.Functions)
{
ScenarioEventVisitor.PopulateEventTypes(function);
}



return globalScope;
}

Expand Down
Loading
Loading