Skip to content

Commit

Permalink
Tidy up some code
Browse files Browse the repository at this point in the history
  • Loading branch information
desplesda committed Aug 27, 2020
1 parent 9908d2b commit 2b61688
Show file tree
Hide file tree
Showing 5 changed files with 239 additions and 127 deletions.
28 changes: 21 additions & 7 deletions YarnSpinner.Compiler/CodeGenerationVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,7 @@ public override int VisitLine_statement(YarnSpinnerParser.Line_statementContext
//
// is identical to
//
// <<if true>>
// Mae: here's a line
// <<endif>>
// <<if true>> Mae: here's a line <<endif>>

// Convert the formatted string into a string with
// placeholders, and evaluate the inline expressions and push
Expand Down Expand Up @@ -161,7 +159,8 @@ public override int VisitSetVariableToValue(YarnSpinnerParser.SetVariableToValue
var expressionType = expressionTypeVisitor.Visit(context.expression());
var variableType = expressionTypeVisitor.Visit(context.variable());

if (expressionType != variableType) {
if (expressionType != variableType)
{
throw new TypeException(context, $"{context.variable().GetText()} ({variableType}) cannot be assigned a {expressionType}");
}

Expand Down Expand Up @@ -280,6 +279,7 @@ public override int VisitIf_statement(YarnSpinnerParser.If_statementContext cont

return 0;
}

internal void generateClause(string jumpLabel, YarnSpinnerParser.StatementContext[] children, YarnSpinnerParser.ExpressionContext expression)
{
string endOfClauseLabel = compiler.RegisterLabel("skipclause");
Expand All @@ -293,7 +293,7 @@ internal void generateClause(string jumpLabel, YarnSpinnerParser.StatementContex

// Code-generate the expression
Visit(expression);

compiler.Emit(OpCode.JumpIfFalse, new Operand(endOfClauseLabel));
}

Expand All @@ -316,7 +316,6 @@ internal void generateClause(string jumpLabel, YarnSpinnerParser.StatementContex
// indent statements dedent)+
public override int VisitShortcut_option_statement(YarnSpinnerParser.Shortcut_option_statementContext context)
{

string endOfGroupLabel = compiler.RegisterLabel("group_end");

var labels = new List<string>();
Expand Down Expand Up @@ -426,12 +425,15 @@ public override int VisitShortcut_option_statement(YarnSpinnerParser.Shortcut_op
// the calls for the various operations and expressions first the
// special cases (), unary -, !, and if it is just a value by
// itself

#region specialCaseCalls

// (expression)
public override int VisitExpParens(YarnSpinnerParser.ExpParensContext context)
{
return Visit(context.expression());
}

// -expression
public override int VisitExpNegative(YarnSpinnerParser.ExpNegativeContext context)
{
Expand All @@ -446,6 +448,7 @@ public override int VisitExpNegative(YarnSpinnerParser.ExpNegativeContext contex

return 0;
}

// (not NOT !)expression
public override int VisitExpNot(YarnSpinnerParser.ExpNotContext context)
{
Expand All @@ -460,6 +463,7 @@ public override int VisitExpNot(YarnSpinnerParser.ExpNotContext context)

return 0;
}

// variable
public override int VisitExpValue(YarnSpinnerParser.ExpValueContext context)
{
Expand All @@ -482,13 +486,15 @@ internal void genericExpVisitor(YarnSpinnerParser.ExpressionContext left, YarnSp

compiler.Emit(OpCode.CallFunc, new Operand(tokens[op].ToString()));
}

// * / %
public override int VisitExpMultDivMod(YarnSpinnerParser.ExpMultDivModContext context)
{
genericExpVisitor(context.expression(0), context.expression(1), context.op.Type);

return 0;
}

// + -
public override int VisitExpAddSub(YarnSpinnerParser.ExpAddSubContext context)
{
Expand All @@ -503,13 +509,15 @@ public override int VisitExpComparison(YarnSpinnerParser.ExpComparisonContext co

return 0;
}

// == !=
public override int VisitExpEquality(YarnSpinnerParser.ExpEqualityContext context)
{
genericExpVisitor(context.expression(0), context.expression(1), context.op.Type);

return 0;
}

// and && or || xor ^
public override int VisitExpAndOrXor(YarnSpinnerParser.ExpAndOrXorContext context)
{
Expand All @@ -532,7 +540,8 @@ internal void opEquals(YarnSpinnerParser.VariableContext variable, YarnSpinnerPa
var expressionType = expressionTypeVisitor.Visit(expression);
var variableType = expressionTypeVisitor.Visit(variable);

if (expressionType != variableType) {
if (expressionType != variableType)
{
throw new TypeException(expression.Parent as ParserRuleContext, $"{variable.GetText()} ({variableType}) cannot be assigned a {expressionType}");
}

Expand Down Expand Up @@ -584,31 +593,36 @@ public override int VisitValueVar(YarnSpinnerParser.ValueVarContext context)
{
return Visit(context.variable());
}

public override int VisitValueNumber(YarnSpinnerParser.ValueNumberContext context)
{
float number = float.Parse(context.NUMBER().GetText(), CultureInfo.InvariantCulture);
compiler.Emit(OpCode.PushFloat, new Operand(number));

return 0;
}

public override int VisitValueTrue(YarnSpinnerParser.ValueTrueContext context)
{
compiler.Emit(OpCode.PushBool, new Operand(true));

return 0;
}

public override int VisitValueFalse(YarnSpinnerParser.ValueFalseContext context)
{
compiler.Emit(OpCode.PushBool, new Operand(false));
return 0;
}

public override int VisitVariable(YarnSpinnerParser.VariableContext context)
{
string variableName = context.VAR_ID().GetText();
compiler.Emit(OpCode.PushVariable, new Operand(variableName));

return 0;
}

public override int VisitValueString(YarnSpinnerParser.ValueStringContext context)
{
// stripping the " off the front and back actually is this what
Expand Down
72 changes: 47 additions & 25 deletions YarnSpinner.Compiler/Compiler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Yarn.Compiler
namespace Yarn.Compiler
{
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -107,27 +107,34 @@ internal StringInfo(string text, string fileName, string nodeName, int lineNumbe
}
}

public struct VariableDeclaration {
public struct VariableDeclaration
{
public string name;
public Value defaultValue;
public Value.Type type;
public string description;

public override string ToString() {
if (string.IsNullOrEmpty(description)) {
public override string ToString()
{
if (string.IsNullOrEmpty(description))
{
return $"{name} : {type} = {defaultValue}";
} else {
}
else
{
return $"{name} : {type} = {defaultValue} (\"{description}\")";
}
}
}

public struct CompilationJob {
public struct CompilationJob
{

/// <summary>
/// Represents the contents of a file to compile.
/// </summary>
public struct File {
public struct File
{
public string FileName;
public string Source;
}
Expand Down Expand Up @@ -176,18 +183,21 @@ public static CompilationJob CreateFromFiles(IEnumerable<string> paths, Library
};
}

public static CompilationJob CreateFromFiles(params string[] paths) {
return CreateFromFiles((IEnumerable<string>) paths);
public static CompilationJob CreateFromFiles(params string[] paths)
{
return CreateFromFiles((IEnumerable<string>)paths);
}

/// <summary>
/// Creates a new <see cref="CompilationJob"/> using the contents
/// of a string.
/// </summary>
/// <param name="fileName">The name to assign to the compiled file.</param>
/// <param name="fileName">The name to assign to the compiled
/// file.</param>
/// <param name="source">The text to compile.</param>
/// <returns>A new <see cref="CompilationJob"/>.</returns>
public static CompilationJob CreateFromString(string fileName, string source, Library library = null) {
public static CompilationJob CreateFromString(string fileName, string source, Library library = null)
{
return new CompilationJob
{
Files = new List<File>
Expand Down Expand Up @@ -221,8 +231,9 @@ internal static CompilationResult CombineCompilationResults(IEnumerable<Compilat
foreach (var result in results)
{
programs.Add(result.Program);

if (result.Declarations != null) {

if (result.Declarations != null)
{
declarations.AddRange(result.Declarations);
}

Expand All @@ -231,7 +242,8 @@ internal static CompilationResult CombineCompilationResults(IEnumerable<Compilat
mergedStringTable.Add(entry.Key, entry.Value);
}

if (result.Status != CompilationStatus.Succeeded) {
if (result.Status != CompilationStatus.Succeeded)
{
status = result.Status;
}
}
Expand Down Expand Up @@ -294,7 +306,9 @@ public class Compiler : YarnSpinnerParserBaseListener
internal IEnumerable<VariableDeclaration> VariableDeclarations = new List<VariableDeclaration>();

/// <summary>
/// The Library, which contains the function declarations known to the compiler. Supplied as part of a <see cref="CompilationJob"/>.
/// The Library, which contains the function declarations known to
/// the compiler. Supplied as part of a <see
/// cref="CompilationJob"/>.
/// </summary>
internal Library Library { get; private set; }

Expand All @@ -313,19 +327,24 @@ public static CompilationResult Compile(CompilationJob compilationJob)
{
var results = new List<CompilationResult>();

// All variable declarations that we've encountered during this compilation job
// All variable declarations that we've encountered during this
// compilation job
var derivedVariableDeclarations = new List<VariableDeclaration>();

// All variable declarations that we've encountered, PLUS the ones we knew about before
// All variable declarations that we've encountered, PLUS the
// ones we knew about before
var knownVariableDeclarations = new List<VariableDeclaration>();
if (compilationJob.VariableDeclarations != null) {
if (compilationJob.VariableDeclarations != null)
{
knownVariableDeclarations.AddRange(compilationJob.VariableDeclarations);
}

var compiledTrees = new List<(string name, IParseTree tree)>();

// First pass: parse all files, generate their syntax trees, and figure out what variables they've delcared
foreach (var file in compilationJob.Files) {
// First pass: parse all files, generate their syntax trees,
// and figure out what variables they've delcared
foreach (var file in compilationJob.Files)
{
var tree = ParseSyntaxTree(file);
IEnumerable<VariableDeclaration> newDeclarations = DeriveVariableDeclarations(tree, knownVariableDeclarations);

Expand All @@ -335,10 +354,11 @@ public static CompilationResult Compile(CompilationJob compilationJob)
compiledTrees.Add((file.FileName, tree));
}

foreach (var parsedFile in compiledTrees) {
foreach (var parsedFile in compiledTrees)
{
CompilationResult compilationResult = GenerateCode(parsedFile.name, knownVariableDeclarations, compilationJob, parsedFile.tree);
results.Add(compilationResult);
}
}

var finalResult = CompilationResult.CombineCompilationResults(results);

Expand All @@ -347,7 +367,8 @@ public static CompilationResult Compile(CompilationJob compilationJob)
// it. (We don't specify an initial value for
// externally-declared variables, because we expect their value
// to be in the variable storage when the program is run.)
foreach (var declaration in derivedVariableDeclarations) {
foreach (var declaration in derivedVariableDeclarations)
{
Operand value;

switch (declaration.type)
Expand Down Expand Up @@ -379,7 +400,8 @@ private static IEnumerable<VariableDeclaration> DeriveVariableDeclarations(IPars

variableDeclarationVisitor.Visit(tree);

// Upon exit, declarations will now contain every variable declaration we found
// Upon exit, declarations will now contain every variable
// declaration we found
return variableDeclarationVisitor.NewVariableDeclarations;
}

Expand All @@ -396,7 +418,7 @@ private static CompilationResult GenerateCode(string fileName, IEnumerable<Varia
{
Program = compiler.Program,
StringTable = compiler.StringTable,
Status = compiler.containsImplicitStringTags ? CompilationStatus.SucceededUntaggedStrings : CompilationStatus.Succeeded,
Status = compiler.containsImplicitStringTags ? CompilationStatus.SucceededUntaggedStrings : CompilationStatus.Succeeded,
};
}

Expand Down
Loading

0 comments on commit 2b61688

Please sign in to comment.