Compare commits
12 commits
master
...
feature/js
Author | SHA1 | Date | |
---|---|---|---|
5821db3b55 | |||
c4cd9d1806 | |||
2cc170395c | |||
|
9aba3939c3 | ||
|
0dafbabc23 | ||
|
9c31a92abd | ||
|
2ba01713ef | ||
|
2289827a9d | ||
|
00b6f66110 | ||
|
a751490e4b | ||
77fa88dfd4 | |||
12fc26fa44 |
118 changed files with 11982 additions and 3685 deletions
13
.gitignore
vendored
13
.gitignore
vendored
|
@ -4,5 +4,14 @@
|
|||
.~lock.*
|
||||
output/*
|
||||
AspectedRouting.sln.DotSettings
|
||||
AspectedRouting.sln.DotSettings.user
|
||||
.DS_Store
|
||||
|
||||
#Visual Studio Code
|
||||
.vscode
|
||||
|
||||
# Node Modules
|
||||
*/node_modules
|
||||
|
||||
.fake
|
||||
.ionide
|
||||
|
||||
*/.routeExamples
|
|
@ -1,7 +1,7 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.IO.jsonParser;
|
||||
|
@ -8,25 +7,10 @@ using AspectedRouting.Language.Functions;
|
|||
using AspectedRouting.Language.Typ;
|
||||
using Xunit;
|
||||
|
||||
namespace AspectedRouting.Test;
|
||||
|
||||
namespace AspectedRouting.Test
|
||||
{
|
||||
public class FunctionsTest
|
||||
{
|
||||
private readonly string constString = "{\"$const\": \"a\"}";
|
||||
|
||||
private readonly string IfDottedConditionJson
|
||||
= "{" +
|
||||
"\"$ifdotted\": {\"$eq\": \"yes\"}," +
|
||||
"\"then\":{\"$const\": \"a\"}," +
|
||||
"\"else\": {\"$const\": \"b\"}" +
|
||||
"}";
|
||||
|
||||
private readonly string IfSimpleConditionJson
|
||||
= "{" +
|
||||
"\"$if\": true," +
|
||||
"\"then\":\"thenResult\"," +
|
||||
"\"else\": \"elseResult\"}";
|
||||
|
||||
private IExpression MustMatchJson()
|
||||
{
|
||||
var json = "{" +
|
||||
|
@ -54,7 +38,7 @@ public class FunctionsTest
|
|||
{"x", "y"}
|
||||
};
|
||||
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize(out _);
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize();
|
||||
var result = expr.Evaluate(new Context());
|
||||
Assert.Equal("yes", result);
|
||||
}
|
||||
|
@ -64,10 +48,10 @@ public class FunctionsTest
|
|||
{
|
||||
var tagsAx = new Dictionary<string, string>
|
||||
{
|
||||
{ "a", "b" }
|
||||
{"a", "b"},
|
||||
};
|
||||
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize(out var _);
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize();
|
||||
var result = expr.Evaluate(new Context());
|
||||
Assert.Equal("no", result);
|
||||
}
|
||||
|
@ -81,11 +65,24 @@ public class FunctionsTest
|
|||
{"x", "someRandomValue"}
|
||||
};
|
||||
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize(out _);
|
||||
var expr = new Apply(MustMatchJson(), new Constant(tagsAx)).Optimize();
|
||||
var result = expr.Evaluate(new Context());
|
||||
Assert.Equal("no", result);
|
||||
}
|
||||
|
||||
private string IfDottedConditionJson
|
||||
= "{" +
|
||||
"\"$ifdotted\": {\"$eq\": \"yes\"}," +
|
||||
"\"then\":{\"$const\": \"a\"}," +
|
||||
"\"else\": {\"$const\": \"b\"}" +
|
||||
"}";
|
||||
|
||||
private string IfSimpleConditionJson
|
||||
= "{" +
|
||||
"\"$if\": true," +
|
||||
"\"then\":\"thenResult\"," +
|
||||
"\"else\": \"elseResult\"}";
|
||||
|
||||
[Fact]
|
||||
public void TestParsing_SimpleIf_CorrectExpression()
|
||||
{
|
||||
|
@ -97,7 +94,7 @@ public class FunctionsTest
|
|||
|
||||
var resultT = ifExpr.Evaluate(c);
|
||||
Assert.Equal("thenResult", resultT);
|
||||
resultT = ifExpr.Optimize(out _).Evaluate(c);
|
||||
resultT = ifExpr.Optimize().Evaluate(c);
|
||||
Assert.Equal("thenResult", resultT);
|
||||
}
|
||||
|
||||
|
@ -123,7 +120,7 @@ public class FunctionsTest
|
|||
{
|
||||
var c = new Context();
|
||||
var ifExpr = JsonParser.ParseExpression(c, IfDottedConditionJson);
|
||||
ifExpr = ifExpr.Optimize(out _);
|
||||
ifExpr = ifExpr.Optimize();
|
||||
var resultT = ifExpr.Evaluate(c,
|
||||
new Constant(Typs.String, "yes"));
|
||||
var resultF = ifExpr.Evaluate(c,
|
||||
|
@ -132,6 +129,9 @@ public class FunctionsTest
|
|||
Assert.Equal("b", resultF);
|
||||
}
|
||||
|
||||
|
||||
private string constString = "{\"$const\": \"a\"}";
|
||||
|
||||
[Fact]
|
||||
public void Parse_ConstString_TypeIsFree()
|
||||
{
|
||||
|
@ -308,9 +308,9 @@ public class FunctionsTest
|
|||
var unifB = tags2pdouble.Unify(tags2double, true);
|
||||
Assert.NotNull(unifB);
|
||||
|
||||
var unifC = tags2double.Unify(tags2pdouble);
|
||||
var unifC = tags2double.Unify(tags2pdouble, false);
|
||||
Assert.NotNull(unifC);
|
||||
var unifD = tags2pdouble.Unify(tags2double);
|
||||
var unifD = tags2pdouble.Unify(tags2double, false);
|
||||
Assert.Null(unifD);
|
||||
}
|
||||
|
||||
|
@ -378,102 +378,8 @@ public class FunctionsTest
|
|||
Assert.Single(e.Types);
|
||||
|
||||
Assert.Equal("string -> string", e.Types.First().ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyFirstMatchOf_FirstMatchIsTaken_50()
|
||||
{
|
||||
var tags0 = new Constant(new Dictionary<string, string>
|
||||
{
|
||||
{ "highway", "residential" },
|
||||
{ "maxspeed", "50" }
|
||||
});
|
||||
|
||||
var f = FirstMatchOfWithMaxspeedAndHighway();
|
||||
var o = f.Evaluate(new Context(), tags0);
|
||||
Assert.Equal(50.0, o);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void ApplyFirstMatchOf_FirstMatchIsTaken_ResidentialDefault()
|
||||
{
|
||||
var tags0 = new Constant(new Dictionary<string, string>
|
||||
{
|
||||
{ "highway", "residential" }
|
||||
});
|
||||
|
||||
var f = FirstMatchOfWithMaxspeedAndHighway();
|
||||
var o = f.Evaluate(new Context(), tags0);
|
||||
Assert.Equal(30, o);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyFirstMatchOf_NoMatchIfFound_Null()
|
||||
{
|
||||
var tags0 = new Constant(new Dictionary<string, string>
|
||||
{
|
||||
{ "highway", "unknown" }
|
||||
});
|
||||
|
||||
var f = FirstMatchOfWithMaxspeedAndHighway();
|
||||
var o = f.Evaluate(new Context(), tags0);
|
||||
Assert.Equal(null, o);
|
||||
}
|
||||
|
||||
public IExpression FirstMatchOfWithMaxspeedAndHighway()
|
||||
{
|
||||
var order = new Constant(new ListType(Typs.String), new List<IExpression>
|
||||
{
|
||||
new Constant("maxspeed"),
|
||||
new Constant("highway")
|
||||
});
|
||||
|
||||
var mapping =
|
||||
Funcs.StringStringToTags.Apply(
|
||||
new Mapping(
|
||||
new List<string> { "maxspeed", "highway" },
|
||||
new List<IExpression>
|
||||
{
|
||||
Funcs.Parse,
|
||||
new Mapping(
|
||||
new List<string> { "residential", "primary" },
|
||||
new List<IExpression> { new Constant(30), new Constant(90) }
|
||||
)
|
||||
})
|
||||
);
|
||||
return Funcs.FirstOf.Apply(order, mapping);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
/**
|
||||
* Regression test for a misbehaving ifDotted
|
||||
*/
|
||||
public void IfDotted_CorrectExpression()
|
||||
{
|
||||
var e = Funcs.IfDotted.Apply(
|
||||
Funcs.Const.Apply(new Parameter("follow_restrictions")),
|
||||
Funcs.Head.Apply( Funcs.StringStringToTags.Apply( new Mapping(new[] { "oneway" }, new[] { Funcs.Id }))),
|
||||
Funcs.Const.Apply(new Constant("dont-care"))
|
||||
);
|
||||
|
||||
var c = new Context();
|
||||
c.AddParameter("follow_restrictions", "yes");
|
||||
|
||||
var tags = new Dictionary<string, string>();
|
||||
tags["oneway"] = "with";
|
||||
|
||||
var r = e.Evaluate(c, new Constant(tags));
|
||||
Assert.Equal("with", r);
|
||||
|
||||
var c0 = new Context();
|
||||
c0.AddParameter("follow_restrictions", "no");
|
||||
|
||||
|
||||
var r0 = e.Evaluate(c0, new Constant(tags));
|
||||
Assert.Equal("dont-care", r0);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,5 @@
|
|||
using System.Collections.Generic;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
using AspectedRouting.IO.LuaSkeleton;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Functions;
|
||||
|
@ -13,10 +14,11 @@ namespace AspectedRouting.Test
|
|||
{
|
||||
var mapping = new Mapping(
|
||||
new[] {"a", "b", "c"},
|
||||
new[] {
|
||||
new[]
|
||||
{
|
||||
new Constant(5),
|
||||
new Constant(6),
|
||||
new Constant(7)
|
||||
new Constant(7),
|
||||
}
|
||||
);
|
||||
|
||||
|
@ -33,10 +35,12 @@ namespace AspectedRouting.Test
|
|||
{
|
||||
var mapping = new Mapping(
|
||||
new[] {"a"},
|
||||
new[] {
|
||||
new[]
|
||||
{
|
||||
new Mapping(new[] {"b"},
|
||||
new[] {
|
||||
new Constant(42)
|
||||
new[]
|
||||
{
|
||||
new Constant(42),
|
||||
}
|
||||
)
|
||||
}
|
||||
|
@ -50,8 +54,10 @@ namespace AspectedRouting.Test
|
|||
public void Sanity_EveryBasicFunction_HasDescription()
|
||||
{
|
||||
var missing = new List<string>();
|
||||
foreach (var (_, f) in Funcs.Builtins) {
|
||||
if (string.IsNullOrEmpty(f.Description)) {
|
||||
foreach (var (_, f) in Funcs.Builtins)
|
||||
{
|
||||
if (string.IsNullOrEmpty(f.Description))
|
||||
{
|
||||
missing.Add(f.Name);
|
||||
}
|
||||
}
|
||||
|
@ -64,8 +70,10 @@ namespace AspectedRouting.Test
|
|||
public void Sanity_EveryBasicFunction_HasArgNames()
|
||||
{
|
||||
var missing = new List<string>();
|
||||
foreach (var (_, f) in Funcs.Builtins) {
|
||||
if (f.ArgNames == null) {
|
||||
foreach (var (_, f) in Funcs.Builtins)
|
||||
{
|
||||
if (f.ArgNames == null)
|
||||
{
|
||||
missing.Add(f.Name);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,151 +0,0 @@
|
|||
using AspectedRouting.IO.LuaSkeleton;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using Xunit;
|
||||
|
||||
namespace AspectedRouting.Test;
|
||||
|
||||
public class OptimizationsTests
|
||||
{
|
||||
[Fact]
|
||||
public void AppliedListDot_Optimize_ListOfApplications()
|
||||
{
|
||||
var lit = new LuaLiteral(Typs.Nat, "tags");
|
||||
var e0 = Funcs.ListDot.Apply(
|
||||
new Constant(new[]
|
||||
{
|
||||
Funcs.Eq.Apply(new Constant(5)),
|
||||
Funcs.Eq.Apply(new Constant(42))
|
||||
}));
|
||||
|
||||
var e = e0.Apply(lit).SpecializeToSmallestType();
|
||||
var x = e.Optimize(out var sc);
|
||||
Assert.True(sc);
|
||||
Assert.Equal(
|
||||
new Constant(new[]
|
||||
{
|
||||
Funcs.Eq.Apply(new Constant(5)).Apply(lit),
|
||||
Funcs.Eq.Apply(new Constant(42)).Apply(lit)
|
||||
}).SpecializeToSmallestType().ToString(), x.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdvancedApplied_Optimized_ListOfAppliedValues()
|
||||
{
|
||||
var legal_access_be = new FunctionCall("$legal_access_be", new Curry(Typs.Tags, Typs.String));
|
||||
var legal_access_pedestrian = new FunctionCall("$pedestrian.legal_access", new Curry(Typs.Tags, Typs.String));
|
||||
var tags = new LuaLiteral(Typs.Tags, "tags");
|
||||
var e = new Apply( // string
|
||||
Funcs.Head,
|
||||
new Apply( // list (string)
|
||||
new Apply( // tags -> list (string)
|
||||
Funcs.ListDot,
|
||||
new Constant(new[]
|
||||
{
|
||||
legal_access_be,
|
||||
legal_access_pedestrian
|
||||
})),
|
||||
tags));
|
||||
var eOpt = e.Optimize(out var sc);
|
||||
Assert.True(sc);
|
||||
Assert.Equal(
|
||||
Funcs.Head.Apply(new Constant(
|
||||
new[]
|
||||
{
|
||||
legal_access_be.Apply(tags),
|
||||
legal_access_pedestrian.Apply(tags)
|
||||
}
|
||||
)).ToString(),
|
||||
eOpt.ToString()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void advancedExpr_Optimize_Works()
|
||||
{
|
||||
var e = new Apply( // double
|
||||
new Apply( // tags -> double
|
||||
new Apply( // (tags -> double) -> tags -> doubleTag
|
||||
Funcs.Default,
|
||||
new Constant(0)),
|
||||
new Apply( // tags -> double
|
||||
new Apply( // (tags -> list (double)) -> tags -> double
|
||||
Funcs.Dot,
|
||||
Funcs.Head),
|
||||
new Apply( // tags -> list (double)
|
||||
Funcs.StringStringToTags,
|
||||
new Mapping(
|
||||
new[]
|
||||
{
|
||||
"access"
|
||||
},
|
||||
new[]
|
||||
{
|
||||
new Mapping(
|
||||
new[]
|
||||
{
|
||||
"private",
|
||||
"destination",
|
||||
"permissive"
|
||||
},
|
||||
new[]
|
||||
{
|
||||
new Constant(-500), new Constant(-3), new Constant(-1)
|
||||
}
|
||||
)
|
||||
}
|
||||
)))),
|
||||
new LuaLiteral(Typs.Tags, "tags"));
|
||||
var eOpt = e.Optimize(out var sc);
|
||||
Assert.True(sc);
|
||||
Assert.NotEmpty(eOpt.Types);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void optimizeListdotAway()
|
||||
{
|
||||
var tagsToStr = new Curry(Typs.Tags, Typs.PDouble);
|
||||
var e = new Apply( // pdouble
|
||||
new Apply( // tags -> pdouble
|
||||
Funcs.Id,
|
||||
new Apply( // tags -> pdouble
|
||||
new Apply( // (tags -> list (pdouble)) -> tags -> pdouble
|
||||
Funcs.Dot,
|
||||
Funcs.Min),
|
||||
new Apply( // tags -> list (pdouble)
|
||||
Funcs.ListDot,
|
||||
new Constant(new IExpression[]
|
||||
{
|
||||
new FunctionCall("$legal_maxspeed_be", tagsToStr),
|
||||
new FunctionCall("$car.practical_max_speed", tagsToStr),
|
||||
new Apply( // tags -> pdouble
|
||||
Funcs.Const,
|
||||
new Parameter("#maxspeed"))
|
||||
})))),
|
||||
new LuaLiteral(Typs.Tags, "tags"));
|
||||
var opt = e.SpecializeToSmallestType().Optimize(out var sc);
|
||||
Assert.True(sc);
|
||||
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Regression_ShouldOptimize()
|
||||
{
|
||||
var e = new Apply( // nat
|
||||
new Apply( // tags -> nat
|
||||
new Apply( // nat -> tags -> nat
|
||||
new Apply( // (nat -> tags -> nat) -> nat -> tags -> nat
|
||||
Funcs.ConstRight,
|
||||
Funcs.Id),
|
||||
Funcs.Const),
|
||||
new LuaLiteral(Typs.PDouble, "distance")),
|
||||
new LuaLiteral(Typs.Tags, "tags")).SpecializeToSmallestType();
|
||||
var opt = e.Optimize(out var sc);
|
||||
Assert.True(sc);
|
||||
|
||||
}
|
||||
}
|
|
@ -1,52 +0,0 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using AspectedRouting.IO.jsonParser;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using Xunit;
|
||||
|
||||
namespace AspectedRouting.Test;
|
||||
|
||||
public class RegressionTest
|
||||
{
|
||||
[Fact]
|
||||
public void IfDotted_ShouldBeParsed()
|
||||
{
|
||||
var carOneway = Funcs.Const.Apply(new Constant("result of car.oneway")).Specialize(new Curry(
|
||||
Typs.Tags, Typs.String));
|
||||
|
||||
var doc = JsonDocument.Parse("{\"oneway\":{\"$ifdotted\":{\"$const\": \"#follow_restrictions\"},\"then\": \"$car.oneway\",\"else\": {\"$const\": \"both-ignored-restrictions\"}}}");
|
||||
|
||||
var parsingContext = new Context();
|
||||
parsingContext .AddFunction("car.oneway", new AspectMetadata(
|
||||
carOneway, "car.oneway","oneway function", "test", "with|against|both",
|
||||
"N/A", false
|
||||
));
|
||||
parsingContext.AddParameter("follow_restrictions","no");
|
||||
var aspect = JsonParser.ParseProfileProperty(doc.RootElement,parsingContext, "oneway");
|
||||
var oneway = new Dictionary<string, string>();
|
||||
|
||||
var c = new Context();
|
||||
c .AddFunction("car.oneway", new AspectMetadata(
|
||||
carOneway, "car.oneway","oneway function", "test", "with|against|both",
|
||||
"N/A", false
|
||||
));
|
||||
|
||||
c.AddParameter("follow_restrictions","yes");
|
||||
var result = aspect.Run(c, oneway);
|
||||
Assert.Equal("result of car.oneway", result);
|
||||
|
||||
var c0 = new Context();
|
||||
c0.AddFunction("car.oneway", new AspectMetadata(
|
||||
carOneway, "car.oneway","oneway function", "test", "with|against|both",
|
||||
"N/A", false
|
||||
));
|
||||
c0.AddParameter("follow_restrictions","no");
|
||||
var result0 = aspect.Run(c0, oneway);
|
||||
Assert.Equal("both-ignored-restrictions", result0);
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,3 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AspectedRouting.IO.LuaSkeleton;
|
||||
using AspectedRouting.IO.LuaSnippets;
|
||||
|
@ -8,8 +7,8 @@ using AspectedRouting.Language.Functions;
|
|||
using AspectedRouting.Language.Typ;
|
||||
using Xunit;
|
||||
|
||||
namespace AspectedRouting.Test.Snippets;
|
||||
|
||||
namespace AspectedRouting.Test.Snippets
|
||||
{
|
||||
public class SnippetTests
|
||||
{
|
||||
[Fact]
|
||||
|
@ -17,8 +16,7 @@ public class SnippetTests
|
|||
{
|
||||
var gen = new DefaultSnippet();
|
||||
var lua = new LuaSkeleton(new Context(), true);
|
||||
var code = gen.Convert(lua, "result", new List<IExpression>
|
||||
{
|
||||
var code = gen.Convert(lua, "result", new List<IExpression> {
|
||||
new Constant("the_default_value"),
|
||||
Funcs.Id,
|
||||
new Constant("value")
|
||||
|
@ -36,8 +34,7 @@ public class SnippetTests
|
|||
// FirstMatchOf: [a] -> (Tags -> [a]) -> Tags -> a
|
||||
|
||||
// Order: [string]
|
||||
var order = new Constant(new List<IExpression>
|
||||
{
|
||||
var order = new Constant(new List<IExpression> {
|
||||
new Constant("bicycle"),
|
||||
new Constant("access")
|
||||
});
|
||||
|
@ -47,8 +44,7 @@ public class SnippetTests
|
|||
Funcs.StringStringToTags,
|
||||
new Mapping(
|
||||
new[] {"bicycle", "access"},
|
||||
new IExpression[]
|
||||
{
|
||||
new IExpression[] {
|
||||
Funcs.Id,
|
||||
Funcs.Id
|
||||
}
|
||||
|
@ -58,8 +54,7 @@ public class SnippetTests
|
|||
var tags = new LuaLiteral(new[] {Typs.Tags}, "tags");
|
||||
|
||||
var code = gen.Convert(lua, "result",
|
||||
new List<IExpression>
|
||||
{
|
||||
new List<IExpression> {
|
||||
order,
|
||||
func,
|
||||
tags
|
||||
|
@ -77,15 +72,13 @@ public class SnippetTests
|
|||
{
|
||||
var mapping = new Mapping(
|
||||
new[] {"1", "-1"},
|
||||
new IExpression[]
|
||||
{
|
||||
new IExpression[] {
|
||||
new Constant("with"),
|
||||
new Constant("against")
|
||||
}
|
||||
);
|
||||
var gen = new SimpleMappingSnippet(mapping);
|
||||
var code = gen.Convert(new LuaSkeleton(new Context(), true), "result", new List<IExpression>
|
||||
{
|
||||
var code = gen.Convert(new LuaSkeleton(new Context(), true), "result", new List<IExpression> {
|
||||
new LuaLiteral(Typs.String, "tags.oneway")
|
||||
});
|
||||
|
||||
|
@ -94,27 +87,5 @@ public class SnippetTests
|
|||
Assert.Equal(expected, code);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void ListDotWithHead_GeneratesLua()
|
||||
{
|
||||
// (dot head) (stringToTags (mapping speed $ parse))
|
||||
var eSub = Funcs.Dot.Apply(Funcs.Head,
|
||||
new Constant(new[]
|
||||
{
|
||||
Funcs.Head.Apply(Funcs.StringStringToTags.Apply(
|
||||
new Mapping(new List<string> { "_speed" }, new[] { Funcs.Parse }))),
|
||||
Funcs.Const.Apply(new Constant(Typs.Double, 42))
|
||||
})
|
||||
);
|
||||
var condition = Funcs.Dot.Apply(Funcs.Head, Funcs.StringStringToTags.Apply(
|
||||
new Mapping(new[] { "route" }, new[] { Funcs.Eq.Apply(new Constant("ferry")) })));
|
||||
var e =
|
||||
Funcs.IfDotted.Apply(condition, eSub);
|
||||
e = e.Apply(new LuaLiteral(Typs.Tags, "tags")).Finalize().Optimize(out _);
|
||||
var ctx = new Context();
|
||||
var lua = new LuaSkeleton(ctx, true);
|
||||
var code = IO.LuaSnippets.Snippets.Convert(lua, "varname", e);
|
||||
Console.WriteLine(code);
|
||||
}
|
||||
}
|
|
@ -18,7 +18,8 @@ namespace AspectedRouting.Test
|
|||
"{\"name\": \"legal_maxspeed_be\",\"description\": \"Gives, for each type of highway, which the default legal maxspeed is in Belgium. This file is intended to be reused for in all vehicles, from pedestrian to car. In some cases, a legal maxspeed is not really defined (e.g. on footways). In that case, a socially acceptable speed should be taken (e.g.: a bicycle on a pedestrian path will go say around 12km/h)\",\"unit\": \"km/h\",\"$max\": {\"maxspeed\": \"$parse\",\"highway\": {\"residential\": 30},\"ferry\":5}}";
|
||||
|
||||
var aspect = JsonParser.AspectFromJson(null, json, null);
|
||||
var tags = new Dictionary<string, string> {
|
||||
var tags = new Dictionary<string, string>
|
||||
{
|
||||
{"maxspeed", "42"},
|
||||
{"highway", "residential"},
|
||||
{"ferry", "yes"}
|
||||
|
@ -39,7 +40,8 @@ namespace AspectedRouting.Test
|
|||
var aspect = JsonParser.AspectFromJson(null, json, null);
|
||||
|
||||
Assert.Equal(
|
||||
new Dictionary<string, HashSet<string>> {
|
||||
new Dictionary<string, HashSet<string>>
|
||||
{
|
||||
{"maxspeed", new HashSet<string>()},
|
||||
{"highway", new HashSet<string> {"residential"}},
|
||||
{"ferry", new HashSet<string>()}
|
||||
|
|
21
AspectedRouting.sln.DotSettings.user
Normal file
21
AspectedRouting.sln.DotSettings.user
Normal file
|
@ -0,0 +1,21 @@
|
|||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=3112587d_002D1c06_002D4ad3_002Da845_002D73105d4b723a/@EntryIndexedValue"><SessionState ContinuousTestingMode="0" Name="DefaultSnippet_SimpleDefault_GetsLua" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session">
|
||||
<TestAncestor>
|
||||
<TestId>xUnit::A1309041-8AAE-42D7-A886-94C9FFC6A28C::.NETCoreApp,Version=v3.1::AspectedRouting.Test.Snippets.SnippetTests</TestId>
|
||||
<TestId>xUnit::A1309041-8AAE-42D7-A886-94C9FFC6A28C::.NETCoreApp,Version=v3.1::AspectedRouting.Test.TypingTests.SpecializeToCommonTypes_X2PDouble_Y2Double_Gives_X2Double</TestId>
|
||||
</TestAncestor>
|
||||
</SessionState></s:String>
|
||||
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=5e89d9f5_002D24ed_002D4ea2_002Da7ea_002Dcc7faea6d057/@EntryIndexedValue"><SessionState ContinuousTestingMode="0" Name="JoinApply_Id" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session">
|
||||
<TestAncestor>
|
||||
<TestId>xUnit::A1309041-8AAE-42D7-A886-94C9FFC6A28C::.NETCoreApp,Version=v3.1::AspectedRouting.Test.TypingTests.JoinApply_Id</TestId>
|
||||
<TestId>xUnit::A1309041-8AAE-42D7-A886-94C9FFC6A28C::.NETCoreApp,Version=v3.1::AspectedRouting.Test.FunctionsTest.ApplyDefaultFunctionWithId_ApplicationIsSuccessfull</TestId>
|
||||
</TestAncestor>
|
||||
</SessionState></s:String>
|
||||
|
||||
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=a6a74f48_002D8456_002D43c7_002Dbbee_002Dd3da33a8a4be/@EntryIndexedValue"><SessionState ContinuousTestingMode="0" IsActive="True" Name="Integration_TestExamples" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session">
|
||||
<Project Location="/home/pietervdvn/git/AspectedRouting/AspectedRouting.Test" Presentation="&lt;AspectedRouting.Test&gt;" />
|
||||
</SessionState></s:String>
|
||||
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=d2e3d58f_002Debff_002D4fb5_002D8d18_002Deafe85f4773d/@EntryIndexedValue"><SessionState ContinuousTestingMode="0" Name="SpecializeToCommonTypes_ValueAndFuncType_ShouldFail" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session">
|
||||
<Project Location="/home/pietervdvn/git/AspectedRouting/AspectedRouting.Test" Presentation="&lt;AspectedRouting.Test&gt;" />
|
||||
</SessionState></s:String>
|
||||
</wpf:ResourceDictionary>
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<LangVersion>8</LangVersion>
|
||||
<AssemblyName>AspectedRouting</AssemblyName>
|
||||
<RootNamespace>AspectedRouting</RootNamespace>
|
||||
|
@ -15,9 +15,6 @@
|
|||
<None Update="Examples\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Format.md">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
@ -2,7 +2,6 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using Type = AspectedRouting.Language.Typ.Type;
|
||||
|
||||
namespace AspectedRouting.IO.LuaSkeleton
|
||||
|
@ -10,8 +9,12 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
public class LuaLiteral : IExpression
|
||||
{
|
||||
public readonly string Lua;
|
||||
public IEnumerable<Type> Types { get; }
|
||||
|
||||
public LuaLiteral(Type type, string lua) : this(new[] { type }, lua) { }
|
||||
public LuaLiteral(Type type, string lua):this(new [] {type}, lua)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public LuaLiteral(IEnumerable<Type> types, string lua)
|
||||
{
|
||||
|
@ -19,8 +22,6 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
Types = types;
|
||||
}
|
||||
|
||||
public IEnumerable<Type> Types { get; }
|
||||
|
||||
public object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
|
@ -31,46 +32,25 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
return this;
|
||||
}
|
||||
|
||||
public IExpression PruneTypes(System.Func<Type, bool> allowedTypes)
|
||||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passed = Types.Where(allowedTypes);
|
||||
if (passed.Any())
|
||||
{
|
||||
return new LuaLiteral(passed, Lua);
|
||||
var passed = this.Types.Where(allowedTypes);
|
||||
if (passed.Any()) {
|
||||
return new LuaLiteral(passed, this.Lua);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
public IExpression Optimize()
|
||||
{
|
||||
somethingChanged = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void Visit(Func<IExpression, bool> f)
|
||||
{
|
||||
f(this);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is LuaLiteral ll)
|
||||
{
|
||||
return ll.Lua.Equals(this.Lua);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
if (this.Types.Count() == 1 && this.Types.First() == Typs.Tags)
|
||||
{
|
||||
return $"new LuaLiteral(Typs.Tags, \"{this.Lua}\")";
|
||||
}
|
||||
|
||||
return $"new LuaLiteral(\"{this.Lua}\")";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,8 +6,8 @@ namespace AspectedRouting.IO.itinero1
|
|||
{
|
||||
public class LuaParameterPrinter
|
||||
{
|
||||
private readonly ProfileMetaData _profile;
|
||||
private readonly LuaSkeleton.LuaSkeleton _skeleton;
|
||||
private ProfileMetaData _profile;
|
||||
private LuaSkeleton.LuaSkeleton _skeleton;
|
||||
|
||||
public LuaParameterPrinter(ProfileMetaData profile, LuaSkeleton.LuaSkeleton skeleton)
|
||||
{
|
||||
|
@ -18,7 +18,8 @@ namespace AspectedRouting.IO.itinero1
|
|||
|
||||
public string GenerateDefaultParameters()
|
||||
{
|
||||
var impl = new List<string> {
|
||||
var impl = new List<string>()
|
||||
{
|
||||
"function default_parameters()",
|
||||
" local parameters = {}",
|
||||
DeclareParametersFor(_profile.DefaultParameters),
|
||||
|
@ -31,12 +32,17 @@ namespace AspectedRouting.IO.itinero1
|
|||
|
||||
/// <summary>
|
||||
/// Generates a piece of code of the following format:
|
||||
///
|
||||
/// parameters["x"] = a;
|
||||
/// parameters["y"] = b:
|
||||
/// ...
|
||||
///
|
||||
/// Where x=a and y=b are defined in the profile
|
||||
///
|
||||
/// Dependencies are added.
|
||||
///
|
||||
/// Note that the caller should still add `local paramaters = default_parameters()`
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="behaviour"></param>
|
||||
/// <returns></returns>
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Dynamic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
|
@ -15,16 +13,6 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
{
|
||||
public partial class LuaSkeleton
|
||||
{
|
||||
|
||||
internal string ToLuaWithTags(IExpression bare)
|
||||
{
|
||||
if (bare == null)
|
||||
{
|
||||
throw new NullReferenceException("bare is null");
|
||||
}
|
||||
var opt = bare.Apply(new LuaLiteral(Typs.Tags, "tags")).SpecializeToSmallestType().Optimize(out _);
|
||||
return this.ToLua(opt);
|
||||
}
|
||||
internal string ToLua(IExpression bare, string key = "nil", bool forceFirstArgInDot = false)
|
||||
{
|
||||
var collectedMapping = new List<IExpression>();
|
||||
|
@ -38,8 +26,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
, UnApply(
|
||||
IsFunc(Funcs.StringStringToTags),
|
||||
Assign(collectedMapping))
|
||||
).Invoke(bare))
|
||||
{
|
||||
).Invoke(bare)) {
|
||||
AddDep(Funcs.FirstOf.Name);
|
||||
return "first_match_of(\n" +
|
||||
" " + ToLua(order.First(), key) + ",\n" +
|
||||
|
@ -54,8 +41,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
, UnApply(
|
||||
IsFunc(Funcs.StringStringToTags),
|
||||
Assign(collectedMapping))
|
||||
).Invoke(bare))
|
||||
{
|
||||
).Invoke(bare)) {
|
||||
AddDep(Funcs.MustMatch.Name);
|
||||
return "must_match(" +
|
||||
" " + ToLua(order.First(), key) + "," +
|
||||
|
@ -66,36 +52,41 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
if (UnApply(
|
||||
IsFunc(Funcs.MemberOf),
|
||||
Any
|
||||
).Invoke(bare))
|
||||
{
|
||||
).Invoke(bare)) {
|
||||
AddDep("memberOf");
|
||||
return "memberOf(funcName, parameters, tags, result)";
|
||||
}
|
||||
|
||||
{
|
||||
var name = new List<string>();
|
||||
var arg = new List<IExpression>();
|
||||
if (UnApply(
|
||||
IsFunctionCall(name),
|
||||
Assign(arg)
|
||||
).Invoke(bare))
|
||||
{
|
||||
var called = _context.DefinedFunctions[name.First()];
|
||||
if (called.ProfileInternal)
|
||||
{
|
||||
return called.Name;
|
||||
|
||||
var collectedList = new List<IExpression>();
|
||||
var func = new List<IExpression>();
|
||||
if (
|
||||
UnApply(
|
||||
UnApply(IsFunc(Funcs.Dot), Assign(func)),
|
||||
UnApply(IsFunc(Funcs.ListDot),
|
||||
Assign(collectedList))).Invoke(bare)) {
|
||||
var exprs = (IEnumerable<IExpression>) ((Constant) collectedList.First()).Evaluate(_context);
|
||||
var luaExprs = new List<string>();
|
||||
var funcName = func.First().ToString().TrimStart('$');
|
||||
AddDep(funcName);
|
||||
foreach (var expr in exprs) {
|
||||
var c = new List<IExpression>();
|
||||
if (UnApply(IsFunc(Funcs.Const), Assign(c)).Invoke(expr)) {
|
||||
luaExprs.Add(ToLua(c.First(), key));
|
||||
continue;
|
||||
}
|
||||
|
||||
AddDependenciesFor(called);
|
||||
AddFunction(called);
|
||||
var usesParams = called.ExpressionImplementation.UsedParameters().Any();
|
||||
if (usesParams)
|
||||
{
|
||||
return $"{name.First().Replace(".", "_")}({ToLua(arg.First())}, parameters)";
|
||||
}
|
||||
return $"{name.First().Replace(".", "_")}({ToLua(arg.First())})";
|
||||
if (expr.Types.First() is Curry curry
|
||||
&& curry.ArgType.Equals(Typs.Tags)) {
|
||||
var lua = ToLua(expr, key);
|
||||
luaExprs.Add(lua);
|
||||
}
|
||||
}
|
||||
|
||||
return "\n " + funcName + "({\n " + string.Join(",\n ", luaExprs) +
|
||||
"\n })";
|
||||
}
|
||||
|
||||
collectedMapping.Clear();
|
||||
var dottedFunction = new List<IExpression>();
|
||||
dottedFunction.Clear();
|
||||
|
@ -107,8 +98,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
UnApply(
|
||||
IsFunc(Funcs.StringStringToTags),
|
||||
Assign(collectedMapping))).Invoke(bare)
|
||||
)
|
||||
{
|
||||
) {
|
||||
var mapping = (Mapping) collectedMapping.First();
|
||||
var baseFunc = (Function) dottedFunction.First();
|
||||
AddDep(baseFunc.Name);
|
||||
|
@ -124,44 +114,32 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
// The expression might be a function which still expects a string (the value from the tag) as argument
|
||||
if (!(bare is Mapping) &&
|
||||
bare.Types.First() is Curry curr &&
|
||||
curr.ArgType.Equals(Typs.String))
|
||||
{
|
||||
curr.ArgType.Equals(Typs.String)) {
|
||||
var applied = new Apply(bare, new Constant(curr.ArgType, ("tags", "\"" + key + "\"")));
|
||||
return ToLua(applied.Optimize(out _), key);
|
||||
return ToLua(applied.Optimize(), key);
|
||||
}
|
||||
|
||||
|
||||
// The expression might consist of multiple nested functions
|
||||
var fArgs = bare.DeconstructApply();
|
||||
if (fArgs != null)
|
||||
{
|
||||
if (fArgs != null) {
|
||||
var (f, args) = fArgs.Value;
|
||||
|
||||
if (f is Constant constant)
|
||||
{
|
||||
if(f is Constant constant) {
|
||||
return ConstantToLua(constant);
|
||||
}
|
||||
|
||||
if (!(f is Function baseFunc))
|
||||
{
|
||||
if (!(f is Function baseFunc)) {
|
||||
throw new ArgumentException("Not a function: " + f);
|
||||
}
|
||||
|
||||
if (baseFunc.Name.Equals(Funcs.Id.Name))
|
||||
{
|
||||
if (baseFunc.Name.Equals(Funcs.Id.Name)) {
|
||||
// This is an ugly hack
|
||||
return ToLua(args.First());
|
||||
}
|
||||
|
||||
if (baseFunc.Name.Equals(Funcs.Dot.Name))
|
||||
{
|
||||
if (args.Count == 1)
|
||||
{
|
||||
return ToLua(args[0]);
|
||||
}
|
||||
|
||||
if (forceFirstArgInDot)
|
||||
{
|
||||
if (baseFunc.Name.Equals(Funcs.Dot.Name)) {
|
||||
if (args.Count == 1 || forceFirstArgInDot) {
|
||||
return ToLua(args[0]);
|
||||
}
|
||||
|
||||
|
@ -175,8 +153,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
AddDep(baseFunc.Name);
|
||||
|
||||
var argExpressions = new List<string>();
|
||||
foreach (var arg in args)
|
||||
{
|
||||
foreach (var arg in args) {
|
||||
argExpressions.Add(ToLua(arg, key));
|
||||
}
|
||||
|
||||
|
@ -185,35 +162,30 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
|
||||
|
||||
var collected = new List<IExpression>();
|
||||
switch (bare)
|
||||
{
|
||||
switch (bare) {
|
||||
case LuaLiteral lua:
|
||||
return lua.Lua;
|
||||
case FunctionCall fc:
|
||||
var called = _context.DefinedFunctions[fc.CalledFunctionName];
|
||||
if (called.ProfileInternal)
|
||||
{
|
||||
if (called.ProfileInternal) {
|
||||
return called.Name;
|
||||
}
|
||||
|
||||
AddDependenciesFor(called);
|
||||
AddFunction(called);
|
||||
return $"{fc.CalledFunctionName.AsLuaIdentifier()}(tags, parameters)";
|
||||
return $"{fc.CalledFunctionName.AsLuaIdentifier()}(parameters, tags, result)";
|
||||
case Constant c:
|
||||
return ConstantToLua(c);
|
||||
case Mapping m:
|
||||
return MappingToLua(m).Indent();
|
||||
case Function f:
|
||||
var fName = f.Name.TrimStart('$');
|
||||
if (Funcs.Builtins.ContainsKey(fName))
|
||||
{
|
||||
if (Funcs.Builtins.ContainsKey(fName)) {
|
||||
AddDep(f.Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
var definedFunc = _context.DefinedFunctions[fName];
|
||||
if (definedFunc.ProfileInternal)
|
||||
{
|
||||
if (definedFunc.ProfileInternal) {
|
||||
return f.Name;
|
||||
}
|
||||
|
||||
|
@ -235,19 +207,16 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
public string MappingToLua(Mapping m)
|
||||
{
|
||||
var isConstant = true;
|
||||
var contents = m.StringToResultFunctions.Select(kv =>
|
||||
{
|
||||
var contents = m.StringToResultFunctions.Select(kv => {
|
||||
var (key, expr) = kv;
|
||||
var left = "[\"" + key + "\"]";
|
||||
|
||||
if (Regex.IsMatch(key, "^[a-zA-Z][_a-zA-Z-9]*$"))
|
||||
{
|
||||
if (Regex.IsMatch(key, "^[a-zA-Z][_a-zA-Z-9]*$")) {
|
||||
left = key;
|
||||
}
|
||||
|
||||
var luaExpr = ToLua(expr, key);
|
||||
if (luaExpr.Contains("tags"))
|
||||
{
|
||||
if (luaExpr.Contains("tags")) {
|
||||
isConstant = false;
|
||||
}
|
||||
|
||||
|
@ -258,8 +227,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
"{\n " +
|
||||
string.Join(",\n ", contents) +
|
||||
"\n}";
|
||||
if (_staticTables && isConstant)
|
||||
{
|
||||
if (_staticTables && isConstant) {
|
||||
return AddConstant(mapping);
|
||||
}
|
||||
|
||||
|
@ -273,17 +241,16 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
/// <returns></returns>
|
||||
private string ConstantToLua(Constant c)
|
||||
{
|
||||
var o = c.Get();
|
||||
switch (o)
|
||||
{
|
||||
var o = c.Evaluate(_context);
|
||||
switch (o) {
|
||||
case LuaLiteral lua:
|
||||
return lua.Lua;
|
||||
case IExpression e:
|
||||
return ToLua(e);
|
||||
return ConstantToLua(new Constant(e.Types.First(), e.Evaluate(null)));
|
||||
case int i:
|
||||
return i.ToString(CultureInfo.InvariantCulture);
|
||||
return "" + i;
|
||||
case double d:
|
||||
return d.ToString(CultureInfo.InvariantCulture);
|
||||
return "" + d;
|
||||
case string s:
|
||||
return '"' + s.Replace("\"", "\\\"") + '"';
|
||||
case null:
|
||||
|
@ -292,11 +259,9 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
return unpack.Item1 + "[" + unpack.Item2 + "]";
|
||||
case IEnumerable<object> ls:
|
||||
var t = ((ListType) c.Types.First()).InnerType;
|
||||
return "{" + string.Join(", ", ls.Select(obj =>
|
||||
{
|
||||
return "{" + string.Join(", ", ls.Select(obj => {
|
||||
var objInConstant = new Constant(t, obj);
|
||||
if (obj is Constant asConstant)
|
||||
{
|
||||
if (obj is Constant asConstant) {
|
||||
objInConstant = asConstant;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
|
@ -13,8 +12,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
{
|
||||
public void AddFunction(AspectMetadata meta)
|
||||
{
|
||||
if (_alreadyAddedFunctions.Contains(meta.Name))
|
||||
{
|
||||
if (_alreadyAddedFunctions.Contains(meta.Name)) {
|
||||
// already added
|
||||
return;
|
||||
}
|
||||
|
@ -29,55 +27,49 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
|
||||
var funcNameDeclaration = "";
|
||||
|
||||
meta.Visit(e =>
|
||||
{
|
||||
if (e is Function f && f.Name.Equals(Funcs.MemberOf.Name))
|
||||
{
|
||||
meta.Visit(e => {
|
||||
if (e is Function f && f.Name.Equals(Funcs.MemberOf.Name)) {
|
||||
funcNameDeclaration = $"\n local funcName = \"{meta.Name.AsLuaIdentifier()}\"";
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
var expression = Funcs.Either(Funcs.Id, Funcs.Const, meta.ExpressionImplementation)
|
||||
.Apply(new LuaLiteral(Typs.Tags, "tags"))
|
||||
.PruneTypes(t => !(t is Curry))
|
||||
.SpecializeToSmallestType()
|
||||
.Optimize(out _);
|
||||
if (!expression.Types.Any())
|
||||
{
|
||||
throw new Exception("Could not optimize expression with applied tags");
|
||||
}
|
||||
var expression = meta.ExpressionImplementation;
|
||||
|
||||
var ctx = Context;
|
||||
_context = _context.WithAspectName(meta.Name);
|
||||
|
||||
var body = "";
|
||||
if (_useSnippets)
|
||||
{
|
||||
if (_useSnippets) {
|
||||
if (expression.Types.First() is Curry c) {
|
||||
expression = expression.Apply(new LuaLiteral(Typs.Tags, "tags"));
|
||||
}
|
||||
|
||||
body = Utils.Lines(
|
||||
" local r = nil",
|
||||
" " + Snippets.Convert(this, "r", expression).Indent(),
|
||||
" return r"
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
body = " return " + ToLua(expression);
|
||||
}
|
||||
|
||||
|
||||
var impl = Utils.Lines(
|
||||
"--[[",
|
||||
meta.Description,
|
||||
"",
|
||||
"Unit: " + meta.Unit,
|
||||
"Created by " + meta.Author,
|
||||
"Originally defined in " + meta.Filepath,
|
||||
"Uses tags: " + string.Join(", ", possibleTags.Keys),
|
||||
"Used parameters: " + string.Join(", ", usedParams),
|
||||
"Number of combintations: " + numberOfCombinations,
|
||||
"Returns values: ",
|
||||
"]]",
|
||||
"function " + meta.Name.AsLuaIdentifier() + "(tags, parameters)" + funcNameDeclaration,
|
||||
"function " + meta.Name.AsLuaIdentifier() + "(parameters, tags, result)" + funcNameDeclaration,
|
||||
body,
|
||||
"end"
|
||||
);
|
||||
|
|
|
@ -42,14 +42,11 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
|
||||
internal void AddDep(string name)
|
||||
{
|
||||
if (name.StartsWith("mapping"))
|
||||
{
|
||||
Console.Error.WriteLine(">>>");
|
||||
if (name.StartsWith("mapping")) {
|
||||
throw new Exception("A mapping was added as dependency - this is a bug");
|
||||
}
|
||||
|
||||
if (name.Contains("stringToTags"))
|
||||
{
|
||||
if (name.Contains("stringToTags")) {
|
||||
AddDep("table_to_list");
|
||||
}
|
||||
_dependencies.Add(name);
|
||||
|
@ -68,14 +65,11 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
public void AddDependenciesFor(IExpression e)
|
||||
{
|
||||
var (_, functionNames) = e.InList().DirectlyAndInderectlyCalled(_context);
|
||||
foreach (var functionName in functionNames)
|
||||
{
|
||||
if (_context.DefinedFunctions.TryGetValue(functionName, out var aspectMeta))
|
||||
{
|
||||
foreach (var functionName in functionNames) {
|
||||
if (_context.DefinedFunctions.TryGetValue(functionName, out var aspectMeta)) {
|
||||
AddFunction(aspectMeta);
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
AddDep(functionName);
|
||||
}
|
||||
}
|
||||
|
@ -85,15 +79,12 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
{
|
||||
var imps = new List<string>();
|
||||
|
||||
foreach (var name in _dependencies)
|
||||
{
|
||||
foreach (var name in _dependencies) {
|
||||
var path = $"IO/lua/{name}.lua";
|
||||
if (File.Exists(path))
|
||||
{
|
||||
if (File.Exists(path)) {
|
||||
imps.Add(File.ReadAllText(path));
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
throw new FileNotFoundException(path);
|
||||
}
|
||||
}
|
||||
|
@ -115,8 +106,7 @@ namespace AspectedRouting.IO.LuaSkeleton
|
|||
private readonly Dictionary<string, uint> counters = new Dictionary<string, uint>();
|
||||
public string FreeVar(string key)
|
||||
{
|
||||
if (!counters.ContainsKey(key))
|
||||
{
|
||||
if (!counters.ContainsKey(key)) {
|
||||
counters[key] = 0;
|
||||
return key;
|
||||
}
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
|
@ -13,14 +12,14 @@ namespace AspectedRouting.IO.itinero1
|
|||
var contents = tags.Select(kv =>
|
||||
{
|
||||
var (key, value) = kv;
|
||||
var left = "[\"" + key .ToString(CultureInfo.InvariantCulture)+ "\"]";
|
||||
var left = "[\"" + key + "\"]";
|
||||
|
||||
if (Regex.IsMatch(key, "^[a-zA-Z][_a-zA-Z-9]*$"))
|
||||
{
|
||||
left = key;
|
||||
}
|
||||
|
||||
return $"{left.ToString(CultureInfo.InvariantCulture)} = \"{value.ToString(CultureInfo.InvariantCulture)}\"";
|
||||
return $"{left} = \"{value}\"";
|
||||
});
|
||||
return "{" + string.Join(", ", contents) + "}";
|
||||
}
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Tests;
|
||||
|
||||
|
@ -82,8 +81,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
foreach (var key in keysToCheck)
|
||||
{
|
||||
var newKey = key.Replace(".", "_");
|
||||
if (newKey == key)
|
||||
{
|
||||
if (newKey == key) {
|
||||
continue;
|
||||
}
|
||||
tags[newKey] = tags[key];
|
||||
|
@ -95,10 +93,9 @@ namespace AspectedRouting.IO.itinero1
|
|||
tags.Remove("#" + paramName);
|
||||
}
|
||||
|
||||
var expectedPriority = expected.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
if (invertPriority)
|
||||
{
|
||||
expectedPriority = $"inv({expectedPriority.ToString(CultureInfo.InvariantCulture)})";
|
||||
var expectedPriority = "" + expected.Priority;
|
||||
if (invertPriority) {
|
||||
expectedPriority = $"inv({expectedPriority})";
|
||||
}
|
||||
|
||||
// Generates something like:
|
||||
|
@ -107,7 +104,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
$"unit_test_profile(behaviour_{testSuite.Profile.Name.AsLuaIdentifier()}_{testSuite.BehaviourName.AsLuaIdentifier()}, " +
|
||||
$"\"{testSuite.BehaviourName}\", " +
|
||||
$"{index}, " +
|
||||
$"{{access = \"{D(expected.Access)}\", speed = {expected.Speed.ToString(CultureInfo.InvariantCulture)}, oneway = \"{D(expected.Oneway)}\", priority = {expectedPriority} }}, " +
|
||||
$"{{access = \"{D(expected.Access)}\", speed = {expected.Speed}, oneway = \"{D(expected.Oneway)}\", priority = {expectedPriority} }}, " +
|
||||
tags.ToLuaTable() +
|
||||
")";
|
||||
}
|
||||
|
@ -152,7 +149,8 @@ namespace AspectedRouting.IO.itinero1
|
|||
|
||||
_skeleton.AddDep("unitTest");
|
||||
_skeleton.AddDep("debug_table");
|
||||
return $"unit_test({functionToApplyName.AsLuaIdentifier()}, \"{functionToApplyName}\", {index.ToString(CultureInfo.InvariantCulture)}, \"{expected.ToString(CultureInfo.InvariantCulture)}\", {parameters.ToLuaTable()}, {tags.ToLuaTable()})";
|
||||
return
|
||||
$"unit_test({functionToApplyName.AsLuaIdentifier()}, \"{functionToApplyName}\", {index}, \"{expected}\", {parameters.ToLuaTable()}, {tags.ToLuaTable()})";
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -15,8 +15,7 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
{
|
||||
var c = lua.Context;
|
||||
|
||||
if (!(args[0].Evaluate(c) is List<IExpression> order))
|
||||
{
|
||||
if (!(args[0].Evaluate(c) is List<IExpression> order)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -24,18 +23,15 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
if (!UnApply(
|
||||
IsFunc(Funcs.StringStringToTags),
|
||||
IsMapping(mappings)
|
||||
).Invoke(args[1]))
|
||||
{
|
||||
).Invoke(args[1])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (mappings.Count != 1)
|
||||
{
|
||||
if (mappings.Count != 1) {
|
||||
throw new Exception("Multiple possible implementations at this point - should not happen");
|
||||
}
|
||||
|
||||
if (mappings.Count == 0)
|
||||
{
|
||||
if (mappings.Count == 0) {
|
||||
|
||||
}
|
||||
var mapping = mappings.First();
|
||||
|
@ -44,22 +40,18 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
var varName = "tags";
|
||||
|
||||
var result = "";
|
||||
if (tags is LuaLiteral literal)
|
||||
{
|
||||
if (tags is LuaLiteral literal) {
|
||||
varName = literal.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
result += Snippets.Convert(lua, "tags", tags);
|
||||
}
|
||||
|
||||
// We _reverse_ the order, so that the _most_ important one is at the _bottom_
|
||||
// The most important one will then _overwrite_ the result value
|
||||
order.Reverse();
|
||||
foreach (var t in order)
|
||||
{
|
||||
if (!(t.Evaluate(c) is string key))
|
||||
{
|
||||
foreach (var t in order) {
|
||||
if (!(t.Evaluate(c) is string key)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -70,9 +62,8 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
result += "\n";
|
||||
result += "end\n";
|
||||
// note: we do not do an 'elseif' as we have to fallthrough
|
||||
if (result.Contains("tags[\"nil\"]"))
|
||||
{
|
||||
Console.WriteLine("Warning: FirstMatchOf has a 'nil' in the indexes due to expression " + t.ToString());
|
||||
if (result.Contains("tags[\"nil\"]")) {
|
||||
Console.WriteLine("EUHM");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -20,25 +20,21 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
UnApply(IsFunc(Funcs.StringStringToTags),
|
||||
IsMapping(mappings)),
|
||||
Assign(actualArgs)
|
||||
).Invoke(args[0]))
|
||||
{
|
||||
).Invoke(args[0])) {
|
||||
var actualArg = actualArgs.First();
|
||||
var mapping = mappings.First();
|
||||
|
||||
if (mapping.StringToResultFunctions.Count != 1)
|
||||
{
|
||||
if (mapping.StringToResultFunctions.Count != 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var (key, func) = mapping.StringToResultFunctions.ToList().First();
|
||||
var result = "";
|
||||
var tags = "";
|
||||
if (actualArg is LuaLiteral l)
|
||||
{
|
||||
if (actualArg is LuaLiteral l) {
|
||||
tags = l.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
tags = lua.FreeVar("tags");
|
||||
result += "local " + tags+"\n";
|
||||
result += Snippets.Convert(lua, tags, actualArg);
|
||||
|
|
|
@ -11,12 +11,11 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
public override string Convert(LuaSkeleton.LuaSkeleton lua, string assignTo, List<IExpression> args)
|
||||
{
|
||||
var fCond = args[0].Optimize(out _);
|
||||
var fCond = args[0].Optimize();
|
||||
var fValue = args[1];
|
||||
IExpression fElse = null;
|
||||
var arg = args[2];
|
||||
if (args.Count == 4)
|
||||
{
|
||||
if (args.Count == 4) {
|
||||
arg = args[3];
|
||||
fElse = args[2];
|
||||
}
|
||||
|
@ -30,8 +29,7 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
result += $"if ( {c} or {c} == \"yes\" ) then \n";
|
||||
result += " " + Snippets.Convert(lua, assignTo, fValue.Apply(arg)).Indent() ;
|
||||
|
||||
if (fElse != null)
|
||||
{
|
||||
if (fElse != null) {
|
||||
result += "else\n";
|
||||
result += " " + Snippets.Convert(lua, assignTo, fElse.Apply(arg)).Indent();
|
||||
}
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using static AspectedRouting.Language.Deconstruct;
|
||||
|
||||
namespace AspectedRouting.IO.LuaSnippets
|
||||
{
|
||||
|
@ -13,51 +11,23 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
public override string Convert(LuaSkeleton.LuaSkeleton lua, string assignTo, List<IExpression> args)
|
||||
{
|
||||
var cond = args[0].Optimize(out _);
|
||||
var cond = args[0].Optimize();
|
||||
var ifTrue = args[1];
|
||||
IExpression ifElse = null;
|
||||
if (args.Count == 3)
|
||||
{
|
||||
if (args.Count == 3) {
|
||||
ifElse = args[2];
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
var fa = new List<IExpression>();
|
||||
if (UnApply(
|
||||
IsFunc(Funcs.IsNull),
|
||||
Assign(fa)
|
||||
).Invoke(cond))
|
||||
{
|
||||
|
||||
if (fa.First().ToString() == ifElse.ToString())
|
||||
{
|
||||
var result = "";
|
||||
|
||||
// We calculate the value that we need
|
||||
result += Snippets.Convert(lua, assignTo, ifElse) + "\n";
|
||||
result += "if (" + assignTo + " == nil) then\n";
|
||||
result += " " + Snippets.Convert(lua, assignTo, ifTrue).Indent();
|
||||
result += "end\n";
|
||||
return result;
|
||||
|
||||
}
|
||||
throw new Exception("TODO optimize with default");
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var c = lua.FreeVar("cond");
|
||||
var result = "";
|
||||
result += "local " + c+"\n";
|
||||
|
||||
var isString = cond.Types.First().Equals(Typs.String);
|
||||
result += Snippets.Convert(lua, c, cond)+"\n";
|
||||
result += $"if ( {c} == true or {c} == \"yes\" ) then \n";
|
||||
result += $"if ( {c} or {c} == \"yes\" ) then \n";
|
||||
result += " " + Snippets.Convert(lua, assignTo, ifTrue).Indent() ;
|
||||
|
||||
if (ifElse != null)
|
||||
{
|
||||
if (ifElse != null) {
|
||||
result += "else\n";
|
||||
result += " " + Snippets.Convert(lua, assignTo, ifElse).Indent();
|
||||
}
|
||||
|
@ -67,4 +37,3 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -21,35 +21,29 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
public override string Convert(LuaSkeleton.LuaSkeleton lua, string assignTo, List<IExpression> args)
|
||||
{
|
||||
|
||||
// Multiply multiplies a list of values - we thus have to handle _each_ arg
|
||||
// Note: we get a single argument which is an expression resulting in a list of values
|
||||
|
||||
{
|
||||
var listToMultiply = args[0];
|
||||
var mappings = new List<Mapping>();
|
||||
var arg = new List<IExpression>();
|
||||
if (args.Count == 1 && UnApply(UnApply(
|
||||
if (UnApply(UnApply(
|
||||
IsFunc(Funcs.StringStringToTags),
|
||||
IsMapping(mappings)),
|
||||
Assign(arg)
|
||||
).Invoke(args[0]))
|
||||
{
|
||||
).Invoke(listToMultiply)) {
|
||||
var mapping = mappings.First();
|
||||
|
||||
var result = assignTo + " = " + _neutralValue + "\n";
|
||||
var mappingArg = arg.First();
|
||||
if (!Equals(mappingArg.Types.First(), Typs.Tags))
|
||||
{
|
||||
if (!Equals(mappingArg.Types.First(), Typs.Tags)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string tags;
|
||||
if (mappingArg is LuaLiteral literal)
|
||||
{
|
||||
if (mappingArg is LuaLiteral literal) {
|
||||
tags = literal.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
tags = lua.FreeVar("tags");
|
||||
result += "local " + tags + " = nil\n";
|
||||
result += Snippets.Convert(lua, tags, mappingArg);
|
||||
|
@ -58,14 +52,12 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
var m = lua.FreeVar("m");
|
||||
result += " local " + m + " = nil\n";
|
||||
|
||||
foreach (var (key, func) in mapping.StringToResultFunctions)
|
||||
{
|
||||
foreach (var (key, func) in mapping.StringToResultFunctions) {
|
||||
result += "if (" + tags + "[\"" + key + "\"] ~= nil) then\n";
|
||||
result += m + " = nil\n";
|
||||
result += " " +
|
||||
Snippets.Convert(lua, m,
|
||||
func.Apply(new LuaLiteral(Typs.String, tags + "[\"" + key + "\"]"))).Indent() +
|
||||
"\n";
|
||||
func.Apply(new LuaLiteral(Typs.String, tags + "[\"" + key + "\"]"))).Indent() + "\n";
|
||||
result += "\n\n if (" + m + " ~= nil) then\n " +
|
||||
Combine(assignTo, m) +
|
||||
"\n end\n";
|
||||
|
@ -74,32 +66,25 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
{
|
||||
// Print a 'listDot', assume 'tags' is the applied argument
|
||||
var arg = new List<IExpression>();
|
||||
|
||||
|
||||
var listDotArgs = new List<IExpression>();
|
||||
if (args.Count == 1 && UnApply(
|
||||
if (UnApply(
|
||||
UnApply(IsFunc(Funcs.ListDot),
|
||||
Assign(listDotArgs)),
|
||||
Assign(arg)
|
||||
).Invoke(args[0]))
|
||||
{
|
||||
).Invoke(listToMultiply)) {
|
||||
var listDotArg = arg.First();
|
||||
if (!(listDotArgs.First().Evaluate(lua.Context) is List<IExpression> functionsToApply))
|
||||
{
|
||||
if (!(listDotArgs.First().Evaluate(lua.Context) is List<IExpression> functionsToApply)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = " " + assignTo + " = " + _neutralValue + "\n";
|
||||
string tags;
|
||||
if (listDotArg is LuaLiteral literal)
|
||||
{
|
||||
if (listDotArg is LuaLiteral literal) {
|
||||
tags = literal.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
tags = lua.FreeVar("tags");
|
||||
result += " local " + tags + "\n";
|
||||
result += Snippets.Convert(lua, tags, listDotArg);
|
||||
|
@ -107,19 +92,16 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
var m = lua.FreeVar("m");
|
||||
result += " local " + m + "\n";
|
||||
foreach (var func in functionsToApply)
|
||||
{
|
||||
foreach (var func in functionsToApply) {
|
||||
result += " " + m + " = nil\n";
|
||||
var subMapping = ExtractSubMapping(func);
|
||||
if (subMapping != null)
|
||||
{
|
||||
if (subMapping != null) {
|
||||
var (key, f) = subMapping.Value;
|
||||
var e = f.Apply(new LuaLiteral(Typs.String, tags + "[\"" + key + "\"]"));
|
||||
e = e.Optimize(out _);
|
||||
e = e.Optimize();
|
||||
result += Snippets.Convert(lua, m, e).Indent();
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
result += Snippets.Convert(lua, m, func.Apply(new LuaLiteral(Typs.Tags, "tags")));
|
||||
}
|
||||
|
||||
|
@ -127,44 +109,11 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
result += "\n\n if (" + m + " ~= nil) then\n " + Combine(assignTo, m) + "\n end\n";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
{
|
||||
|
||||
|
||||
var constantArgs = new List<Constant>();
|
||||
if (args.Count == 1 && IsConstant(constantArgs).Invoke(args[0]))
|
||||
{
|
||||
if (!(constantArgs.First().Get() is List<IExpression> listItems))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = " " + assignTo + " = " + _neutralValue + "\n";
|
||||
|
||||
|
||||
var m = lua.FreeVar("m");
|
||||
result += " local " + m + "\n";
|
||||
foreach (var listItem in listItems)
|
||||
{
|
||||
result += " " + m + " = nil\n";
|
||||
result += Snippets.Convert(lua, m, listItem).Indent();
|
||||
result += "\n\n if (" + m + " ~= nil) then\n " + Combine(assignTo, m) + "\n end\n";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Console.Error.WriteLine("ListFoldingSnippet encountered an unsupported expression");
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
|
@ -188,11 +137,9 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
IsFunc(Funcs.StringStringToTags),
|
||||
IsMapping(mappings)
|
||||
)
|
||||
).Invoke(app))
|
||||
{
|
||||
).Invoke(app)) {
|
||||
var mapping = mappings.First();
|
||||
if (mapping.StringToResultFunctions.Count == 1)
|
||||
{
|
||||
if (mapping.StringToResultFunctions.Count == 1) {
|
||||
var kv = mapping.StringToResultFunctions.ToList().First();
|
||||
return (kv.Key, kv.Value);
|
||||
}
|
||||
|
|
|
@ -19,12 +19,10 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
|
||||
var tags = "";
|
||||
var result = "";
|
||||
if (tagsToken is LuaLiteral lit)
|
||||
{
|
||||
if (tagsToken is LuaLiteral lit) {
|
||||
tags = lit.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
tags = lua.FreeVar("tags");
|
||||
result += "local " + tags + "\n";
|
||||
result += Snippets.Convert(lua, tags, tagsToken);
|
||||
|
|
|
@ -17,12 +17,10 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
var result = "";
|
||||
var neededKeys = lua.FreeVar("neededKeys");
|
||||
var tags = "";
|
||||
if (tagsExpr is LuaLiteral literal)
|
||||
{
|
||||
if (tagsExpr is LuaLiteral literal) {
|
||||
tags = literal.Lua;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
tags = lua.FreeVar("tags");
|
||||
result += $"local {tags}";
|
||||
result += Snippets.Convert(lua, tags, tagsExpr);
|
||||
|
|
|
@ -26,11 +26,9 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
var vLua = new LuaLiteral(Typs.String, v);
|
||||
|
||||
var mappings = new List<string>();
|
||||
foreach (var kv in _mapping.StringToResultFunctions)
|
||||
{
|
||||
foreach (var kv in _mapping.StringToResultFunctions) {
|
||||
var f = kv.Value;
|
||||
if (f.Types.First() is Curry)
|
||||
{
|
||||
if (f.Types.First() is Curry) {
|
||||
f = f.Apply(vLua);
|
||||
}
|
||||
mappings.Add("if (" + v + " == \"" + kv.Key + "\") then\n " + assignTo + " = " + lua.ToLua(f));
|
||||
|
|
|
@ -33,44 +33,37 @@ namespace AspectedRouting.IO.LuaSnippets
|
|||
public static string Convert(LuaSkeleton.LuaSkeleton lua, string assignTo, IExpression e)
|
||||
{
|
||||
|
||||
var opt = e.Optimize(out _);
|
||||
var opt = e.Optimize();
|
||||
// Note that optimization might optimize to a _subtype_ of the original expresion - which is fine!
|
||||
var origType = e.Types.First();
|
||||
var optType = opt.Types.First();
|
||||
if (!origType.Equals(optType) && !origType.IsSuperSet(optType))
|
||||
{
|
||||
if (!origType.Equals(optType) && !origType.IsSuperSet(optType)) {
|
||||
throw new Exception("Optimization went wrong!");
|
||||
}
|
||||
e = opt;
|
||||
var deconstructed = e.DeconstructApply();
|
||||
|
||||
if (deconstructed != null)
|
||||
{
|
||||
if (deconstructed != null){
|
||||
|
||||
if (deconstructed.Value.f is Mapping m)
|
||||
{
|
||||
if (deconstructed.Value.f is Mapping m) {
|
||||
return new SimpleMappingSnippet(m).Convert(lua, assignTo, deconstructed.Value.args);
|
||||
}
|
||||
|
||||
if (deconstructed.Value.f is Function f
|
||||
&& SnippetsIndex.TryGetValue(f.Name, out var snippet))
|
||||
{
|
||||
&& SnippetsIndex.TryGetValue(f.Name, out var snippet)) {
|
||||
var optimized = snippet.Convert(lua, assignTo, deconstructed.Value.args);
|
||||
if (optimized != null)
|
||||
{
|
||||
if (optimized != null) {
|
||||
return optimized + "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
|
||||
|
||||
return assignTo + " = " + lua.ToLua(e)+"\n";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
catch (Exception err) {
|
||||
return "print(\"ERROR COMPILER BUG\");\n";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,8 +14,7 @@ namespace AspectedRouting.IO
|
|||
{
|
||||
public static void GenerateHelpText(string saveTo = null)
|
||||
{
|
||||
var format = File.ReadAllText("Format.md");
|
||||
var helpText = format + "\n\n" + TypeOverview +
|
||||
var helpText = TypeOverview +
|
||||
FunctionOverview;
|
||||
|
||||
if (saveTo == null)
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.IO.LuaSkeleton;
|
||||
using AspectedRouting.IO.LuaSnippets;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
|
@ -15,9 +14,9 @@ namespace AspectedRouting.IO.itinero1
|
|||
private string GenerateMainProfileFunction()
|
||||
{
|
||||
|
||||
var access = _skeleton.ToLuaWithTags(_profile.Access);
|
||||
var oneway = _skeleton.ToLuaWithTags(_profile.Oneway);
|
||||
var speed = _skeleton.ToLuaWithTags(_profile.Speed);
|
||||
var access = _skeleton.ToLua(_profile.Access);
|
||||
var oneway = _skeleton.ToLua(_profile.Oneway);
|
||||
var speed = _skeleton.ToLua(_profile.Speed);
|
||||
|
||||
var impl = string.Join("\n",
|
||||
"",
|
||||
|
@ -28,6 +27,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
"Comfort is calculated as well, based on the parameters which are padded in",
|
||||
"",
|
||||
"Created by " + _profile.Author,
|
||||
"Originally defined in " + _profile.Filename,
|
||||
"]]",
|
||||
"function " + _profile.Name + "(parameters, tags, result)",
|
||||
"",
|
||||
|
@ -54,22 +54,18 @@ namespace AspectedRouting.IO.itinero1
|
|||
impl +=
|
||||
"\n local priority = 0\n ";
|
||||
|
||||
var tags = new LuaLiteral(Typs.Tags, "tags");
|
||||
foreach (var (parameterName, expression) in _profile.Priority)
|
||||
{
|
||||
var paramInLua = _skeleton.ToLua(new Parameter(parameterName));
|
||||
|
||||
|
||||
var expr = Funcs.Either(Funcs.Id, Funcs.Const, expression).Apply(tags)
|
||||
.SpecializeToSmallestType()
|
||||
.PruneTypes(t => !(t is Curry))
|
||||
.Optimize(out _);
|
||||
|
||||
if (expr.Types.Any(t => t.Name.Equals(Typs.Bool.Name)))
|
||||
var exprInLua = _skeleton.ToLua(expression.Optimize(), forceFirstArgInDot: true);
|
||||
var resultTypes = expression.Types.Select(t => t.Uncurry().Last());
|
||||
if (resultTypes.Any(t => t.Name.Equals(Typs.Bool.Name)))
|
||||
{
|
||||
expr = Funcs.Parse.Apply(expr).SpecializeToSmallestType();
|
||||
_skeleton. AddDep("parse");
|
||||
exprInLua = "parse(" + exprInLua + ")";
|
||||
}
|
||||
var exprInLua = _skeleton.ToLua(expr);
|
||||
|
||||
impl += "\n " + string.Join("\n ",
|
||||
$"if({paramInLua} ~= 0) then",
|
||||
|
@ -78,14 +74,8 @@ namespace AspectedRouting.IO.itinero1
|
|||
);
|
||||
}
|
||||
|
||||
var scalingFactor = Funcs.Default.Apply(new Constant(Typs.Double, 1.0), _profile.ScalingFactor, tags);
|
||||
|
||||
impl += string.Join("\n",
|
||||
" -- Calculate the scaling factor",
|
||||
" local scalingfactor",
|
||||
Snippets.Convert(_skeleton, "scalingfactor", scalingFactor.SpecializeToSmallestType()),
|
||||
"",
|
||||
"priority = priority * scalingfactor",
|
||||
"",
|
||||
"",
|
||||
" if (priority <= 0) then",
|
||||
|
@ -119,15 +109,9 @@ namespace AspectedRouting.IO.itinero1
|
|||
var functionName = referenceName.AsLuaIdentifier();
|
||||
behaviourParameters.TryGetValue("description", out var description);
|
||||
|
||||
_skeleton.AddDep("copy_tags");
|
||||
var usedkeys = _profile.AllExpressionsFor(behaviourName, _context)
|
||||
.PossibleTagsRecursive(_context)
|
||||
.Select(t => "\"" + t.Key + "\"")
|
||||
.ToHashSet();
|
||||
|
||||
_skeleton.AddDep("remove_relation_prefix");
|
||||
var impl = string.Join("\n",
|
||||
"behaviour_" + functionName + "_used_keys = create_set({" + string.Join(", ", usedkeys) + "})",
|
||||
"",
|
||||
"--[[",
|
||||
description,
|
||||
"]]",
|
||||
|
@ -141,7 +125,6 @@ namespace AspectedRouting.IO.itinero1
|
|||
impl += _parameterPrinter.DeclareParametersFor(behaviourParameters);
|
||||
|
||||
impl += " " + _profile.Name + "(parameters, tags, result)\n";
|
||||
impl += " copy_tags(tags, result.attributes_to_keep, behaviour_" + functionName + "_used_keys)\n";
|
||||
impl += "end\n";
|
||||
return (functionName, impl);
|
||||
}
|
||||
|
|
|
@ -57,7 +57,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
func.Add("");
|
||||
func.Add(" subresult.attributes_to_keep = {}");
|
||||
func.Add(" parameters = default_parameters()");
|
||||
func.Add($" matched = {preProcName}(relation_tags, parameters)");
|
||||
func.Add($" matched = {preProcName}(parameters, relation_tags, subresult)");
|
||||
func.Add(" if (matched) then");
|
||||
var tagKey = "_relation:" + calledInFunction.AsLuaIdentifier();
|
||||
extraKeys.Add(tagKey);
|
||||
|
@ -90,7 +90,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
func.Add(" parameters = default_parameters()");
|
||||
func.Add(_parameterPrinter.DeclareParametersFor(parameters.Where(kv => usedParameters.Contains(kv.Key))
|
||||
.ToDictionary(kv => kv.Key, kv => kv.Value)));
|
||||
func.Add($" matched = {preProcName}(relation_tags, parameters)");
|
||||
func.Add($" matched = {preProcName}(parameters, relation_tags, subresult)");
|
||||
func.Add(" if (matched) then");
|
||||
tagKey = "_relation:" + behaviourName.AsLuaIdentifier() + ":" + calledInFunction.AsLuaIdentifier();
|
||||
extraKeys.Add(tagKey);
|
||||
|
|
|
@ -27,7 +27,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
_aspectTestSuites = aspectTestSuites?.Where(suite => suite != null)
|
||||
?.Select(testSuite => testSuite.WithoutRelationTests())?.ToList();
|
||||
_profileTests = profileTests;
|
||||
_skeleton = new LuaSkeleton.LuaSkeleton(context, true);
|
||||
_skeleton = new LuaSkeleton.LuaSkeleton(context, false);
|
||||
_parameterPrinter = new LuaParameterPrinter(profile, _skeleton);
|
||||
}
|
||||
|
||||
|
@ -38,8 +38,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
var (membershipFunction, extraKeys) = GenerateMembershipPreprocessor();
|
||||
var (profileOverview, behaviourFunctions) = GenerateProfileFunctions();
|
||||
var mainFunction = GenerateMainProfileFunction();
|
||||
var tests = new LuaTestPrinter(_skeleton, new List<string> { "unitTest", "unitTestProfile" })
|
||||
.GenerateFullTestSuite(_profileTests, _aspectTestSuites);
|
||||
var tests = new LuaTestPrinter(_skeleton, new List<string>{"unitTest","unitTestProfile"}).GenerateFullTestSuite(_profileTests, _aspectTestSuites);
|
||||
|
||||
|
||||
var keys = _profile.AllExpressions(_context).PossibleTags().Keys
|
||||
|
@ -49,10 +48,10 @@ namespace AspectedRouting.IO.itinero1
|
|||
|
||||
var header = new List<string>
|
||||
{
|
||||
$"-- Itinero 1.0-profile, generated by AspectedRouting.",
|
||||
$"-- Itinero 1.0-profile, generated by AspectedRouting. Last source file change is {_profile.LastChange:s}",
|
||||
$"name = \"{_profile.Name}\"",
|
||||
"normalize = false",
|
||||
"vehicle_types = {" + string.Join(", ", _profile.VehicleTyps.Select(s => "\"" + s + "\"")) + "}",
|
||||
"vehicle_type = {" + string.Join(", ", _profile.VehicleTyps.Select(s => "\"" + s + "\"")) + "}",
|
||||
// meta_whitelist is defined in the profile file, these are tags that are included in the generated route, but are not relevant for determining weights
|
||||
"meta_whitelist = {\n"
|
||||
+ string.Join("\n , ", _profile.Metadata.Select(s => "\"" + s + "\""))
|
||||
|
@ -63,15 +62,7 @@ namespace AspectedRouting.IO.itinero1
|
|||
"",
|
||||
profileOverview,
|
||||
"",
|
||||
_parameterPrinter.GenerateDefaultParameters(),
|
||||
"",
|
||||
"function create_set(list)",
|
||||
" local set = {}",
|
||||
" for _, l in ipairs(list) do " +
|
||||
" set[l] = true" +
|
||||
" end",
|
||||
" return set",
|
||||
"end"
|
||||
_parameterPrinter.GenerateDefaultParameters()
|
||||
};
|
||||
|
||||
|
||||
|
@ -151,8 +142,6 @@ namespace AspectedRouting.IO.itinero1
|
|||
"test_all()",
|
||||
"if (not failed_tests and not failed_profile_tests) then",
|
||||
" print(\"Tests OK\")",
|
||||
"else",
|
||||
" error(\"Some tests failed\")",
|
||||
"end"
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,11 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AspectedRouting.IO.LuaSkeleton;
|
||||
using AspectedRouting.IO.LuaSnippets;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
|
||||
namespace AspectedRouting.IO.itinero2
|
||||
|
@ -15,43 +11,56 @@ namespace AspectedRouting.IO.itinero2
|
|||
private string GenerateFactorFunction()
|
||||
{
|
||||
var parameters = new Dictionary<string, IExpression>();
|
||||
foreach (var (name, value) in _profile.DefaultParameters) parameters[name] = value;
|
||||
foreach (var (name, value) in _profile.DefaultParameters)
|
||||
{
|
||||
parameters[name] = value;
|
||||
}
|
||||
|
||||
foreach (var (name, value) in _profile.Behaviours[_behaviourName]) parameters[name] = value;
|
||||
foreach (var (name, value) in _profile.Behaviours[_behaviourName])
|
||||
{
|
||||
parameters[name] = value;
|
||||
}
|
||||
|
||||
|
||||
var aspects = new List<string>();
|
||||
var tags = new LuaLiteral(Typs.Tags, "tags");
|
||||
|
||||
foreach (var (paramName, expr) in _profile.Priority)
|
||||
{
|
||||
var weightExpr = parameters[paramName].Evaluate(_context);
|
||||
if (!(weightExpr is double weight)) continue;
|
||||
if (!(weightExpr is double weight))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (weight == 0) continue;
|
||||
if (weight == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The expression might still have multiple typings,
|
||||
// which take inputs different from 'Tags', so we specialize the expr first
|
||||
var appliedExpr = Funcs.Either(Funcs.Id, Funcs.Const, expr)
|
||||
.Apply(tags)
|
||||
.PruneTypes(tp => !(tp is Curry));
|
||||
var exprSpecialized = appliedExpr.Optimize(out _);
|
||||
|
||||
if (exprSpecialized.Types.First().Equals(Typs.Bool) ||
|
||||
exprSpecialized.Types.First().Equals(Typs.String))
|
||||
{
|
||||
_skeleton.AddDep("parse");
|
||||
exprSpecialized = Funcs.Parse.Apply(exprSpecialized);
|
||||
var exprSpecialized = expr;
|
||||
var resultType = expr.Types.First();
|
||||
if (exprSpecialized.Types.Count() >=2) {
|
||||
exprSpecialized = expr.Specialize(new Curry(Typs.Tags, new Var("a")));
|
||||
if (exprSpecialized == null) {
|
||||
throw new Exception("Could not specialize expression to type tags -> $a");
|
||||
}
|
||||
resultType = (exprSpecialized.Types.First() as Curry).ResultType;
|
||||
}
|
||||
|
||||
var exprInLua = _skeleton.ToLua(exprSpecialized);
|
||||
if (exprInLua.Contains("constRight") || exprInLua.Contains("firstArg"))
|
||||
throw new Exception("Not optimized properly:" + exprSpecialized.Repr());
|
||||
aspects.Add(weight.ToString(CultureInfo.InvariantCulture) + " * " + exprInLua.ToString(CultureInfo.InvariantCulture));
|
||||
if (resultType.Equals(Typs.Bool) || resultType.Equals(Typs.String))
|
||||
{
|
||||
_skeleton.AddDep("parse");
|
||||
exprInLua = "parse(" + exprInLua + ")";
|
||||
}
|
||||
|
||||
var scalingFactor = Funcs.Default.Apply(new Constant(Typs.Double, 1.0), _profile.ScalingFactor, tags)
|
||||
.SpecializeToSmallestType();
|
||||
var code = new List<string>
|
||||
aspects.Add(weight + " * " + exprInLua);
|
||||
}
|
||||
|
||||
Console.WriteLine(aspects.Lined());
|
||||
var code = new List<string>()
|
||||
{
|
||||
"--[[",
|
||||
"Generates the factor according to the priorities and the parameters for this behaviour",
|
||||
|
@ -60,64 +69,12 @@ namespace AspectedRouting.IO.itinero2
|
|||
"function calculate_priority(parameters, tags, result, access, oneway, speed)",
|
||||
" local distance = 1",
|
||||
" local priority = \n " + string.Join(" +\n ", aspects),
|
||||
"",
|
||||
"local scalingfactor",
|
||||
Snippets.Convert(_skeleton, "scalingfactor", scalingFactor),
|
||||
" return priority * scalingfactor",
|
||||
" return priority",
|
||||
"end"
|
||||
};
|
||||
return code.Lined();
|
||||
}
|
||||
|
||||
private string GenerateTurnCostFunction()
|
||||
{
|
||||
var vehicleTypes = _profile.VehicleTyps;
|
||||
_skeleton.AddDep("containedIn");
|
||||
_skeleton.AddDep("str_split");
|
||||
_skeleton.AddDep("calculate_turn_cost_factor");
|
||||
|
||||
|
||||
/**
|
||||
* Calculates the turn cost factor for relation attributes or obstacles.
|
||||
Keep in mind that there are no true relations in the routerDB anymore, instead the attributes are copied onto a turn cost object.
|
||||
This turn cost object has a set of sequence of edges and is applied onto the vertex.0
|
||||
|
||||
Obstacles such as bollards are converted into a turn cost as well.
|
||||
calculate_turn_cost_factor will be called for this bollard too to calculate the weight.
|
||||
|
||||
If result.factor = -1 if passing is not possible - this is more or less equal to an infinite cost
|
||||
If result.factor = 0 if no weight/passing is possible
|
||||
If result.factor is positive, that is the cost.
|
||||
|
||||
There is no forward or backward, so this should always be the same for the same attributes
|
||||
*/
|
||||
var parameters = _profile.Behaviours[_behaviourName];
|
||||
var tags = new LuaLiteral(Typs.Tags, "attributes");
|
||||
var hasAccess = _profile.ObstacleAccess.Apply(tags).SpecializeToSmallestType().Optimize(out _);
|
||||
var code = new List<string>
|
||||
{
|
||||
"--[[ Function called by itinero2 on every turn restriction relation", " ]]",
|
||||
"function turn_cost_factor(attributes, result)",
|
||||
" local parameters = default_parameters()",
|
||||
_parameterPrinter.DeclareParametersFor(parameters),
|
||||
"local has_access",
|
||||
Snippets.Convert(_skeleton, "has_access", hasAccess),
|
||||
"if ( has_access == \"no\" or has_access == \"false\") then",
|
||||
" result.factor = -1",
|
||||
"else",
|
||||
Snippets.Convert(_skeleton, "result.factor", _profile.ObstacleCost.Apply(tags).SpecializeToSmallestType().Optimize(out _)),
|
||||
"end",
|
||||
|
||||
" -- not known by the profile or invalid value - use the default implementation",
|
||||
" if (result.factor == nil) then",
|
||||
" result.factor = calculate_turn_cost_factor(attributes, vehicle_types)",
|
||||
" end",
|
||||
"end",
|
||||
""
|
||||
};
|
||||
return code.Lined();
|
||||
}
|
||||
|
||||
private string GenerateMainFunction()
|
||||
{
|
||||
var parameters = _profile.Behaviours[_behaviourName];
|
||||
|
@ -128,7 +85,6 @@ There is no forward or backward, so this should always be the same for the same
|
|||
|
||||
_skeleton.AddDep("eq");
|
||||
_skeleton.AddDep("remove_relation_prefix");
|
||||
_skeleton.AddDep("debug_table");
|
||||
var code = new List<string>
|
||||
{
|
||||
"--[[",
|
||||
|
@ -152,7 +108,7 @@ There is no forward or backward, so this should always be the same for the same
|
|||
" local parameters = default_parameters()",
|
||||
_parameterPrinter.DeclareParametersFor(parameters),
|
||||
"",
|
||||
" local oneway = " + _skeleton.ToLuaWithTags(_profile.Oneway).Indent(),
|
||||
" local oneway = " + _skeleton.ToLua(_profile.Oneway),
|
||||
" tags.oneway = oneway",
|
||||
" -- An aspect describing oneway should give either 'both', 'against' or 'width'",
|
||||
|
||||
|
@ -160,7 +116,7 @@ There is no forward or backward, so this should always be the same for the same
|
|||
"",
|
||||
" -- forward calculation. We set the meta tag '_direction' to 'width' to indicate that we are going forward. The other functions will pick this up",
|
||||
" tags[\"_direction\"] = \"with\"",
|
||||
" local access_forward = " + _skeleton.ToLuaWithTags(_profile.Access).Indent(),
|
||||
" local access_forward = " + _skeleton.ToLua(_profile.Access),
|
||||
" if(oneway == \"against\") then",
|
||||
" -- no 'oneway=both' or 'oneway=with', so we can only go back over this segment",
|
||||
" -- we overwrite the 'access_forward'-value with no; whatever it was...",
|
||||
|
@ -168,7 +124,7 @@ There is no forward or backward, so this should always be the same for the same
|
|||
" end",
|
||||
" if(access_forward ~= nil and access_forward ~= \"no\" and access_forward ~= false) then",
|
||||
" tags.access = access_forward -- might be relevant, e.g. for 'access=dismount' for bicycles",
|
||||
" result.forward_speed = " + _skeleton.ToLuaWithTags(_profile.Speed).Indent(),
|
||||
" result.forward_speed = " + _skeleton.ToLua(_profile.Speed).Indent(),
|
||||
" tags.speed = result.forward_speed",
|
||||
" local priority = calculate_priority(parameters, tags, result, access_forward, oneway, result.forward_speed)",
|
||||
" if (priority <= 0) then",
|
||||
|
@ -180,7 +136,7 @@ There is no forward or backward, so this should always be the same for the same
|
|||
"",
|
||||
" -- backward calculation",
|
||||
" tags[\"_direction\"] = \"against\" -- indicate the backward direction to priority calculation",
|
||||
" local access_backward = " + _skeleton.ToLuaWithTags(_profile.Access).Indent(),
|
||||
" local access_backward = " + _skeleton.ToLua(_profile.Access),
|
||||
" if(oneway == \"with\") then",
|
||||
" -- no 'oneway=both' or 'oneway=against', so we can only go forward over this segment",
|
||||
" -- we overwrite the 'access_forward'-value with no; whatever it was...",
|
||||
|
@ -188,7 +144,7 @@ There is no forward or backward, so this should always be the same for the same
|
|||
" end",
|
||||
" if(access_backward ~= nil and access_backward ~= \"no\" and access_backward ~= false) then",
|
||||
" tags.access = access_backward",
|
||||
" result.backward_speed = " + _skeleton.ToLuaWithTags(_profile.Speed).Indent(),
|
||||
" result.backward_speed = " + _skeleton.ToLua(_profile.Speed).Indent(),
|
||||
" tags.speed = result.backward_speed",
|
||||
" local priority = calculate_priority(parameters, tags, result, access_backward, oneway, result.backward_speed)",
|
||||
" if (priority <= 0) then",
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Tests;
|
||||
|
||||
namespace AspectedRouting.IO.itinero2
|
||||
|
@ -28,7 +28,7 @@ namespace AspectedRouting.IO.itinero2
|
|||
private readonly string _behaviourName;
|
||||
private readonly IEnumerable<BehaviourTestSuite> _behaviourTestSuite;
|
||||
private readonly Context _context;
|
||||
private readonly bool _includeTests;
|
||||
private readonly DateTime _lastChangeTime;
|
||||
private readonly LuaParameterPrinter _parameterPrinter;
|
||||
private readonly ProfileMetaData _profile;
|
||||
|
||||
|
@ -38,7 +38,7 @@ namespace AspectedRouting.IO.itinero2
|
|||
public LuaPrinter2(ProfileMetaData profile, string behaviourName,
|
||||
Context context,
|
||||
List<AspectTestSuite> aspectTests, IEnumerable<BehaviourTestSuite> behaviourTestSuite,
|
||||
bool includeTests = true)
|
||||
DateTime lastChangeTime)
|
||||
{
|
||||
_skeleton = new LuaSkeleton.LuaSkeleton(context, true);
|
||||
_profile = profile;
|
||||
|
@ -46,14 +46,45 @@ namespace AspectedRouting.IO.itinero2
|
|||
_context = context;
|
||||
_aspectTests = aspectTests;
|
||||
_behaviourTestSuite = behaviourTestSuite;
|
||||
_includeTests = includeTests;
|
||||
_lastChangeTime = lastChangeTime;
|
||||
_parameterPrinter = new LuaParameterPrinter(_profile, _skeleton);
|
||||
}
|
||||
|
||||
private string TestRunner()
|
||||
{
|
||||
return new List<string>
|
||||
public string ToLua()
|
||||
{
|
||||
var profileDescr = _profile.Behaviours[_behaviourName]["description"].Evaluate(_context).ToString();
|
||||
var header =
|
||||
new List<string> {
|
||||
$"name = \"{_profile.Name}.{_behaviourName}\"",
|
||||
$"generationDate = \"{_lastChangeTime:s}\"",
|
||||
$"description = \"{profileDescr} ({_profile.Description})\""
|
||||
};
|
||||
|
||||
var testPrinter = new LuaTestPrinter(_skeleton,
|
||||
new List<string> {"unitTestProfile2"});
|
||||
var tests = testPrinter.GenerateFullTestSuite(
|
||||
_behaviourTestSuite.ToList(),
|
||||
new List<AspectTestSuite>(),
|
||||
true);
|
||||
var all = new List<string> {
|
||||
header.Lined(),
|
||||
"",
|
||||
GenerateMainFunction(),
|
||||
"",
|
||||
GenerateFactorFunction(),
|
||||
"",
|
||||
_parameterPrinter.GenerateDefaultParameters(),
|
||||
"",
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateFunctions()),
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateDependencies()), // Should be AFTER generating the main function!
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateConstants()),
|
||||
"",
|
||||
tests,
|
||||
"",
|
||||
|
||||
"if (itinero == nil) then",
|
||||
" itinero = {}",
|
||||
" itinero.log = print",
|
||||
|
@ -69,56 +100,7 @@ namespace AspectedRouting.IO.itinero2
|
|||
"test_all()",
|
||||
"if (not failed_tests and not failed_profile_tests and print ~= nil) then",
|
||||
$" print(\"Tests OK ({_profile.Name}.{_behaviourName})\")",
|
||||
"else",
|
||||
" error(\"Some tests failed\")",
|
||||
"end"
|
||||
}.Lined();
|
||||
}
|
||||
|
||||
public string ToLua()
|
||||
{
|
||||
var profileDescr = _profile.Behaviours[_behaviourName]["description"].Evaluate(_context).ToString();
|
||||
var header =
|
||||
new List<string>
|
||||
{
|
||||
$"name = \"{_profile.Name}.{_behaviourName}\"",
|
||||
$"description = \"{profileDescr} ({_profile.Description})\"",
|
||||
"",
|
||||
"-- The hierarchy of types that this vehicle is; mostly used to check access restrictions",
|
||||
"vehicle_types = " +
|
||||
_skeleton.ToLua(new Constant(_profile.VehicleTyps.Select(v => new Constant(v)).ToArray()))
|
||||
};
|
||||
|
||||
var tests = "";
|
||||
if (_includeTests) {
|
||||
var testPrinter = new LuaTestPrinter(_skeleton,
|
||||
new List<string> { "unitTestProfile2" });
|
||||
tests = testPrinter.GenerateFullTestSuite(
|
||||
_behaviourTestSuite.ToList(),
|
||||
new List<AspectTestSuite>(),
|
||||
true) + "\n\n" + TestRunner();
|
||||
}
|
||||
|
||||
var all = new List<string>
|
||||
{
|
||||
header.Lined(),
|
||||
"",
|
||||
GenerateMainFunction(),
|
||||
"",
|
||||
GenerateFactorFunction(),
|
||||
"",
|
||||
GenerateTurnCostFunction(),
|
||||
"",
|
||||
_parameterPrinter.GenerateDefaultParameters(),
|
||||
"",
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateFunctions()),
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateDependencies()), // Should be AFTER generating the main function!
|
||||
"",
|
||||
string.Join("\n\n", _skeleton.GenerateConstants()),
|
||||
"",
|
||||
tests
|
||||
};
|
||||
|
||||
return all.Lined();
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
# What about relations in Itinero 2.0?
|
||||
|
||||
Relations have moved to the preprocessor, where they do put a tag on the members of the relation. This is done with a TagsFilter
|
|
@ -24,12 +24,9 @@ namespace AspectedRouting.IO.jsonParser
|
|||
return null;
|
||||
}
|
||||
|
||||
Console.Write("Parsing " + fileName + "... ");
|
||||
Console.WriteLine("Parsing " + fileName);
|
||||
|
||||
var aspect = doc.RootElement.ParseAspect(fileName, c);
|
||||
|
||||
Console.WriteLine($"\rAspect {aspect.Name} has type {string.Join(",", aspect.ExpressionImplementation.Types)}");
|
||||
return aspect;
|
||||
return doc.RootElement.ParseAspect(fileName, c);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
@ -93,29 +90,16 @@ namespace AspectedRouting.IO.jsonParser
|
|||
filepath + " is not a valid profile; it does not contain the obligated parameter " + name);
|
||||
}
|
||||
|
||||
var defaultParameters = e.GetProperty("defaults").ParseParameters();
|
||||
|
||||
var contextWithParameters = new Context(context);
|
||||
foreach (var (paramName, paramExpression) in defaultParameters)
|
||||
{
|
||||
if (!context.Parameters.TryGetValue(paramName, out var previousParam))
|
||||
{
|
||||
contextWithParameters.AddParameter(paramName, paramExpression);
|
||||
}
|
||||
}
|
||||
|
||||
var vehicleTypes = GetTopProperty("vehicletypes").EnumerateArray().Select(
|
||||
el => el.GetString()).ToList();
|
||||
var metadata = GetTopProperty("metadata").EnumerateArray().Select(
|
||||
el => el.GetString()).ToList();
|
||||
|
||||
|
||||
var access = ParseProfileProperty(e, contextWithParameters, "access").Finalize();
|
||||
var oneway = ParseProfileProperty(e, contextWithParameters, "oneway").Finalize();
|
||||
var speed = ParseProfileProperty(e, contextWithParameters, "speed").Finalize();
|
||||
var scalingFactor = ParseProfileProperty(e, contextWithParameters, "scalingfactor", Funcs.Const.Apply(new Constant(1))).Finalize();
|
||||
var obstacle_access = ParseProfileProperty(e, contextWithParameters, "obstacleaccess", Funcs.Const.Apply(new Constant(new Var("any"), null))).Finalize();
|
||||
var obstacle_cost = ParseProfileProperty(e, contextWithParameters, "obstaclecost", Funcs.Const.Apply(new Constant(new Var("any0"), null))).Finalize();
|
||||
var access = ParseProfileProperty(e, context, "access").Finalize();
|
||||
var oneway = ParseProfileProperty(e, context, "oneway").Finalize();
|
||||
var speed = ParseProfileProperty(e, context, "speed").Finalize();
|
||||
|
||||
|
||||
IExpression TagsApplied(IExpression x)
|
||||
{
|
||||
|
@ -168,22 +152,22 @@ namespace AspectedRouting.IO.jsonParser
|
|||
author,
|
||||
filepath?.DirectoryName ?? "unknown",
|
||||
vehicleTypes,
|
||||
defaultParameters,
|
||||
e.GetProperty("defaults").ParseParameters(),
|
||||
profiles,
|
||||
access,
|
||||
oneway,
|
||||
speed,
|
||||
obstacle_access, obstacle_cost,
|
||||
weights,
|
||||
scalingFactor,
|
||||
metadata,
|
||||
lastChange
|
||||
);
|
||||
}
|
||||
|
||||
private static readonly IExpression _mconst = Funcs.EitherFunc.Apply(Funcs.Id, Funcs.Const);
|
||||
private static readonly IExpression _mconst =
|
||||
new Apply(new Apply(Funcs.EitherFunc, Funcs.Id), Funcs.Const);
|
||||
|
||||
private static readonly IExpression _mappingWrapper = Funcs.EitherFunc.Apply(Funcs.Id, Funcs.StringStringToTags);
|
||||
private static readonly IExpression _mappingWrapper =
|
||||
new Apply(new Apply(Funcs.EitherFunc, Funcs.Id), Funcs.StringStringToTags);
|
||||
|
||||
private static IExpression ParseMapping(IEnumerable<JsonProperty> allArgs, Context context)
|
||||
{
|
||||
|
@ -217,7 +201,7 @@ namespace AspectedRouting.IO.jsonParser
|
|||
{
|
||||
var simpleMapping = new Mapping(keys, exprs);
|
||||
|
||||
var wrapped = _mappingWrapper.Apply(simpleMapping);
|
||||
var wrapped = (IExpression) new Apply(_mappingWrapper, simpleMapping);
|
||||
if (keys.Count == 1)
|
||||
{
|
||||
// We can interpret this directly without going through a list
|
||||
|
@ -311,20 +295,13 @@ namespace AspectedRouting.IO.jsonParser
|
|||
if (s.StartsWith("#"))
|
||||
{
|
||||
// This is a parameter, the type of it is free
|
||||
if (context.Parameters.TryGetValue(s.Substring(1), out var param))
|
||||
{
|
||||
return new Parameter(s).Specialize(param.Types);
|
||||
|
||||
}
|
||||
|
||||
return new Parameter(s);
|
||||
}
|
||||
|
||||
return new Constant(s);
|
||||
}
|
||||
|
||||
if (e.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
if (e.ValueKind == JsonValueKind.Null) {
|
||||
return new Constant(new Var("a"), null);
|
||||
}
|
||||
|
||||
|
@ -536,6 +513,7 @@ namespace AspectedRouting.IO.jsonParser
|
|||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"Aspect {name} has type {string.Join(",", expr.Types)}");
|
||||
return new AspectMetadata(
|
||||
expr,
|
||||
name,
|
||||
|
|
|
@ -1,83 +1,60 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
|
||||
[assembly: InternalsVisibleTo("AspectedRouting.Test")]
|
||||
namespace AspectedRouting.IO.jsonParser
|
||||
{
|
||||
public static partial class JsonParser
|
||||
{
|
||||
internal static IExpression ParseProfileProperty(JsonElement e, Context c, string property, IExpression defaultExpression = null)
|
||||
{
|
||||
if (!e.TryGetProperty(property, out var prop))
|
||||
{
|
||||
if (defaultExpression == null)
|
||||
private static IExpression ParseProfileProperty(JsonElement e, Context c, string property)
|
||||
{
|
||||
if (!e.TryGetProperty(property, out var prop)) {
|
||||
throw new ArgumentException("Not a valid profile: the declaration expression for '" + property +
|
||||
"' is missing");
|
||||
}
|
||||
|
||||
Console.Error.WriteLine("WARNING: no expression defined for " + property + ", using the default instead");
|
||||
return defaultExpression;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
var expr = ParseExpression(prop, c);
|
||||
if (!expr.Types.Any())
|
||||
{
|
||||
if (!expr.Types.Any()) {
|
||||
throw new Exception($"Could not parse field {property}, no valid typing for expression found");
|
||||
}
|
||||
|
||||
expr = expr.Optimize(out _);
|
||||
expr = expr.Optimize();
|
||||
expr = Funcs.Either(Funcs.Id, Funcs.Const, expr);
|
||||
var specialized = expr.Specialize(new Curry(Typs.Tags, new Var("a")));
|
||||
|
||||
if (specialized == null)
|
||||
{
|
||||
if (specialized == null) {
|
||||
throw new ArgumentException("The expression for " + property +
|
||||
" hasn't the right type of 'Tags -> a'; it has types " +
|
||||
string.Join(",", expr.Types) + "\n" + expr.TypeBreakdown());
|
||||
}
|
||||
|
||||
var pruned = specialized.PruneTypes(type =>
|
||||
{
|
||||
if (!(type is Curry c))
|
||||
{
|
||||
var pruned = specialized.PruneTypes(type => {
|
||||
if (!(type is Curry c)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Equals(c.ArgType, Typs.Tags))
|
||||
{
|
||||
if (!Equals(c.ArgType, Typs.Tags)) {
|
||||
return false;
|
||||
}
|
||||
if (c.ResultType is Curry)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (c.ResultType is ListType)
|
||||
{
|
||||
if (c.ResultType is Curry) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (pruned.SpecializeToSmallestType().Types.Count() != 1)
|
||||
{
|
||||
if (pruned.SpecializeToSmallestType().Types.Count() != 1) {
|
||||
throw new ArgumentException("The expression for " + property +
|
||||
" hasn't the right type of 'Tags -> a'; it has multiple types " +
|
||||
string.Join(",", pruned.Types) + "\n" + pruned.TypeBreakdown());
|
||||
}
|
||||
|
||||
return pruned.Optimize(out _);
|
||||
return pruned.Optimize();
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
catch (Exception exc) {
|
||||
throw new Exception("While parsing the property " + property, exc);
|
||||
}
|
||||
}
|
||||
|
@ -85,25 +62,20 @@ namespace AspectedRouting.IO.jsonParser
|
|||
private static Dictionary<string, IExpression> ParseParameters(this JsonElement e)
|
||||
{
|
||||
var ps = new Dictionary<string, IExpression>();
|
||||
foreach (var obj in e.EnumerateObject())
|
||||
{
|
||||
foreach (var obj in e.EnumerateObject()) {
|
||||
var nm = obj.Name.TrimStart('#');
|
||||
if (nm == "")
|
||||
{
|
||||
if (nm == "") {
|
||||
// This is a comment - not a parameter!
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (obj.Value.ValueKind)
|
||||
{
|
||||
switch (obj.Value.ValueKind) {
|
||||
case JsonValueKind.String:
|
||||
var v = obj.Value.ToString();
|
||||
if (v.Equals("yes") || v.Equals("no"))
|
||||
{
|
||||
if (v.Equals("yes") || v.Equals("no")) {
|
||||
ps[nm] = new Constant(Typs.Bool, v);
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
ps[nm] = new Constant(v);
|
||||
}
|
||||
|
||||
|
@ -134,8 +106,7 @@ namespace AspectedRouting.IO.jsonParser
|
|||
|
||||
private static string Get(this JsonElement json, string key)
|
||||
{
|
||||
if (json.TryGetProperty(key, out var p))
|
||||
{
|
||||
if (json.TryGetProperty(key, out var p)) {
|
||||
return p.GetString();
|
||||
}
|
||||
|
||||
|
@ -144,8 +115,7 @@ namespace AspectedRouting.IO.jsonParser
|
|||
|
||||
private static string TryGet(this JsonElement json, string key)
|
||||
{
|
||||
if (json.TryGetProperty(key, out var p))
|
||||
{
|
||||
if (json.TryGetProperty(key, out var p)) {
|
||||
return p.GetString();
|
||||
}
|
||||
|
||||
|
|
|
@ -1,42 +0,0 @@
|
|||
--[[
|
||||
|
||||
|
||||
Returns '0' if the turn is allowed and '-1' if the turn is forbidden.
|
||||
Only used by itinero 2.0.
|
||||
|
||||
The itinero 2.0 profile outputs a `turn_cost_factor` which immediately calls this one (see LuaPrinter2.MainFunction).
|
||||
|
||||
Dependencies: str_split, containedIn
|
||||
]]
|
||||
function calculate_turn_cost_factor(attributes, vehicle_types)
|
||||
|
||||
if (attributes["type"] ~= "restriction") then
|
||||
-- not a turn restriction; no cost to turn,
|
||||
return 0
|
||||
end
|
||||
|
||||
for _, vehicle_type in pairs(vehicle_types) do
|
||||
if (attributes["restriction:"..vehicle_type] ~= nil) then
|
||||
-- There is a turn restriction specifically for one of our vehicle types!
|
||||
return -1
|
||||
end
|
||||
end
|
||||
|
||||
if (attributes["restriction"] == nil) then
|
||||
-- Not a turn restriction; no cost to turn
|
||||
return 0
|
||||
end
|
||||
if (attributes["except"] ~= nil) then
|
||||
local except_types = str_split(attributes["except"],";")
|
||||
for _, vehicle_type in pairs(vehicle_types) do
|
||||
if (containedIn(except_types, vehicle_type)) then
|
||||
-- This vehicle is exempt from this turn restriction
|
||||
return 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return -1
|
||||
end
|
||||
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
|
||||
--[[
|
||||
copies all attributes from the source-table into the target-table,
|
||||
but only if the key is listed in 'whitelist' (which is a set)
|
||||
]]
|
||||
function copy_tags(source, target, whitelist)
|
||||
for k, v in pairs(source) do
|
||||
if whitelist[k] then
|
||||
target[k] = v
|
||||
end
|
||||
end
|
||||
end
|
|
@ -1,5 +0,0 @@
|
|||
function create_set(list)
|
||||
local set = {}
|
||||
for _, l in ipairs(list) do set[l] = true end
|
||||
return set
|
||||
end
|
|
@ -14,6 +14,6 @@ function if_then_else_dotted(conditionf, thnf, elsef, arg)
|
|||
if (condition) then
|
||||
return applyIfNeeded(thnf, arg)
|
||||
else
|
||||
return applyIfNeeded(elsef, arg) -- if no third parameter is given, 'else' will be nil
|
||||
return applyIfNeeded(elsef, arg) -- if no third parameter is given, 'els' will be nil
|
||||
end
|
||||
end
|
|
@ -1,3 +0,0 @@
|
|||
function is_null(a)
|
||||
return a == nil;
|
||||
end
|
|
@ -79,7 +79,7 @@ function must_match(needed_keys, table, tags, result)
|
|||
|
||||
-- Now that we know for sure that every key matches, we add them all to the 'attributes_to_keep'
|
||||
if (result == nil) then
|
||||
-- euhm, well, seems like we don't care about the attributes_to_keep; early return!
|
||||
-- euhm, well, seems like we don't are about the attributes_to_keep; early return!
|
||||
return true
|
||||
end
|
||||
for _, key in ipairs(needed_keys) do
|
||||
|
|
|
@ -1,14 +0,0 @@
|
|||
--[[
|
||||
Splits a string on the specified character, e.g.
|
||||
str_split("abc;def;ghi", ";") will result in a table ["abc","def","ghi"]
|
||||
]]
|
||||
function str_split (inputstr, sep)
|
||||
if sep == nil then
|
||||
sep = "%s"
|
||||
end
|
||||
local t={}
|
||||
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
|
||||
table.insert(t, str)
|
||||
end
|
||||
return t
|
||||
end
|
|
@ -10,18 +10,14 @@ function table_to_list(tags, result, factor_table)
|
|||
local f = mapping[v]
|
||||
if (f ~= nil) then
|
||||
table.insert(list, f);
|
||||
if (result.attributes_to_keep ~= nil) then
|
||||
result.attributes_to_keep[key] = v
|
||||
end
|
||||
end
|
||||
else
|
||||
table.insert(list, mapping);
|
||||
if (result.attributes_to_keep ~= nil) then
|
||||
result.attributes_to_keep[key] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return list;
|
||||
end
|
|
@ -1,30 +0,0 @@
|
|||
#! /bin/bash
|
||||
|
||||
echo "" > temp.lua
|
||||
|
||||
for f in `ls`
|
||||
do
|
||||
if [[ $f != "temp.lua" && $f != "test.sh" && $f != "not.lua" ]]
|
||||
then
|
||||
cat $f >> temp.lua
|
||||
echo -e "\n\n" >> temp.lua
|
||||
fi
|
||||
done
|
||||
|
||||
cat << TESTCODE >> temp.lua
|
||||
|
||||
print("------------ TESTS --------------")
|
||||
|
||||
function expect(expected, actual)
|
||||
if (actual ~= expected) then
|
||||
print("Expected "..expected.." but got "..actual)
|
||||
else
|
||||
print("OK")
|
||||
end
|
||||
end
|
||||
|
||||
expect(-1, calculate_turn_cost_factor({["type"] = "restriction", restriction = "no_left_turn"}, {}))
|
||||
expect(0, calculate_turn_cost_factor({["type"] = "restriction", restriction = "no_left_turn", except="bicycle;cargo_bike"}, {"bicycle"}))
|
||||
TESTCODE
|
||||
|
||||
lua temp.lua
|
|
@ -5,7 +5,8 @@ function unit_test(f, fname, index, expected, parameters, tags)
|
|||
failed_tests = true
|
||||
return
|
||||
end
|
||||
local actual = f(tags)
|
||||
local result = {attributes_to_keep = {}}
|
||||
local actual = f(parameters, tags, result)
|
||||
if(expected == "null" and actual == nil) then
|
||||
-- OK!
|
||||
elseif(tonumber(actual) and tonumber(expected) and math.abs(tonumber(actual) - tonumber(expected)) < 0.1) then
|
||||
|
|
|
@ -1,245 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Tests;
|
||||
|
||||
namespace AspectedRouting.IO.md
|
||||
{
|
||||
internal class MarkDownSection
|
||||
{
|
||||
private readonly List<string> parts = new List<string>();
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return string.Join("\n\n", parts);
|
||||
}
|
||||
|
||||
public void AddTitle(string title, int level)
|
||||
{
|
||||
var str = "";
|
||||
for (var i = 0; i < level; i++)
|
||||
{
|
||||
str += "#";
|
||||
}
|
||||
|
||||
str += " " + title;
|
||||
parts.Add(str);
|
||||
}
|
||||
|
||||
public void Add(params string[] paragraph)
|
||||
{
|
||||
parts.Add(string.Join("\n", paragraph));
|
||||
}
|
||||
|
||||
public void AddList(List<string> items)
|
||||
{
|
||||
parts.Add(string.Join("\n", items.Select(i => " - " + i)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class ProfileToMD
|
||||
{
|
||||
private readonly string _behaviour;
|
||||
private readonly Context _c;
|
||||
private readonly ProfileMetaData _profile;
|
||||
private readonly MarkDownSection md = new MarkDownSection();
|
||||
|
||||
public ProfileToMD(ProfileMetaData profile, string behaviour, Context c)
|
||||
{
|
||||
_profile = profile;
|
||||
_behaviour = behaviour;
|
||||
_c = c.WithAspectName(behaviour);
|
||||
_c.DefinedFunctions["speed"] = new AspectMetadata(profile.Speed, "speed", "The speed this vehicle is going",
|
||||
"", "km/h", "", true);
|
||||
if (!profile.Behaviours.ContainsKey(behaviour))
|
||||
{
|
||||
throw new ArgumentException("Profile does not contain behaviour " + behaviour);
|
||||
}
|
||||
}
|
||||
|
||||
private decimal R(double d)
|
||||
{
|
||||
return Math.Round((decimal)d, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates an entry with `speed`, `priority` for the profile
|
||||
*/
|
||||
public string TableEntry(string msg, Dictionary<string, string> tags, ProfileResult? reference,
|
||||
bool nullOnSame = false)
|
||||
{
|
||||
var profile = _profile.Run(_c, _behaviour, tags);
|
||||
if (!reference.HasValue)
|
||||
{
|
||||
return "| " + msg + " | " + profile.Speed + " | " + profile.Priority + " | ";
|
||||
}
|
||||
|
||||
if (reference.Equals(profile) && nullOnSame)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return "| " + msg + " | " + R(profile.Speed) + " | " +
|
||||
R(profile.Speed / reference.Value.Speed) + " | " +
|
||||
R(profile.Priority) + " | " + R(profile.Priority / reference.Value.Priority) + " | " +
|
||||
profile.Access + " | " + profile.Oneway;
|
||||
}
|
||||
|
||||
public void addTagsTable(ProfileResult reference, Dictionary<string, HashSet<string>> usedTags)
|
||||
{
|
||||
var p = _profile;
|
||||
var b = _profile.Behaviours[_behaviour];
|
||||
|
||||
var tableEntries = new List<string>();
|
||||
foreach (var (key, vals) in usedTags)
|
||||
{
|
||||
var values = vals;
|
||||
if (values.Count == 0 && key == "maxspeed")
|
||||
{
|
||||
tableEntries.Add($" | {key}=* (example values below)");
|
||||
values = new HashSet<string> {
|
||||
"20", "30", "50", "70", "90", "120", "150"
|
||||
};
|
||||
}
|
||||
|
||||
if (values.Count == 0)
|
||||
{
|
||||
tableEntries.Add($" | {key}=*");
|
||||
}
|
||||
|
||||
if (values.Count > 0)
|
||||
{
|
||||
foreach (var value in values)
|
||||
{
|
||||
var tags = new Dictionary<string, string>
|
||||
{
|
||||
[key] = value
|
||||
};
|
||||
var entry = TableEntry($"{key}={value} ", tags, reference);
|
||||
if (entry == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
tableEntries.Add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
md.Add("| Tags | Speed (km/h) | speedfactor | Priority | priorityfactor | access | oneway | ",
|
||||
"| ---- | ------------ | ----------- | -------- | --------------- | ----- | ------ |",
|
||||
string.Join("\n", tableEntries));
|
||||
}
|
||||
|
||||
public Dictionary<string, IExpression> TagsWithPriorityInfluence()
|
||||
{
|
||||
|
||||
var p = _profile;
|
||||
var parameters = _profile.ParametersFor(_behaviour);
|
||||
var withInfluence = new Dictionary<string, IExpression>();
|
||||
|
||||
foreach (var kv in p.Priority)
|
||||
{
|
||||
if (parameters[kv.Key].Equals(0.0) || parameters[kv.Key].Equals(0))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
withInfluence[kv.Key] = kv.Value;
|
||||
}
|
||||
|
||||
return withInfluence;
|
||||
}
|
||||
|
||||
|
||||
public string MainFormula()
|
||||
{
|
||||
var p = _profile;
|
||||
var b = _profile.Behaviours[_behaviour];
|
||||
|
||||
var overridenParams = new HashSet<string>();
|
||||
var paramValues = new Dictionary<string, object>();
|
||||
foreach (var kv in p.DefaultParameters)
|
||||
{
|
||||
paramValues[kv.Key] = kv.Value.Evaluate(_c);
|
||||
}
|
||||
|
||||
foreach (var kv in b)
|
||||
{
|
||||
paramValues[kv.Key] = kv.Value.Evaluate(_c);
|
||||
overridenParams.Add(kv.Key);
|
||||
}
|
||||
|
||||
var mainFormulaParts = p.Priority.Select(delegate (KeyValuePair<string, IExpression> kv)
|
||||
{
|
||||
var key = kv.Key;
|
||||
var param = paramValues[key];
|
||||
if (param.Equals(0) || param.Equals(0.0))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
if (overridenParams.Contains(key))
|
||||
{
|
||||
param = "**" + param + "**";
|
||||
}
|
||||
|
||||
|
||||
var called = kv.Value.DirectlyCalled();
|
||||
return param + " * `" + string.Join("", called.calledFunctionNames) + "`";
|
||||
});
|
||||
|
||||
var mainFormula = string.Join(" + ", mainFormulaParts.Where(p => p != ""));
|
||||
return mainFormula;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var p = _profile;
|
||||
var b = _profile.Behaviours[_behaviour];
|
||||
md.AddTitle($"[{_profile.Name}](./{_profile.Name}.md).{_behaviour}", 1);
|
||||
|
||||
md.Add(p.Description);
|
||||
|
||||
if (b.ContainsKey("description"))
|
||||
{
|
||||
md.Add(b["description"].Evaluate(_c).ToString());
|
||||
}
|
||||
|
||||
|
||||
md.Add("This profile is calculated as following (non-default keys are bold):", MainFormula());
|
||||
|
||||
var residentialTags = new Dictionary<string, string>
|
||||
{
|
||||
["highway"] = "residential"
|
||||
};
|
||||
|
||||
md.Add("| Tags | Speed (km/h) | Priority",
|
||||
"| ---- | ----- | ---------- | ",
|
||||
TableEntry("Residential highway (reference)", residentialTags, null));
|
||||
var reference = _profile.Run(_c, _behaviour, residentialTags);
|
||||
md.AddTitle("Tags influencing priority", 2);
|
||||
md.Add(
|
||||
"Priority is what influences which road to take. The routeplanner will search a way where `1/priority` is minimal.");
|
||||
addTagsTable(reference, TagsWithPriorityInfluence().Values.PossibleTagsRecursive(_c));
|
||||
|
||||
md.AddTitle("Tags influencing speed", 2);
|
||||
md.Add(
|
||||
"Speed is used to calculate how long the trip will take, but does _not_ influence which route is taken. Some profiles do use speed as a factor in priority too - in this case, these tags will be mentioned above too.");
|
||||
addTagsTable(reference, _profile.Speed.PossibleTagsRecursive(_c));
|
||||
|
||||
md.AddTitle("Tags influencing access", 2);
|
||||
md.Add("These tags influence whether or not this road can be taken with this vehicle or behaviour");
|
||||
addTagsTable(reference, _profile.Access.PossibleTagsRecursive(_c));
|
||||
md.AddTitle("Tags influencing oneway", 2);
|
||||
md.Add("These tags influence whether or not this road can be taken in all directions or not");
|
||||
addTagsTable(reference, _profile.Oneway.PossibleTagsRecursive(_c));
|
||||
|
||||
|
||||
return md.ToString();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -2,8 +2,7 @@
|
|||
|
||||
## Introduction
|
||||
|
||||
Generating a good route for travellers is hard; especially for cyclists. They can be very picky and the driving style
|
||||
and purposes are diverse. Think about:
|
||||
Generating a good route for travellers is hard; especially for cyclists. They can be very picky and the driving style and purposes are diverse. Think about:
|
||||
|
||||
- A lightweight food delivery driver, who wants to be at their destination as soon as possible
|
||||
- A cargo bike, possibly with a cart or electrically supported, doing heavy delivery
|
||||
|
@ -11,18 +10,13 @@ and purposes are diverse. Think about:
|
|||
- Grandma cycling along a canal on sunday afternoon
|
||||
- Someone bringing their kids to school
|
||||
|
||||
It is clear that these persona's on top have very different wishes for their route. A road with a high car pressure
|
||||
won't pose a problem for the food delivery, whereas grandma wouldn't even think about going there. And this is without
|
||||
mentioning the speed these cyclists drive, where they are allowed to drive, ...
|
||||
It is clear that these persona's on top have very different wishes for their route. A road with a high car pressure won't pose a problem for the food delivery, whereas grandma wouldn't even think about going there. And this is without mentioning the speed these cyclists drive, where they are allowed to drive, ...
|
||||
|
||||
Generating a cycle route for these persons is thus clearly far from simply picking the shortest possible path. On top of
|
||||
that, a consumer expects the route calculations to be both customizable and to be blazingly fast.
|
||||
Generating a cycle route for these persons is thus clearly far from simply picking the shortest possible path. On top of that, a consumer expects the route calculations to be both customizable and to be blazingly fast.
|
||||
|
||||
In order to simplify the generation of these routing profiles, this repository introduces _aspected routing_.
|
||||
|
||||
In _aspected routing_, one does not try to tackle the routing problem all at once, but one tries to dissassemble the
|
||||
preferences of the travellers into multiple, orthogonal aspects. These aspects can then be combined in a linear way,
|
||||
giving a fast and flexible system.
|
||||
In _aspected routing_, one does not try to tackle the routing problem all at once, but one tries to dissassemble the preferences of the travellers into multiple, orthogonal aspects. These aspects can then be combined in a linear way, giving a fast and flexible system.
|
||||
|
||||
Some aspects can be:
|
||||
|
||||
|
@ -44,12 +38,9 @@ Even though this repository is heavily inspired on OpenStreetMap, it can be gene
|
|||
|
||||
## Road network assumptions
|
||||
|
||||
The only assumptions made are that roads have a **length** and a collection of **tags**, this is a dictionary mapping
|
||||
strings onto strings. These tags encode the properties of the road (e.g. road classification, name, surface, ...)
|
||||
The only assumptions made are that roads have a **length** and a collection of **tags**, this is a dictionary mapping strings onto strings. These tags encode the properties of the road (e.g. road classification, name, surface, ...)
|
||||
|
||||
OpenStreetMap also has a concept of **relations**. A special function is available for that. However, in a preprocessing
|
||||
step, the relations that a road is a member of, are converted into tags on every way with a `_network:i:key=value`
|
||||
format, where `i` is the number of the relation, and `key`=`value` is a tag present on the relation.
|
||||
OpenStreetMap also has a concept of **relations**. A special function is available for that. However, in a preprocessing step, the relations that a road is a member of, are converted into tags on every way with a `_network:i:key=value` format, where `i` is the number of the relation, and `key`=`value` is a tag present on the relation.
|
||||
|
||||
## Describing an aspect
|
||||
|
||||
|
|
|
@ -7,7 +7,6 @@
|
|||
- string
|
||||
- tags
|
||||
- bool
|
||||
|
||||
## Builtin functions
|
||||
|
||||
- eq
|
||||
|
@ -38,6 +37,7 @@
|
|||
- eitherFunc
|
||||
- stringToTags
|
||||
|
||||
|
||||
### Function overview
|
||||
|
||||
#### eq
|
||||
|
@ -49,6 +49,8 @@ $a | $a | string |
|
|||
|
||||
Returns 'yes' if both values _are_ the same
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -62,6 +64,7 @@ end
|
|||
|
||||
````
|
||||
|
||||
|
||||
#### notEq
|
||||
|
||||
a | b | returns |
|
||||
|
@ -72,6 +75,8 @@ bool | bool |
|
|||
|
||||
OVerloaded function, either boolean not or returns 'yes' if the two passed in values are _not_ the same;
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -88,6 +93,7 @@ function notEq(a, b)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### not
|
||||
|
||||
a | b | returns |
|
||||
|
@ -98,6 +104,8 @@ bool | bool |
|
|||
|
||||
OVerloaded function, either boolean not or returns 'yes' if the two passed in values are _not_ the same;
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -114,6 +122,7 @@ function notEq(a, b)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### inv
|
||||
|
||||
d | returns |
|
||||
|
@ -123,6 +132,8 @@ double | double |
|
|||
|
||||
Calculates `1/d`
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -131,6 +142,7 @@ function inv(n)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### default
|
||||
|
||||
defaultValue | f | returns |
|
||||
|
@ -139,6 +151,8 @@ $a | $b -> $a | $b | $a |
|
|||
|
||||
Calculates function `f` for the given argument. If the result is `null`, the default value is returned instead
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -150,6 +164,7 @@ function default(defaultValue, realValue)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### parse
|
||||
|
||||
s | returns |
|
||||
|
@ -159,6 +174,8 @@ string | pdouble |
|
|||
|
||||
Parses a string into a numerical value
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -191,6 +208,7 @@ function parse(string)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### to_string
|
||||
|
||||
obj | returns |
|
||||
|
@ -199,6 +217,8 @@ $a | string |
|
|||
|
||||
Converts a value into a human readable string
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -207,6 +227,7 @@ function to_string(o)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### concat
|
||||
|
||||
a | b | returns |
|
||||
|
@ -215,6 +236,8 @@ string | string | string |
|
|||
|
||||
Concatenates two strings
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -223,6 +246,7 @@ function concat(a, b)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### containedIn
|
||||
|
||||
list | a | returns |
|
||||
|
@ -231,6 +255,8 @@ list ($a) | $a | bool |
|
|||
|
||||
Given a list of values, checks if the argument is contained in the list.
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -245,6 +271,7 @@ function containedIn(list, a)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### min
|
||||
|
||||
list | returns |
|
||||
|
@ -257,6 +284,8 @@ list (bool) | bool |
|
|||
|
||||
Out of a list of values, gets the smallest value. IN case of a list of bools, this acts as `and`
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -274,6 +303,7 @@ function min(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### and
|
||||
|
||||
list | returns |
|
||||
|
@ -286,6 +316,8 @@ list (bool) | bool |
|
|||
|
||||
Out of a list of values, gets the smallest value. IN case of a list of bools, this acts as `and`
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -303,6 +335,7 @@ function min(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### max
|
||||
|
||||
list | returns |
|
||||
|
@ -315,6 +348,8 @@ list (bool) | bool |
|
|||
|
||||
Returns the biggest value in the list. For a list of booleans, this acts as 'or'
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -332,6 +367,7 @@ function max(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### or
|
||||
|
||||
list | returns |
|
||||
|
@ -344,6 +380,8 @@ list (bool) | bool |
|
|||
|
||||
Returns the biggest value in the list. For a list of booleans, this acts as 'or'
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -361,6 +399,7 @@ function max(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### sum
|
||||
|
||||
list | returns |
|
||||
|
@ -373,6 +412,8 @@ list (bool) | int |
|
|||
|
||||
Sums all the numbers in the given list. If the list contains bool, `yes` or `true` will be considered to equal `1`
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -388,6 +429,7 @@ function sum(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### multiply
|
||||
|
||||
list | returns |
|
||||
|
@ -400,6 +442,8 @@ list (bool) | bool |
|
|||
|
||||
Multiplies all the values in a given list. On a list of booleans, this acts as 'and' or 'all'
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -412,6 +456,7 @@ function multiply(list)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### firstMatchOf
|
||||
|
||||
s | returns |
|
||||
|
@ -420,6 +465,8 @@ list (string) | tags -> list ($a) | tags | $a |
|
|||
|
||||
Parses a string into a numerical value
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -445,15 +492,18 @@ function first_match_of(tags, result, order_of_keys, table)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### mustMatch
|
||||
|
||||
neededKeys (filled in by parser) | f | returns |
|
||||
--- | --- | --- |
|
||||
list (string) | tags -> list (bool) | tags | bool |
|
||||
|
||||
Every key that is used in the subfunction must be present. If, on top, a value is present with a mapping, every
|
||||
key/value will be executed and must return a value that is not 'no' or 'false' Note that this is a privileged builtin
|
||||
function, as the parser will automatically inject the keys used in the called function.
|
||||
Every key that is used in the subfunction must be present.
|
||||
If, on top, a value is present with a mapping, every key/value will be executed and must return a value that is not 'no' or 'false'
|
||||
Note that this is a privileged builtin function, as the parser will automatically inject the keys used in the called function.
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
|
@ -522,6 +572,7 @@ function must_match(tags, result, needed_keys, table)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### memberOf
|
||||
|
||||
f | tags | returns |
|
||||
|
@ -535,18 +586,15 @@ In order to use this for itinero 1.0, the membership _must_ be the top level exp
|
|||
Conceptually, when the aspect is executed for a way, every relation will be used as argument in the subfunction `f`
|
||||
If this subfunction returns 'true', the entire aspect will return true.
|
||||
|
||||
In the lua implementation for itinero 1.0, this is implemented slightly different: a
|
||||
flag `_relation:<aspect_name>="yes"` will be set if the aspect matches on every way for where this aspect matches.
|
||||
However, this plays poorly with parameters (e.g.: what if we want to cycle over a highway which is part of a certain
|
||||
cycling network with a certain `#network_name`?) Luckily, parameters can only be simple values. To work around this
|
||||
problem, an extra tag is introduced for _every single
|
||||
profile_:`_relation:<profile_name>:<aspect_name>=yes'. The subfunction is thus executed `countOr(relations) * countOf(
|
||||
profiles)` time, yielding `countOf(
|
||||
profiles)` tags. The profile function then picks the tags for himself and strips the `<profile_name>:` away from the
|
||||
key.
|
||||
In the lua implementation for itinero 1.0, this is implemented slightly different: a flag `_relation:<aspect_name>="yes"` will be set if the aspect matches on every way for where this aspect matches.
|
||||
However, this plays poorly with parameters (e.g.: what if we want to cycle over a highway which is part of a certain cycling network with a certain `#network_name`?) Luckily, parameters can only be simple values. To work around this problem, an extra tag is introduced for _every single profile_:`_relation:<profile_name>:<aspect_name>=yes'. The subfunction is thus executed `countOr(relations) * countOf(profiles)` time, yielding `countOf(profiles)` tags. The profile function then picks the tags for himself and strips the `<profile_name>:` away from the key.
|
||||
|
||||
|
||||
|
||||
In the test.csv, one can simply use `_relation:<aspect_name>=yes` to mimic relations in your tests
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -562,6 +610,7 @@ function member_of(calledIn, parameters, tags, result)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### if_then_else
|
||||
|
||||
condition | then | else | returns |
|
||||
|
@ -569,8 +618,9 @@ condition | then | else | returns |
|
|||
bool | $a | $a | $a |
|
||||
bool | $a | $a |
|
||||
|
||||
Selects either one of the branches, depending on the condition.If the `else` branch is not set, `null` is returned in
|
||||
the condition is false.
|
||||
Selects either one of the branches, depending on the condition.If the `else` branch is not set, `null` is returned in the condition is false.
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
|
@ -584,6 +634,7 @@ function if_then_else(condition, thn, els)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### if
|
||||
|
||||
condition | then | else | returns |
|
||||
|
@ -591,8 +642,9 @@ condition | then | else | returns |
|
|||
bool | $a | $a | $a |
|
||||
bool | $a | $a |
|
||||
|
||||
Selects either one of the branches, depending on the condition.If the `else` branch is not set, `null` is returned in
|
||||
the condition is false.
|
||||
Selects either one of the branches, depending on the condition.If the `else` branch is not set, `null` is returned in the condition is false.
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
|
@ -606,6 +658,7 @@ function if_then_else(condition, thn, els)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### id
|
||||
|
||||
a | returns |
|
||||
|
@ -614,6 +667,8 @@ $a | $a |
|
|||
|
||||
Returns the argument unchanged - the identity function. Seems useless at first sight, but useful in parsing
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -622,6 +677,7 @@ function id(v)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### const
|
||||
|
||||
a | b | returns |
|
||||
|
@ -630,6 +686,8 @@ $a | $b | $a |
|
|||
|
||||
Small utility function, which takes two arguments `a` and `b` and returns `a`. Used extensively to insert freedom
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
@ -638,6 +696,7 @@ function const(a, b)
|
|||
end
|
||||
````
|
||||
|
||||
|
||||
#### constRight
|
||||
|
||||
a | b | returns |
|
||||
|
@ -646,20 +705,24 @@ $a | $b | $b |
|
|||
|
||||
Small utility function, which takes two arguments `a` and `b` and returns `b`. Used extensively to insert freedom
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
||||
````
|
||||
|
||||
|
||||
#### dot
|
||||
|
||||
f | g | a | returns |
|
||||
--- | --- | --- | --- |
|
||||
$b -> $c | $a -> $b | $a | $c |
|
||||
|
||||
Higher order function: converts `f (g a)` into `(dot f g) a`. In other words, this fuses `f` and `g` in a new function,
|
||||
which allows the argument to be lifted out of the expression
|
||||
Higher order function: converts `f (g a)` into `(dot f g) a`. In other words, this fuses `f` and `g` in a new function, which allows the argument to be lifted out of the expression
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
|
@ -667,14 +730,16 @@ Lua implementation:
|
|||
|
||||
````
|
||||
|
||||
|
||||
#### listDot
|
||||
|
||||
list | a | returns |
|
||||
--- | --- | --- |
|
||||
list ($a -> $b) | $a | list ($b) |
|
||||
|
||||
Listdot takes a list of functions `[f, g, h]` and and an argument `a`. It applies the argument on every single
|
||||
function.It conveniently lifts the argument out of the list.
|
||||
Listdot takes a list of functions `[f, g, h]` and and an argument `a`. It applies the argument on every single function.It conveniently lifts the argument out of the list.
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
|
@ -683,6 +748,7 @@ Lua implementation:
|
|||
-- listDot
|
||||
````
|
||||
|
||||
|
||||
#### eitherFunc
|
||||
|
||||
f | g | a | returns |
|
||||
|
@ -690,24 +756,21 @@ f | g | a | returns |
|
|||
$a -> $b | $c -> $d | $a | $b |
|
||||
$a -> $b | $c -> $d | $c | $d |
|
||||
|
||||
EitherFunc is a small utility function, mostly used in the parser. It allows the compiler to choose a function, based on
|
||||
the types.
|
||||
EitherFunc is a small utility function, mostly used in the parser. It allows the compiler to choose a function, based on the types.
|
||||
|
||||
Consider the mapping `{'someKey':'someValue'}`. Under normal circumstances, this acts as a pointwise-function,
|
||||
converting the string `someKey` into `someValue`, just like an ordinary dictionary would do. However, in the context
|
||||
of `mustMatch`, we would prefer this to act as a _check_, that the highway _has_ a key `someKey` which is `someValue`,
|
||||
thus acting
|
||||
as `{'someKey': {'$eq':'someValue'}}`. Both behaviours are automatically supported in parsing, by parsing the string as `(
|
||||
eitherFunc id eq) 'someValue'`. The type system is then able to figure out which implementation is needed.
|
||||
Consider the mapping `{'someKey':'someValue'}`. Under normal circumstances, this acts as a pointwise-function, converting the string `someKey` into `someValue`, just like an ordinary dictionary would do. However, in the context of `mustMatch`, we would prefer this to act as a _check_, that the highway _has_ a key `someKey` which is `someValue`, thus acting as `{'someKey': {'$eq':'someValue'}}. Both behaviours are automatically supported in parsing, by parsing the string as `(eitherFunc id eq) 'someValue'`. The type system is then able to figure out which implementation is needed.
|
||||
|
||||
Disclaimer: _you should never ever need this in your profiles_
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
||||
````
|
||||
|
||||
|
||||
#### stringToTags
|
||||
|
||||
f | tags | returns |
|
||||
|
@ -716,6 +779,8 @@ string -> string -> $a | tags | list ($a) |
|
|||
|
||||
stringToTags converts a function `string -> string -> a` into a function `tags -> [a]`
|
||||
|
||||
|
||||
|
||||
Lua implementation:
|
||||
|
||||
````lua
|
||||
|
|
|
@ -10,6 +10,7 @@ namespace AspectedRouting.Language
|
|||
{
|
||||
public static class Analysis
|
||||
{
|
||||
|
||||
public static Dictionary<string, (List<Type> Types, string inFunction)> UsedParameters(
|
||||
this ProfileMetaData profile, Context context)
|
||||
{
|
||||
|
@ -31,7 +32,7 @@ namespace AspectedRouting.Language
|
|||
param.ParamName + " is used\n" +
|
||||
$" in {oldUsage} as {string.Join(",", types)}\n" +
|
||||
$" in {inFunction} as {string.Join(",", param.Types)}\n" +
|
||||
"which can not be unified");
|
||||
$"which can not be unified");
|
||||
}
|
||||
}
|
||||
else
|
||||
|
@ -45,8 +46,6 @@ namespace AspectedRouting.Language
|
|||
AddParams(profile.Access, "profile definition for " + profile.Name + ".access");
|
||||
AddParams(profile.Oneway, "profile definition for " + profile.Name + ".oneway");
|
||||
AddParams(profile.Speed, "profile definition for " + profile.Name + ".speed");
|
||||
AddParams(profile.ObstacleAccess, "profile definition for " + profile.Name + ".obstacleaccess");
|
||||
AddParams(profile.ObstacleCost, "profile definition for " + profile.Name + ".obstaclecost");
|
||||
|
||||
foreach (var (key, expr) in profile.Priority)
|
||||
{
|
||||
|
@ -167,8 +166,7 @@ namespace AspectedRouting.Language
|
|||
|
||||
|
||||
/// <summary>
|
||||
/// Generates an overview of the dependencies of the expression, both which parameters it needs and what other
|
||||
/// functions (builtin or defined) it needs.
|
||||
/// Generates an overview of the dependencies of the expression, both which parameters it needs and what other functions (builtin or defined) it needs.
|
||||
/// </summary>
|
||||
/// <param name="expr"></param>
|
||||
/// <returns></returns>
|
||||
|
@ -199,7 +197,8 @@ namespace AspectedRouting.Language
|
|||
|
||||
public static string TypeBreakdown(this IExpression e)
|
||||
{
|
||||
return e + " : " + string.Join(" ; ", e.Types);
|
||||
|
||||
return e.ToString() + " : "+string.Join(" ; ", e.Types);
|
||||
}
|
||||
|
||||
public static void SanityCheckProfile(this ProfileMetaData pmd, Context context)
|
||||
|
@ -286,7 +285,6 @@ namespace AspectedRouting.Language
|
|||
Console.WriteLine(
|
||||
$"[{pmd.Name}] WARNING: Some parameters only have a default value: {string.Join(", ", defaultOnly)}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void SanityCheck(this IExpression e)
|
||||
|
@ -340,12 +338,6 @@ namespace AspectedRouting.Language
|
|||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns all possible tags which are used in the given expression.
|
||||
*
|
||||
* If a tag might match a wildcard, an explicit '*' will be added to the collection.
|
||||
* This is different from the _other_ possibleTags, which will return an empty set.
|
||||
*/
|
||||
public static Dictionary<string, HashSet<string>> PossibleTags(this IEnumerable<IExpression> exprs)
|
||||
{
|
||||
var usedTags = new Dictionary<string, HashSet<string>>();
|
||||
|
@ -361,7 +353,6 @@ namespace AspectedRouting.Language
|
|||
{
|
||||
if (!usedTags.TryGetValue(key, out var collection))
|
||||
{
|
||||
// This is the first time we see this collection
|
||||
collection = new HashSet<string>();
|
||||
usedTags[key] = collection;
|
||||
}
|
||||
|
@ -370,85 +361,15 @@ namespace AspectedRouting.Language
|
|||
{
|
||||
collection.Add(v);
|
||||
}
|
||||
|
||||
if (values.Count == 0)
|
||||
{
|
||||
collection.Add("*");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return usedTags;
|
||||
}
|
||||
|
||||
public static Dictionary<string, HashSet<string>> PossibleTagsRecursive(this IEnumerable<IExpression> exprs, Context c)
|
||||
{
|
||||
var usedTags = new Dictionary<string, HashSet<string>>();
|
||||
foreach (var e in exprs)
|
||||
{
|
||||
var possibleTags = e.PossibleTagsRecursive(c);
|
||||
|
||||
if (possibleTags != null)
|
||||
{
|
||||
foreach (var tag in possibleTags)
|
||||
{
|
||||
usedTags[tag.Key] = tag.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return usedTags;
|
||||
}
|
||||
|
||||
public static Dictionary<string, HashSet<string>> PossibleTagsRecursive(this IExpression e, Context c)
|
||||
{
|
||||
var allExpr = new List<IExpression>();
|
||||
var queue = new Queue<IExpression>();
|
||||
queue.Enqueue(e);
|
||||
do
|
||||
{
|
||||
var next = queue.Dequeue();
|
||||
allExpr.Add(next);
|
||||
next.Visit(expression =>
|
||||
{
|
||||
if (expression is FunctionCall fc)
|
||||
{
|
||||
var called = c.GetFunction(fc.CalledFunctionName);
|
||||
queue.Enqueue(called);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
} while (queue.Any());
|
||||
|
||||
var result = new Dictionary<string, HashSet<string>>();
|
||||
|
||||
foreach (var expression in allExpr)
|
||||
{
|
||||
var subTags = expression.PossibleTags();
|
||||
if (subTags == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var kv in subTags)
|
||||
{
|
||||
if (!result.ContainsKey(kv.Key))
|
||||
{
|
||||
result[kv.Key] = new HashSet<string>();
|
||||
}
|
||||
|
||||
foreach (var val in kv.Value)
|
||||
{
|
||||
result[kv.Key].Add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns which tags are used in this calculation
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="e"></param>
|
||||
/// <returns>A dictionary containing all possible values. An entry with an empty list indicates a wildcard</returns>
|
||||
|
|
|
@ -34,11 +34,6 @@ namespace AspectedRouting.Language
|
|||
Parameters.Add(name, new Constant(value));
|
||||
}
|
||||
|
||||
public void AddParameter(string name, IExpression value)
|
||||
{
|
||||
Parameters.Add(name, value);
|
||||
}
|
||||
|
||||
public void AddFunction(string name, AspectMetadata function)
|
||||
{
|
||||
if (Funcs.Builtins.ContainsKey(name))
|
||||
|
|
|
@ -17,8 +17,7 @@ namespace AspectedRouting.Language
|
|||
/// <returns></returns>
|
||||
public static (IExpression f, List<IExpression> args)? DeconstructApply(this IExpression e)
|
||||
{
|
||||
if (!(e is Apply _))
|
||||
{
|
||||
if (!(e is Apply _)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -26,8 +25,7 @@ namespace AspectedRouting.Language
|
|||
|
||||
var fs = new List<IExpression>();
|
||||
|
||||
while (UnApply(Assign(fs), Assign(argss)).Invoke(e))
|
||||
{
|
||||
while (UnApply(Assign(fs), Assign(argss)).Invoke(e)) {
|
||||
e = fs.First();
|
||||
fs.Clear();
|
||||
}
|
||||
|
@ -39,10 +37,8 @@ namespace AspectedRouting.Language
|
|||
|
||||
public static Func<IExpression, bool> IsMapping(List<Mapping> collect)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
if (e is Mapping m)
|
||||
{
|
||||
return e => {
|
||||
if (e is Mapping m) {
|
||||
collect.Add(m);
|
||||
return true;
|
||||
}
|
||||
|
@ -51,24 +47,10 @@ namespace AspectedRouting.Language
|
|||
};
|
||||
}
|
||||
|
||||
public static Func<IExpression, bool> IsConstant(List<Constant> collect)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
if (!(e is Constant c))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
collect.Add(c);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
public static Func<IExpression, bool> Assign(List<IExpression> collect)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
return e => {
|
||||
collect.Add(e);
|
||||
return true;
|
||||
};
|
||||
|
@ -76,10 +58,8 @@ namespace AspectedRouting.Language
|
|||
|
||||
public static Func<IExpression, bool> IsFunc(Function f)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
if (!(e is Function fe))
|
||||
{
|
||||
return e => {
|
||||
if (!(e is Function fe)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -87,21 +67,6 @@ namespace AspectedRouting.Language
|
|||
};
|
||||
}
|
||||
|
||||
|
||||
public static Func<IExpression, bool> IsFunctionCall(List<string> names)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
if (!(e is FunctionCall fc))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
names.Add(fc.CalledFunctionName);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
public static Func<IExpression, bool> UnApplyAny(
|
||||
Func<IExpression, bool> matchFunc,
|
||||
Func<IExpression, bool> matchArg)
|
||||
|
@ -114,28 +79,21 @@ namespace AspectedRouting.Language
|
|||
Func<IExpression, bool> matchArg,
|
||||
bool matchAny = false)
|
||||
{
|
||||
return e =>
|
||||
{
|
||||
if (!(e is Apply apply))
|
||||
{
|
||||
return e => {
|
||||
if (!(e is Apply apply)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (_, (f, a)) in apply.FunctionApplications)
|
||||
{
|
||||
foreach (var (_, (f, a)) in apply.FunctionApplications) {
|
||||
var doesMatch = matchFunc.Invoke(f) && matchArg.Invoke(a);
|
||||
if (matchAny)
|
||||
{
|
||||
if (doesMatch)
|
||||
{
|
||||
if (matchAny) {
|
||||
if (doesMatch) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!doesMatch)
|
||||
{
|
||||
// All must match - otherwise we might have registered a wrong collection
|
||||
else {
|
||||
if (!doesMatch) {
|
||||
// All must match - otherwise we might have registered a wrong collectiin
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,8 +19,6 @@ namespace AspectedRouting.Language.Expression
|
|||
/// </summary>
|
||||
public readonly Dictionary<Type, (IExpression f, IExpression a)> FunctionApplications;
|
||||
|
||||
private IExpression optimizedForm = null;
|
||||
|
||||
private Apply(string debugInfo, Dictionary<Type, (IExpression f, IExpression a)> argument)
|
||||
{
|
||||
_debugInfo = debugInfo;
|
||||
|
@ -29,18 +27,15 @@ namespace AspectedRouting.Language.Expression
|
|||
|
||||
public Apply(IExpression f, IExpression argument)
|
||||
{
|
||||
if (f == null || argument == null)
|
||||
{
|
||||
if (f == null || argument == null) {
|
||||
throw new NullReferenceException();
|
||||
}
|
||||
|
||||
FunctionApplications = new Dictionary<Type, (IExpression f, IExpression a)>();
|
||||
|
||||
var typesCleaned = argument.Types.RenameVars(f.Types).ToList();
|
||||
foreach (var funcType in f.Types)
|
||||
{
|
||||
if (!(funcType is Curry c))
|
||||
{
|
||||
foreach (var funcType in f.Types) {
|
||||
if (!(funcType is Curry c)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -48,12 +43,10 @@ namespace AspectedRouting.Language.Expression
|
|||
var expectedResultType = c.ResultType;
|
||||
|
||||
|
||||
foreach (var argType in typesCleaned)
|
||||
{
|
||||
foreach (var argType in typesCleaned) {
|
||||
// we try to unify the argType with the expected type
|
||||
var substitutions = expectedArgType.UnificationTable(argType);
|
||||
if (substitutions == null)
|
||||
{
|
||||
if (substitutions == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -63,30 +56,25 @@ namespace AspectedRouting.Language.Expression
|
|||
var actualFunction = f.Specialize(new Curry(actualArgType, actualResultType));
|
||||
var actualArgument = argument.Specialize(actualArgType);
|
||||
|
||||
if (actualFunction == null || actualArgument == null)
|
||||
{
|
||||
if (actualFunction == null || actualArgument == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
if (FunctionApplications.ContainsKey(actualResultType))
|
||||
{
|
||||
if (FunctionApplications.ContainsKey(actualResultType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
FunctionApplications.Add(actualResultType, (actualFunction, actualArgument));
|
||||
}
|
||||
}
|
||||
|
||||
if (!FunctionApplications.Any())
|
||||
{
|
||||
try
|
||||
{
|
||||
_debugInfo = $"\n{f.Optimize(out var _).TypeBreakdown().Indent()}\n" +
|
||||
if (!FunctionApplications.Any()) {
|
||||
try {
|
||||
_debugInfo = $"\n{f.Optimize().TypeBreakdown().Indent()}\n" +
|
||||
"is given the argument: " +
|
||||
"(" + argument.Optimize(out var _).TypeBreakdown() + ")";
|
||||
"(" + argument.Optimize().TypeBreakdown() + ")";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
catch (Exception) {
|
||||
_debugInfo = $"\n (NO OPT) {f.TypeBreakdown().Indent()}\n" +
|
||||
"is given the argument: " +
|
||||
"(" + argument.TypeBreakdown() + ")";
|
||||
|
@ -102,8 +90,7 @@ namespace AspectedRouting.Language.Expression
|
|||
|
||||
public object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
if (!Types.Any())
|
||||
{
|
||||
if (!Types.Any()) {
|
||||
throw new ArgumentException("Trying to invoke an invalid expression: " + this);
|
||||
}
|
||||
|
||||
|
@ -114,8 +101,7 @@ namespace AspectedRouting.Language.Expression
|
|||
var arg = argExpr;
|
||||
var allArgs = new IExpression[arguments.Length + 1];
|
||||
allArgs[0] = arg;
|
||||
for (var i = 0; i < arguments.Length; i++)
|
||||
{
|
||||
for (var i = 0; i < arguments.Length; i++) {
|
||||
allArgs[i + 1] = arguments[i];
|
||||
}
|
||||
|
||||
|
@ -128,40 +114,21 @@ namespace AspectedRouting.Language.Expression
|
|||
return Specialize(allowedTypes);
|
||||
}
|
||||
|
||||
public IExpression PruneTypes(System.Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passed = FunctionApplications.Where(kv => allowedTypes.Invoke(kv.Key));
|
||||
if (!passed.Any())
|
||||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passed = this.FunctionApplications.Where(kv => allowedTypes.Invoke(kv.Key));
|
||||
if (!passed.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Apply("pruned", new Dictionary<Type, (IExpression A, IExpression F)>(passed));
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
{
|
||||
if (this.optimizedForm != null)
|
||||
{
|
||||
somethingChanged = this.optimizedForm != this;
|
||||
return this.optimizedForm;
|
||||
}
|
||||
this.optimizedForm = this.OptimizeInternal(out somethingChanged);
|
||||
if (!optimizedForm.Types.Any())
|
||||
{
|
||||
throw new Exception("Optimizing " + this.ToString() + " failed: cannot be typechecked anymore");
|
||||
}
|
||||
return this.optimizedForm;
|
||||
}
|
||||
|
||||
internal IExpression OptimizeInternal(out bool somethingChanged)
|
||||
{
|
||||
if (!Types.Any())
|
||||
public IExpression Optimize()
|
||||
{
|
||||
if (Types.Count() == 0) {
|
||||
throw new ArgumentException("This application contain no valid types, so cannot be optimized" + this);
|
||||
}
|
||||
|
||||
somethingChanged = false;
|
||||
// (eitherfunc dot id) id
|
||||
// => (const dot _) id => dot id => id
|
||||
// or => (constRight _ id) id => id id => id
|
||||
|
@ -180,37 +147,23 @@ namespace AspectedRouting.Language.Expression
|
|||
Any),
|
||||
IsFunc(Funcs.Id)),
|
||||
IsFunc(Funcs.Id)
|
||||
).Invoke(this))
|
||||
{
|
||||
somethingChanged = true;
|
||||
).Invoke(this)) {
|
||||
return Funcs.Id;
|
||||
}
|
||||
|
||||
|
||||
if (Types.Count() > 1)
|
||||
{
|
||||
// Too much types to optimize: we optimize the subparts instead
|
||||
if (Types.Count() > 1) {
|
||||
// Too much types to optimize
|
||||
var optimized = new Dictionary<Type, (IExpression f, IExpression a)>();
|
||||
foreach (var (resultType, (f, a)) in FunctionApplications)
|
||||
{
|
||||
var fOpt = f.Optimize(out var scf);
|
||||
var aOpt = a.Optimize(out var sca);
|
||||
somethingChanged |= scf || sca;
|
||||
foreach (var (resultType, (f, a)) in FunctionApplications) {
|
||||
var fOpt = f.Optimize();
|
||||
var aOpt = a.Optimize();
|
||||
optimized.Add(resultType, (fOpt, aOpt));
|
||||
}
|
||||
|
||||
if (somethingChanged)
|
||||
{
|
||||
return new Apply(_debugInfo, optimized);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// At this point, we know there only is a single type;
|
||||
// We can safely assume all the 'assign' will only match a single entry
|
||||
|
||||
{
|
||||
// id a => a
|
||||
var arg = new List<IExpression>();
|
||||
|
@ -218,40 +171,11 @@ namespace AspectedRouting.Language.Expression
|
|||
UnApplyAny(
|
||||
IsFunc(Funcs.Id),
|
||||
Assign(arg)
|
||||
).Invoke(this))
|
||||
{
|
||||
var argOpt = arg.First().Optimize(out _);
|
||||
somethingChanged = true;
|
||||
return argOpt;
|
||||
).Invoke(this)) {
|
||||
return arg.First();
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var exprs = new List<Constant>();
|
||||
var arg = new List<IExpression>();
|
||||
// listDot ([f0, f1, f2, ...]) arg ---> [f0 arg, f1 arg, f2 arg, ...]
|
||||
if (UnApply(
|
||||
UnApply(
|
||||
IsFunc(Funcs.ListDot),
|
||||
IsConstant(exprs)
|
||||
),
|
||||
Assign(arg)
|
||||
).Invoke(this))
|
||||
{
|
||||
var a = arg.First();
|
||||
var c = exprs.First();
|
||||
if (c.Types.All(t => t is ListType))
|
||||
{
|
||||
// The constant is a list
|
||||
var o = (List<IExpression>)c.Get();
|
||||
somethingChanged = true;
|
||||
return new Constant(
|
||||
o.Select(e => e.Apply(a).Optimize(out var _)).ToList()
|
||||
);
|
||||
}
|
||||
// fallthrough!
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// ifdotted fcondition fthen felse arg => if (fcondition arg) (fthen arg) (felse arg)
|
||||
|
@ -270,104 +194,38 @@ namespace AspectedRouting.Language.Expression
|
|||
Assign(fthen)),
|
||||
Assign(felse)),
|
||||
Assign(arg)
|
||||
).Invoke(this))
|
||||
{
|
||||
).Invoke(this)) {
|
||||
var a = arg.First();
|
||||
somethingChanged = true;
|
||||
return
|
||||
Funcs.If.Apply(
|
||||
fcondition.First().Apply(a).Optimize(out var _),
|
||||
fthen.First().Apply(a).Optimize(out var _),
|
||||
felse.First().Apply(a).Optimize(out var _)
|
||||
fcondition.First().Apply(a),
|
||||
fthen.First().Apply(a),
|
||||
felse.First().Apply(a)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// ifdotted fcondition fthen <null> arg => if (fcondition arg) (fthen arg) (felse arg)
|
||||
var fcondition = new List<IExpression>();
|
||||
var fthen = new List<IExpression>();
|
||||
var arg = new List<IExpression>();
|
||||
|
||||
if (
|
||||
this.Types.Any(t => !(t is Curry)) &&
|
||||
UnApply(
|
||||
UnApply(
|
||||
UnApply(
|
||||
IsFunc(Funcs.IfDotted),
|
||||
Assign(fcondition)),
|
||||
Assign(fthen)),
|
||||
Assign(arg)
|
||||
).Invoke(this))
|
||||
{
|
||||
var a = arg.First();
|
||||
somethingChanged = true;
|
||||
return
|
||||
Funcs.If.Apply(
|
||||
fcondition.First().Apply(a).Optimize(out var _),
|
||||
fthen.First().Apply(a).Optimize(out var _)
|
||||
).Specialize(this.Types).PruneTypes(t => !(t is Curry)).Optimize(out _);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// (default x f) a --> if (isNull (f a)) x (f a)
|
||||
var defaultArg = new List<IExpression>();
|
||||
var f = new List<IExpression>();
|
||||
var a = new List<IExpression>();
|
||||
if (
|
||||
UnApply(
|
||||
UnApply(
|
||||
UnApply(
|
||||
IsFunc(Funcs.Default),
|
||||
Assign(defaultArg)
|
||||
),
|
||||
Assign(f)
|
||||
|
||||
), Assign(a)
|
||||
).Invoke(this))
|
||||
{
|
||||
|
||||
somethingChanged = true;
|
||||
var fa = f.First().Apply(a.First()).Optimize(out var _);
|
||||
return Funcs.If.Apply(
|
||||
Funcs.IsNull.Apply(fa)
|
||||
).Apply(defaultArg).Apply(fa);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// The fallback case
|
||||
// We couldn't optimize with a pattern, but the subparts might be optimizable
|
||||
var (f, a) = FunctionApplications.Values.First();
|
||||
|
||||
var (newFa, expr) = OptimizeApplicationPair(f, a, out var changed);
|
||||
if (expr != null)
|
||||
{
|
||||
somethingChanged = true;
|
||||
var (newFa, expr) = OptimizeApplicationPair(f, a);
|
||||
if (expr != null) {
|
||||
return expr;
|
||||
}
|
||||
|
||||
if (changed)
|
||||
{
|
||||
somethingChanged = true;
|
||||
(f, a) = newFa.Value;
|
||||
return new Apply(f, a).Optimize(out _);
|
||||
return new Apply(f, a);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public void Visit(Func<IExpression, bool> visitor)
|
||||
{
|
||||
var continueVisit = visitor(this);
|
||||
if (!continueVisit)
|
||||
{
|
||||
if (!continueVisit) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (_, (f, a)) in FunctionApplications)
|
||||
{
|
||||
foreach (var (_, (f, a)) in FunctionApplications) {
|
||||
f.Visit(visitor);
|
||||
a.Visit(visitor);
|
||||
}
|
||||
|
@ -377,13 +235,10 @@ namespace AspectedRouting.Language.Expression
|
|||
{
|
||||
var newArgs = new Dictionary<Type, (IExpression f, IExpression a)>();
|
||||
|
||||
foreach (var allowedType in allowedTypes)
|
||||
{
|
||||
foreach (var (resultType, (funExpr, argExpr)) in FunctionApplications)
|
||||
{
|
||||
foreach (var allowedType in allowedTypes) {
|
||||
foreach (var (resultType, (funExpr, argExpr)) in FunctionApplications) {
|
||||
var substitutions = resultType.UnificationTable(allowedType, true);
|
||||
if (substitutions == null)
|
||||
{
|
||||
if (substitutions == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -395,8 +250,7 @@ namespace AspectedRouting.Language.Expression
|
|||
var actualFunction = funExpr.Specialize(substitutions);
|
||||
var actualArgument = argExpr.Specialize(substitutions);
|
||||
|
||||
if (actualFunction == null || actualArgument == null)
|
||||
{
|
||||
if (actualFunction == null || actualArgument == null) {
|
||||
// One of the subexpressions can't be optimized
|
||||
return null;
|
||||
}
|
||||
|
@ -405,47 +259,34 @@ namespace AspectedRouting.Language.Expression
|
|||
}
|
||||
}
|
||||
|
||||
if (!newArgs.Any())
|
||||
{
|
||||
if (!newArgs.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Apply(_debugInfo, newArgs);
|
||||
}
|
||||
|
||||
private ((IExpression fOpt, IExpression fArg)?, IExpression result) OptimizeApplicationPair(
|
||||
IExpression fRaw,
|
||||
IExpression a,
|
||||
out bool somethingChanged)
|
||||
private ((IExpression fOpt, IExpression fArg)?, IExpression result) OptimizeApplicationPair(IExpression f,
|
||||
IExpression a)
|
||||
{
|
||||
somethingChanged = false;
|
||||
var f = fRaw.Optimize(out var scf);
|
||||
somethingChanged |= scf;
|
||||
f = f.Optimize();
|
||||
|
||||
if (f.Types.Count() == 0)
|
||||
{
|
||||
throw new ArgumentException("Optimizing " + f + " failed, no types returned. The original expression\n " + fRaw.ToString() + "has types" + string.Join("\n ", fRaw.Types));
|
||||
}
|
||||
a = a.Optimize();
|
||||
|
||||
a = a.Optimize(out var sca);
|
||||
somethingChanged |= sca;
|
||||
switch (f)
|
||||
{
|
||||
switch (f) {
|
||||
case Id _:
|
||||
return (null, a);
|
||||
|
||||
case Apply apply:
|
||||
|
||||
if (apply.F is Const _)
|
||||
{
|
||||
if (apply.F is Const _) {
|
||||
// (const x) y -> y
|
||||
// apply == (const x) thus we return 'x' and ignore 'a'
|
||||
|
||||
return (null, apply.A);
|
||||
}
|
||||
|
||||
if (apply.F is ConstRight _)
|
||||
{
|
||||
if (apply.F is ConstRight _) {
|
||||
// constRight x y -> y
|
||||
// apply == (constRight x) so we return a
|
||||
return (null, a);
|
||||
|
@ -459,14 +300,12 @@ namespace AspectedRouting.Language.Expression
|
|||
Assign(f0)
|
||||
),
|
||||
Assign(f1)).Invoke(apply)
|
||||
)
|
||||
{
|
||||
) {
|
||||
// apply == ((dot f0) f1)
|
||||
// ((dot f0) f1) a is the actual expression, but arg is already split of
|
||||
|
||||
// f0 (f1 arg)
|
||||
// which used to be (f0 . f1) arg
|
||||
somethingChanged = true;
|
||||
return ((f0.First(), new Apply(f1.First(), a)), null);
|
||||
}
|
||||
|
||||
|
@ -479,82 +318,21 @@ namespace AspectedRouting.Language.Expression
|
|||
|
||||
public override string ToString()
|
||||
{
|
||||
if (!FunctionApplications.Any())
|
||||
{
|
||||
if (!FunctionApplications.Any()) {
|
||||
return "NOT-TYPECHECKABLE APPLICATION: " + _debugInfo;
|
||||
}
|
||||
|
||||
var (f, arg) = FunctionApplications.Values.First();
|
||||
if (f is Id _)
|
||||
{
|
||||
if (f is Id _) {
|
||||
return arg.ToString();
|
||||
}
|
||||
|
||||
var extra = "";
|
||||
if (FunctionApplications.Count() > 1)
|
||||
{
|
||||
if (FunctionApplications.Count() > 1) {
|
||||
extra = " [" + FunctionApplications.Count + " IMPLEMENTATIONS]";
|
||||
}
|
||||
|
||||
return $"({f} {arg.ToString().Indent()})" + extra;
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (!(other is Apply apply))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var otherOptions = apply.FunctionApplications;
|
||||
if (otherOptions.Count != FunctionApplications.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (type, (otherF, otherA)) in otherOptions)
|
||||
{
|
||||
if (!FunctionApplications.TryGetValue(type, out var tuple))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!otherF.Equals(tuple.f))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!otherA.Equals(tuple.a))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
if (this.Types.Count() == 1)
|
||||
{
|
||||
var f = this.F.Repr().Replace("\n", "\n ");
|
||||
var a = this.A.Repr().Replace("\n", "\n ");
|
||||
|
||||
return $"new Apply( // {string.Join(" ; ", this.Types)}\n {f},\n {a})";
|
||||
}
|
||||
|
||||
var r = "new Apply(";
|
||||
|
||||
foreach (var (type, (f, a)) in this.FunctionApplications)
|
||||
{
|
||||
r += "\n // " + type + "\n";
|
||||
r += " | " + f.Repr().Replace("\n", "\n | ") + ",\n";
|
||||
r += " | " + a.Repr().Replace("\n", "\n | ") + "\n";
|
||||
}
|
||||
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -32,6 +32,7 @@ namespace AspectedRouting.Language.Expression
|
|||
|
||||
public object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
|
||||
return ExpressionImplementation.Evaluate(c, arguments);
|
||||
}
|
||||
|
||||
|
@ -42,31 +43,22 @@ namespace AspectedRouting.Language.Expression
|
|||
Name, Description, Author, Unit, Filepath);
|
||||
}
|
||||
|
||||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
public IExpression PruneTypes(System.Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var e = ExpressionImplementation.PruneTypes(allowedTypes);
|
||||
if (e == null)
|
||||
{
|
||||
if (e == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new AspectMetadata(e, Name, Description, Author, Unit,
|
||||
Filepath, ProfileInternal);
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
public IExpression Optimize()
|
||||
{
|
||||
var optE = ExpressionImplementation.Optimize(out var sc);
|
||||
somethingChanged = sc;
|
||||
if (sc)
|
||||
{
|
||||
return new AspectMetadata(optE,
|
||||
return new AspectMetadata(ExpressionImplementation.Optimize(),
|
||||
Name, Description, Author, Unit, Filepath);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public void Visit(Func<IExpression, bool> f)
|
||||
{
|
||||
var continueVisit = f(this);
|
||||
|
@ -82,20 +74,5 @@ namespace AspectedRouting.Language.Expression
|
|||
{
|
||||
return $"# {Name}; {Unit} by {Author}\n\n# by {Author}\n# {Description}\n{ExpressionImplementation}";
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is AspectMetadata amd)
|
||||
{
|
||||
return amd.ExpressionImplementation.Equals(ExpressionImplementation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
return "Aspect_" + Name;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -37,17 +37,15 @@ namespace AspectedRouting.Language.Expression
|
|||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passedTypes = this.Types.Where(allowedTypes);
|
||||
if (!passedTypes.Any())
|
||||
{
|
||||
if (!passedTypes.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FunctionCall(this.Name, passedTypes);
|
||||
}
|
||||
|
||||
public virtual IExpression Optimize(out bool somethingChanged)
|
||||
public virtual IExpression Optimize()
|
||||
{
|
||||
somethingChanged = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -102,20 +100,5 @@ namespace AspectedRouting.Language.Expression
|
|||
|
||||
return dict;
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is Function f)
|
||||
{
|
||||
return f.Name.Equals(this.Name);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
return "Funcs." + this.Name;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -33,11 +33,6 @@ namespace AspectedRouting.Language.Expression
|
|||
Types = types;
|
||||
}
|
||||
|
||||
public FunctionCall(string name, Type type) : this(name, new[] { type })
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
|
||||
|
@ -60,17 +55,15 @@ namespace AspectedRouting.Language.Expression
|
|||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passedTypes = this.Types.Where(allowedTypes);
|
||||
if (!passedTypes.Any())
|
||||
{
|
||||
if (!passedTypes.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FunctionCall(this._name, passedTypes);
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
public IExpression Optimize()
|
||||
{
|
||||
somethingChanged = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -94,21 +87,6 @@ namespace AspectedRouting.Language.Expression
|
|||
f(this);
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is FunctionCall fc)
|
||||
{
|
||||
return fc._name.Equals(this._name);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
return "new FunctionCall(\"" + this._name + "\")";
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"${_name}";
|
||||
|
|
|
@ -28,14 +28,7 @@ namespace AspectedRouting.Language.Expression
|
|||
public IExpression Access { get; }
|
||||
public IExpression Oneway { get; }
|
||||
public IExpression Speed { get; }
|
||||
|
||||
public IExpression ObstacleAccess { get; }
|
||||
public IExpression ObstacleCost { get; }
|
||||
|
||||
public Dictionary<string, IExpression> Priority { get; }
|
||||
|
||||
public IExpression ScalingFactor { get; }
|
||||
|
||||
/**
|
||||
* Moment of last change of any upstream file
|
||||
*/
|
||||
|
@ -45,21 +38,17 @@ namespace AspectedRouting.Language.Expression
|
|||
List<string> vehicleTyps, Dictionary<string, IExpression> defaultParameters,
|
||||
Dictionary<string, Dictionary<string, IExpression>> behaviours,
|
||||
IExpression access, IExpression oneway, IExpression speed,
|
||||
IExpression obstacleAccess, IExpression obstacleCost,
|
||||
Dictionary<string, IExpression> priority, IExpression scalingFactor, List<string> metadata, DateTime lastChange)
|
||||
Dictionary<string, IExpression> priority, List<string> metadata, DateTime lastChange)
|
||||
{
|
||||
Name = name;
|
||||
Description = description;
|
||||
Author = author;
|
||||
Filename = filename;
|
||||
VehicleTyps = vehicleTyps;
|
||||
Access = access.Optimize(out _);
|
||||
Oneway = oneway.Optimize(out _);
|
||||
Speed = speed.Optimize(out _);
|
||||
ObstacleAccess = obstacleAccess.Optimize(out _);
|
||||
ObstacleCost = obstacleCost.Optimize(out _);
|
||||
Access = access.Optimize();
|
||||
Oneway = oneway.Optimize();
|
||||
Speed = speed.Optimize();
|
||||
Priority = priority;
|
||||
ScalingFactor = scalingFactor;
|
||||
Metadata = metadata;
|
||||
LastChange = lastChange;
|
||||
DefaultParameters = defaultParameters;
|
||||
|
@ -68,28 +57,21 @@ namespace AspectedRouting.Language.Expression
|
|||
CheckTypes(Access, "access");
|
||||
CheckTypes(Oneway, "oneway");
|
||||
CheckTypes(Speed, "speed");
|
||||
CheckTypes(ObstacleAccess, "obstacleaccess");
|
||||
CheckTypes(ObstacleCost, "obstaclecost");
|
||||
|
||||
}
|
||||
|
||||
private static void CheckTypes(IExpression e, string name)
|
||||
{
|
||||
if (e == null)
|
||||
{
|
||||
throw new Exception("No expression given for " + name);
|
||||
}
|
||||
if (e.Types.Count() == 1)
|
||||
{
|
||||
if (e.Types.Count() == 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Exception("Insufficient specialization: " + name + " has multiple types left, namely " +
|
||||
e.Types.Pretty());
|
||||
throw new Exception("Insufficient specialization: " + name + " has multiple types left, namely " + e.Types.Pretty());
|
||||
}
|
||||
|
||||
public List<IExpression> AllExpressions(Context ctx)
|
||||
{
|
||||
var l = new List<IExpression> { Access, Oneway, Speed, ObstacleAccess, ObstacleCost };
|
||||
var l = new List<IExpression> {Access, Oneway, Speed};
|
||||
l.AddRange(DefaultParameters.Values);
|
||||
l.AddRange(Behaviours.Values.SelectMany(b => b.Values));
|
||||
l.AddRange(Priority.Values);
|
||||
|
@ -106,7 +88,6 @@ namespace AspectedRouting.Language.Expression
|
|||
var called = ctx.GetFunction(fc.CalledFunctionName);
|
||||
allExpr.Add(called);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
@ -114,48 +95,15 @@ namespace AspectedRouting.Language.Expression
|
|||
return allExpr;
|
||||
}
|
||||
|
||||
public List<IExpression> AllExpressionsFor(string behaviourName, Context context)
|
||||
{
|
||||
var allExpressions = new List<IExpression>
|
||||
{
|
||||
Access,
|
||||
Oneway,
|
||||
Speed,
|
||||
ObstacleAccess,
|
||||
ObstacleCost
|
||||
};
|
||||
|
||||
var behaviourContext = new Context(context);
|
||||
var behaviourParameters = ParametersFor(behaviourName);
|
||||
|
||||
|
||||
foreach (var (paramName, valueexpression) in Priority)
|
||||
public ProfileResult Run(Context c, string behaviour, Dictionary<string, string> tags)
|
||||
{
|
||||
var weightingFactor = behaviourParameters[paramName].Evaluate(behaviourContext);
|
||||
if (weightingFactor is double d)
|
||||
if (!Behaviours.ContainsKey(behaviour))
|
||||
{
|
||||
if (d == 0.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
throw new ArgumentException(
|
||||
$"Profile {Name} does not contain the behaviour {behaviour}\nTry one of {string.Join(",", Behaviours.Keys)}");
|
||||
}
|
||||
|
||||
if (weightingFactor is int i)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
allExpressions.Add(valueexpression);
|
||||
}
|
||||
|
||||
return allExpressions;
|
||||
}
|
||||
|
||||
public Dictionary<string, IExpression> ParametersFor(string behaviour)
|
||||
{
|
||||
var parameters = new Dictionary<string, IExpression>();
|
||||
|
||||
foreach (var (k, v) in DefaultParameters)
|
||||
|
@ -168,19 +116,8 @@ namespace AspectedRouting.Language.Expression
|
|||
parameters[k.TrimStart('#')] = v;
|
||||
}
|
||||
|
||||
return parameters;
|
||||
}
|
||||
|
||||
public ProfileResult Run(Context c, string behaviour, Dictionary<string, string> tags)
|
||||
{
|
||||
if (!Behaviours.ContainsKey(behaviour))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Profile {Name} does not contain the behaviour {behaviour}\nTry one of {string.Join(",", Behaviours.Keys)}");
|
||||
}
|
||||
|
||||
c = c.WithParameters(ParametersFor(behaviour))
|
||||
.WithAspectName(Name);
|
||||
c = c.WithParameters(parameters)
|
||||
.WithAspectName(this.Name);
|
||||
tags = new Dictionary<string, string>(tags);
|
||||
var canAccess = Access.Run(c, tags);
|
||||
tags["access"] = "" + canAccess;
|
||||
|
@ -209,35 +146,51 @@ namespace AspectedRouting.Language.Expression
|
|||
}
|
||||
|
||||
|
||||
var aspectWeight = new Apply(
|
||||
var aspectWeightObj = new Apply(
|
||||
Funcs.EitherFunc.Apply(Funcs.Id, Funcs.Const, expression)
|
||||
, new Constant(tags)).EvaluateDouble(paramName, c);
|
||||
, new Constant(tags)).Evaluate(c);
|
||||
|
||||
double aspectWeight;
|
||||
switch (aspectWeightObj)
|
||||
{
|
||||
case bool b:
|
||||
aspectWeight = b ? 1.0 : 0.0;
|
||||
break;
|
||||
case double d:
|
||||
aspectWeight = d;
|
||||
break;
|
||||
case int j:
|
||||
aspectWeight = j;
|
||||
break;
|
||||
case string s:
|
||||
if (s.Equals("yes"))
|
||||
{
|
||||
aspectWeight = 1.0;
|
||||
break;
|
||||
}
|
||||
else if (s.Equals("no"))
|
||||
{
|
||||
aspectWeight = 0.0;
|
||||
break;
|
||||
}
|
||||
|
||||
throw new Exception($"Invalid value as result for {paramName}: got string {s}");
|
||||
default:
|
||||
throw new Exception($"Invalid value as result for {paramName}: got object {aspectWeightObj}");
|
||||
}
|
||||
|
||||
weightExplanation.Add($"({paramName} = {aspectInfluence}) * {aspectWeight}");
|
||||
priority += aspectInfluence * aspectWeight;
|
||||
}
|
||||
|
||||
var scalingFactor = Utils.AsDouble(ScalingFactor.Run(c, tags) ?? 1.0, "scalingfactor");
|
||||
weightExplanation.Add("Scaling factor: " + scalingFactor);
|
||||
priority *= scalingFactor;
|
||||
if (priority <= 0)
|
||||
{
|
||||
canAccess = "no";
|
||||
weightExplanation.Add("WARNING: access has been set to 'no' as priority is < 0");
|
||||
}
|
||||
|
||||
if (canAccess is string canAccessString && oneway is string onewayString)
|
||||
{
|
||||
return new ProfileResult(canAccessString, onewayString, speed, priority,
|
||||
return new ProfileResult((string) canAccess, (string) oneway, speed, priority,
|
||||
string.Join("\n ", weightExplanation));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("CanAccess or oneway are not strings but " + canAccess.GetType() +
|
||||
" and " + (oneway?.GetType()?.ToString() ?? "<null>"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public override string ToString()
|
||||
|
|
|
@ -19,7 +19,6 @@ namespace AspectedRouting.Language
|
|||
public static readonly Function Eq = new Eq();
|
||||
public static readonly Function NotEq = new NotEq();
|
||||
public static readonly Function Inv = new Inv();
|
||||
public static readonly Function IsNull = new IsNull();
|
||||
|
||||
public static readonly Function Default = new Default();
|
||||
|
||||
|
@ -88,14 +87,15 @@ namespace AspectedRouting.Language
|
|||
}
|
||||
|
||||
var eSmallest = e.SpecializeToSmallestType();
|
||||
if (eSmallest == null || !eSmallest.Types.Any())
|
||||
if (eSmallest == null || eSmallest.Types.Count() == 0)
|
||||
{
|
||||
throw new Exception("Could not specialize " + e);
|
||||
}
|
||||
|
||||
// TODO FIX THIS so that it works
|
||||
// An argument 'optimizes' it's types from 'string -> bool' to 'string -> string'
|
||||
var eOpt = eSmallest.Optimize(out _);
|
||||
if (eOpt == null || !eOpt.Types.Any())
|
||||
var eOpt = eSmallest.Optimize();
|
||||
if (eOpt == null || eOpt.Types.Count() == 0)
|
||||
{
|
||||
throw new Exception("Could not optimize " + eSmallest);
|
||||
}
|
||||
|
@ -106,10 +106,6 @@ namespace AspectedRouting.Language
|
|||
|
||||
public static IExpression SpecializeToSmallestType(this IExpression e)
|
||||
{
|
||||
if (e == null)
|
||||
{
|
||||
throw new Exception("Cannot specialize null to a smallest type");
|
||||
}
|
||||
if (e.Types.Count() == 1)
|
||||
{
|
||||
return e;
|
||||
|
@ -164,8 +160,7 @@ namespace AspectedRouting.Language
|
|||
|
||||
var lastArg = args[args.Count - 1];
|
||||
var firstArgs = args.GetRange(0, args.Count - 1);
|
||||
var applied = Apply(function, firstArgs);
|
||||
return new Apply(applied, lastArg);
|
||||
return new Apply(Apply(function, firstArgs), lastArg);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,8 +6,7 @@ using Type = AspectedRouting.Language.Typ.Type;
|
|||
namespace AspectedRouting.Language.Functions
|
||||
{
|
||||
public class ConstRight : Function
|
||||
{
|
||||
public override string Description { get; } =
|
||||
{ public override string Description { get; } =
|
||||
"Small utility function, which takes two arguments `a` and `b` and returns `b`. Used extensively to insert freedom";
|
||||
|
||||
public override List<string> ArgNames { get; } = new List<string>{"a","b"};
|
||||
|
|
|
@ -14,11 +14,9 @@ namespace AspectedRouting.Language.Functions
|
|||
public Constant(IEnumerable<Type> types, object o)
|
||||
{
|
||||
Types = types.ToList();
|
||||
if (o is IEnumerable<IExpression> enumerable)
|
||||
{
|
||||
if (o is IEnumerable<IExpression> enumerable) {
|
||||
o = enumerable.ToList();
|
||||
if (enumerable.Any(x => x == null))
|
||||
{
|
||||
if (enumerable.Any(x => x == null)) {
|
||||
throw new NullReferenceException("Some subexpression is null");
|
||||
}
|
||||
}
|
||||
|
@ -29,11 +27,9 @@ namespace AspectedRouting.Language.Functions
|
|||
public Constant(Type t, object o)
|
||||
{
|
||||
Types = new List<Type> {t};
|
||||
if (o is IEnumerable<IExpression> enumerable)
|
||||
{
|
||||
if (o is IEnumerable<IExpression> enumerable) {
|
||||
o = enumerable.ToList();
|
||||
if (enumerable.Any(x => x == null))
|
||||
{
|
||||
if (enumerable.Any(x => x == null)) {
|
||||
throw new NullReferenceException("Some subexpression is null");
|
||||
}
|
||||
}
|
||||
|
@ -46,8 +42,7 @@ namespace AspectedRouting.Language.Functions
|
|||
var tps = exprs
|
||||
.SpecializeToCommonTypes(out var specializedVersions)
|
||||
.Select(t => new ListType(t));
|
||||
if (specializedVersions.Any(x => x == null))
|
||||
{
|
||||
if (specializedVersions.Any(x => x == null)) {
|
||||
throw new Exception("Specializing to common types failed for " +
|
||||
string.Join(",", exprs.Select(e => e.ToString())));
|
||||
}
|
||||
|
@ -58,31 +53,23 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public Constant(IReadOnlyCollection<IExpression> exprs)
|
||||
{
|
||||
try
|
||||
{
|
||||
try {
|
||||
|
||||
|
||||
|
||||
Types = exprs
|
||||
.SpecializeToCommonTypes(out var specializedVersions)
|
||||
.Select(t => new ListType(t))
|
||||
.ToList();
|
||||
specializedVersions = specializedVersions.ToList();
|
||||
if (specializedVersions.Any(x => x == null))
|
||||
{
|
||||
Console.Error.WriteLine(">> Some subexpressions of the list are null:");
|
||||
foreach (var expr in exprs)
|
||||
{
|
||||
Console.Error.WriteLine(expr.Repr());
|
||||
Console.Error.WriteLine("\n-------------------------\n");
|
||||
}
|
||||
|
||||
throw new NullReferenceException("Some subexpression of specialized versions are null");
|
||||
if (specializedVersions.Any(x => x == null)) {
|
||||
throw new NullReferenceException("Some subexpression is null");
|
||||
}
|
||||
|
||||
_o = specializedVersions.ToList();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
catch (Exception e) {
|
||||
throw new Exception("While creating a list with members " +
|
||||
string.Join(", ", exprs.Select(x => x.Optimize(out var _))) +
|
||||
string.Join(", ", exprs.Select(x => x.Optimize())) +
|
||||
$" {e.Message}", e);
|
||||
}
|
||||
}
|
||||
|
@ -95,12 +82,10 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public Constant(double d)
|
||||
{
|
||||
if (d >= 0)
|
||||
{
|
||||
if (d >= 0) {
|
||||
Types = new[] {Typs.Double, Typs.PDouble};
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
Types = new[] {Typs.Double};
|
||||
}
|
||||
|
||||
|
@ -109,12 +94,10 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public Constant(int i)
|
||||
{
|
||||
if (i >= 0)
|
||||
{
|
||||
Types = new[] { Typs.Double, Typs.Int, Typs.Nat, Typs.PDouble };
|
||||
if (i >= 0) {
|
||||
Types = new[] {Typs.Double, Typs.Nat, Typs.Nat, Typs.PDouble};
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
Types = new[] {Typs.Double, Typs.Int};
|
||||
}
|
||||
|
||||
|
@ -129,11 +112,10 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public IEnumerable<Type> Types { get; }
|
||||
|
||||
public IExpression PruneTypes(Func<Type, bool> allowedTypes)
|
||||
public IExpression PruneTypes(System.Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passedTypes = Types.Where(allowedTypes);
|
||||
if (!passedTypes.Any())
|
||||
{
|
||||
if (!passedTypes.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -142,24 +124,20 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public object Evaluate(Context c, params IExpression[] args)
|
||||
{
|
||||
if (_o is IExpression e)
|
||||
{
|
||||
if (_o is IExpression e) {
|
||||
return e.Evaluate(c).Pretty();
|
||||
}
|
||||
|
||||
|
||||
if (Types.Count() > 1)
|
||||
{
|
||||
if (Types.Count() > 1) {
|
||||
return _o;
|
||||
}
|
||||
|
||||
var t = Types.First();
|
||||
switch (t)
|
||||
{
|
||||
switch (t) {
|
||||
case DoubleType _:
|
||||
case PDoubleType _:
|
||||
if (_o is int i)
|
||||
{
|
||||
if (_o is int i) {
|
||||
return
|
||||
(double) i; // I know, it seems absurd having to write this as it is nearly the same as the return beneath, but it _is_ needed
|
||||
}
|
||||
|
@ -177,39 +155,31 @@ namespace AspectedRouting.Language.Functions
|
|||
{
|
||||
var allowedTypes = allowedTypesEnumerable.ToList();
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
if (unified == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var newO = _o;
|
||||
if (_o is IExpression e)
|
||||
{
|
||||
if (_o is IExpression e) {
|
||||
newO = e.Specialize(allowedTypes);
|
||||
}
|
||||
|
||||
if (_o is IEnumerable<IExpression> es)
|
||||
{
|
||||
if (_o is IEnumerable<IExpression> es) {
|
||||
var innerTypes = new List<Type>();
|
||||
foreach (var allowedType in allowedTypes)
|
||||
{
|
||||
if (allowedType is ListType listType)
|
||||
{
|
||||
foreach (var allowedType in allowedTypes) {
|
||||
if (allowedType is ListType listType) {
|
||||
innerTypes.Add(listType.InnerType);
|
||||
}
|
||||
}
|
||||
|
||||
var specializedExpressions = new List<IExpression>();
|
||||
foreach (var expr in es)
|
||||
{
|
||||
if (expr == null)
|
||||
{
|
||||
foreach (var expr in es) {
|
||||
if (expr == null) {
|
||||
throw new NullReferenceException("Subexpression is null");
|
||||
}
|
||||
|
||||
var specialized = expr.Specialize(innerTypes);
|
||||
if (specialized == null)
|
||||
{
|
||||
if (specialized == null) {
|
||||
// If a subexpression can not be specialized, this list cannot be specialized
|
||||
return null;
|
||||
}
|
||||
|
@ -223,38 +193,26 @@ namespace AspectedRouting.Language.Functions
|
|||
return new Constant(unified, newO);
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
{
|
||||
somethingChanged = false;
|
||||
if (_o is IEnumerable<IExpression> exprs)
|
||||
public IExpression Optimize()
|
||||
{
|
||||
if (_o is IEnumerable<IExpression> exprs) {
|
||||
// This is a list
|
||||
var optExprs = new List<IExpression>();
|
||||
foreach (var expression in exprs)
|
||||
{
|
||||
var exprOpt = expression.Optimize(out var sc);
|
||||
somethingChanged |= sc;
|
||||
if (exprOpt == null || exprOpt.Types.Count() == 0)
|
||||
{
|
||||
foreach (var expression in exprs) {
|
||||
var exprOpt = expression.Optimize();
|
||||
if (exprOpt == null || exprOpt.Types.Count() == 0) {
|
||||
throw new ArgumentException("Non-optimizable expression:" + expression);
|
||||
}
|
||||
|
||||
optExprs.Add(exprOpt);
|
||||
}
|
||||
|
||||
if (somethingChanged)
|
||||
{
|
||||
return new Constant(optExprs);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
if (_o is IExpression expr)
|
||||
{
|
||||
// This is a subexpression
|
||||
somethingChanged = true;
|
||||
return expr.Optimize(out var _);
|
||||
if (_o is IExpression expr) {
|
||||
// This is a list
|
||||
return new Constant(expr.Types, expr.Optimize());
|
||||
}
|
||||
|
||||
return this;
|
||||
|
@ -262,15 +220,12 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public void Visit(Func<IExpression, bool> f)
|
||||
{
|
||||
if (_o is IExpression e)
|
||||
{
|
||||
if (_o is IExpression e) {
|
||||
e.Visit(f);
|
||||
}
|
||||
|
||||
if (_o is IEnumerable<IExpression> es)
|
||||
{
|
||||
foreach (var x in es)
|
||||
{
|
||||
if (_o is IEnumerable<IExpression> es) {
|
||||
foreach (var x in es) {
|
||||
x.Visit(f);
|
||||
}
|
||||
}
|
||||
|
@ -278,28 +233,6 @@ namespace AspectedRouting.Language.Functions
|
|||
f(this);
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is Constant c)
|
||||
{
|
||||
return c._o.Equals(_o);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
if (_o is IEnumerable<IExpression> exprs)
|
||||
{
|
||||
return "new Constant(new []{" +
|
||||
string.Join(",\n ", exprs.Select(e => e.Repr().Replace("\n", "\n ")))
|
||||
+ "})";
|
||||
}
|
||||
|
||||
return "new Constant(" + (_o?.ToString() ?? null) + ")";
|
||||
}
|
||||
|
||||
public void EvaluateAll(Context c, HashSet<IExpression> addTo)
|
||||
{
|
||||
addTo.Add(this);
|
||||
|
@ -312,12 +245,7 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public override string ToString()
|
||||
{
|
||||
return ObjectExtensions.Pretty(_o);
|
||||
}
|
||||
|
||||
public object Get()
|
||||
{
|
||||
return _o;
|
||||
return _o.Pretty();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -325,24 +253,19 @@ namespace AspectedRouting.Language.Functions
|
|||
{
|
||||
public static string Pretty(this object o, Context context = null)
|
||||
{
|
||||
switch (o)
|
||||
{
|
||||
case null: return "null";
|
||||
switch (o) {
|
||||
case Dictionary<string, string> d:
|
||||
var txt = "";
|
||||
foreach (var (k, v) in d)
|
||||
{
|
||||
foreach (var (k, v) in d) {
|
||||
txt += $"{k}={v};";
|
||||
}
|
||||
|
||||
return $"{{{txt}}}";
|
||||
case Dictionary<string, List<string>> d:
|
||||
var t = "";
|
||||
foreach (var (k, v) in d)
|
||||
{
|
||||
foreach (var (k, v) in d) {
|
||||
var values = v.Pretty();
|
||||
if (!v.Any())
|
||||
{
|
||||
if (!v.Any()) {
|
||||
values = "*";
|
||||
}
|
||||
|
||||
|
|
|
@ -36,7 +36,6 @@ namespace AspectedRouting.Language.Functions
|
|||
{
|
||||
if (arguments.Count() <= 2)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
var f0 = arguments[0];
|
||||
|
|
|
@ -13,9 +13,9 @@ namespace AspectedRouting.Language.Functions
|
|||
"" +
|
||||
"Consider the mapping `{'someKey':'someValue'}`. Under normal circumstances, this acts as a pointwise-function, converting the string `someKey` into `someValue`, just like an ordinary dictionary would do. " +
|
||||
"However, in the context of `mustMatch`, we would prefer this to act as a _check_, that the highway _has_ a key `someKey` which is `someValue`, thus acting as " +
|
||||
"`{'someKey': {'$eq':'someValue'}}`. " +
|
||||
"Both behaviours are automatically supported in parsing, by parsing all string as `(eitherFunc id eq) 'someValue'`. " +
|
||||
"The type system is then able to figure out which implementation is needed an discards the unneeded implementations.\n\n" +
|
||||
"`{'someKey': {'$eq':'someValue'}}. " +
|
||||
"Both behaviours are automatically supported in parsing, by parsing the string as `(eitherFunc id eq) 'someValue'`. " +
|
||||
"The type system is then able to figure out which implementation is needed.\n\n" +
|
||||
"Disclaimer: _you should never ever need this in your profiles_";
|
||||
|
||||
public override List<string> ArgNames { get; } = new List<string>{"f","g","a"};
|
||||
|
|
|
@ -5,8 +5,7 @@ using AspectedRouting.Language.Typ;
|
|||
namespace AspectedRouting.Language.Functions
|
||||
{
|
||||
public class Eq : Function
|
||||
{
|
||||
public override string Description { get; } = "Returns 'yes' if both values _are_ the same";
|
||||
{ public override string Description { get; } = "Returns 'yes' if both values _are_ the same";
|
||||
public override List<string> ArgNames { get; } = new List<string>{"a","b"};
|
||||
public Eq() : base("eq", true,
|
||||
new[]
|
||||
|
|
|
@ -8,18 +8,15 @@ namespace AspectedRouting.Language.Functions
|
|||
{
|
||||
public class FirstMatchOf : Function
|
||||
{
|
||||
public override string Description { get; } = "This higher-order function takes a list of keys, a mapping (function over tags) and a collection of tags." +
|
||||
"It will try the function for the first key (and it's respective value). If the function fails (it gives null), it'll try the next key.\n\n" +
|
||||
"E.g. `$firstMatchOf ['maxspeed','highway'] {'maxspeed' --> $parse, 'highway' --> {residential --> 30, tertiary --> 50}}` applied on `{maxspeed=70, highway=tertiary}`" +
|
||||
" will yield `70` as that is the first key in the list; `{highway=residential}` will yield `30`.";
|
||||
public override string Description { get; } = "This higherorder function takes a list of keys, a mapping (function over tags) and a collection of tags. It will try the function for the first key (and it's respective value). If the function fails (it gives null), it'll try the next key.\n\n" +
|
||||
"E.g. `$firstMatchOf ['maxspeed','highway'] {'maxspeed' --> $parse, 'highway' --> {residential --> 30, tertiary --> 50}}` applied on `{maxspeed=70, highway=tertiary}` will yield `70` as that is the first key in the list; `{highway=residential}` will yield `30`.";
|
||||
public override List<string> ArgNames { get; } = new List<string> {"s"};
|
||||
|
||||
public FirstMatchOf() : base("first_match_of", true,
|
||||
new[]
|
||||
{
|
||||
// [String] -> (Tags -> [a]) -> Tags -> a
|
||||
Curry.ConstructFrom(
|
||||
new Var("a"), // Result type on top!
|
||||
Curry.ConstructFrom(new Var("a"), // Result type on top!
|
||||
new ListType(Typs.String),
|
||||
new Curry(Typs.Tags, new ListType(new Var("a"))),
|
||||
Typs.Tags
|
||||
|
|
|
@ -15,8 +15,7 @@ namespace AspectedRouting.Language.Functions
|
|||
new Curry(new Var("b"), new ListType(new Var("a"))),
|
||||
new Curry(new Var("b"), new Var("a")))
|
||||
}
|
||||
)
|
||||
{ }
|
||||
) { }
|
||||
|
||||
private HeadFunction(IEnumerable<Type> unified) : base("head", unified) { }
|
||||
|
||||
|
@ -28,25 +27,20 @@ namespace AspectedRouting.Language.Functions
|
|||
public override object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
object o = arguments[0];
|
||||
if (o is Apply app)
|
||||
{
|
||||
if (o is Apply app) {
|
||||
o = app.Evaluate(c, arguments.SubArray(1));
|
||||
}
|
||||
|
||||
while (o is IExpression e)
|
||||
{
|
||||
while (o is IExpression e) {
|
||||
o = e.Evaluate(c);
|
||||
}
|
||||
|
||||
if (!(o is IEnumerable<object> ls))
|
||||
{
|
||||
if (!(o is IEnumerable<object> ls)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var v in ls)
|
||||
{
|
||||
if (v != null)
|
||||
{
|
||||
foreach (var v in ls) {
|
||||
if (v != null) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
@ -57,8 +51,7 @@ namespace AspectedRouting.Language.Functions
|
|||
public override IExpression Specialize(IEnumerable<Type> allowedTypes)
|
||||
{
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
if (unified == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
@ -6,8 +6,7 @@ using AspectedRouting.Language.Typ;
|
|||
namespace AspectedRouting.Language.Functions
|
||||
{
|
||||
public class Id : Function
|
||||
{
|
||||
public override string Description { get; } = "Returns the argument unchanged - the identity function. Seems useless at first sight, but useful in parsing";
|
||||
{ public override string Description { get; } = "Returns the argument unchanged - the identity function. Seems useless at first sight, but useful in parsing";
|
||||
public override List<string> ArgNames { get; } = new List<string>{"a"};
|
||||
public Id() : base("id", true,
|
||||
new[]
|
||||
|
|
|
@ -10,9 +10,8 @@ namespace AspectedRouting.Language.Functions
|
|||
private static Var b = new Var("b");
|
||||
|
||||
public override string Description { get; } = "Selects either one of the branches, depending on the condition." +
|
||||
" The 'then' branch is returned if the condition returns the string `yes` or `true`." +
|
||||
" Otherwise, the `else` branch is taken (including if the condition returns `null`)" +
|
||||
"If the `else` branch is not set, `null` is returned if the condition evaluates to false.";
|
||||
" The 'then' branch is returned if the condition returns the string `yes` or `true`. Otherwise, the `else` branch is taken (including if the condition returns `null`)" +
|
||||
"If the `else` branch is not set, `null` is returned in the condition is false.";
|
||||
public override List<string> ArgNames { get; } = new List<string> {"condition", "then", "else"};
|
||||
|
||||
public If() : base("if_then_else", true,
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using Type = AspectedRouting.Language.Typ.Type;
|
||||
|
||||
namespace AspectedRouting.Language.Functions
|
||||
{
|
||||
|
@ -13,7 +11,7 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public override string Description { get; } = "An if_then_else, but one which takes an extra argument and applies it on the condition, then and else.\n" +
|
||||
"Consider `fc`, `fthen` and `felse` are all functions taking an `a`, then:\n" +
|
||||
"`(ifDotted fc fthen felse) a` === `(if (fc a) (fthen a) (felse a)`" +
|
||||
"`(ifDotted fc fthen felse) a` === `(if (fc a) (fthen a) (felse a)" +
|
||||
"Selects either one of the branches, depending on the condition." +
|
||||
" The 'then' branch is returned if the condition returns the string `yes` or `true` or the boolean `true`" +
|
||||
"If the `else` branch is not set, `null` is returned in the condition is false." +
|
||||
|
|
|
@ -1,50 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Language.Typ;
|
||||
using Type = AspectedRouting.Language.Typ.Type;
|
||||
|
||||
namespace AspectedRouting.Language.Functions
|
||||
{
|
||||
public class IsNull : Function
|
||||
{
|
||||
public override string Description { get; } = "Returns true if the given argument is null";
|
||||
public override List<string> ArgNames { get; } = new List<string> { "a" };
|
||||
|
||||
public IsNull() : base("is_null", true,
|
||||
new[]
|
||||
{
|
||||
new Curry(new Var("a"), Typs.Bool),
|
||||
})
|
||||
{
|
||||
}
|
||||
|
||||
private IsNull(IEnumerable<Type> specializedTypes) : base("is_null", specializedTypes)
|
||||
{
|
||||
}
|
||||
|
||||
public override IExpression Specialize(IEnumerable<Type> allowedTypes)
|
||||
{
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new IsNull(unified);
|
||||
}
|
||||
|
||||
public override object Evaluate(Context c, params IExpression[] arguments)
|
||||
{
|
||||
var arg = (string)arguments[0].Evaluate(c);
|
||||
if (arg == null)
|
||||
{
|
||||
return "yes";
|
||||
}
|
||||
|
||||
return "no";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -89,32 +89,30 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
var key = (string) s;
|
||||
var otherARgs = arguments.ToList().GetRange(1, arguments.Length - 1);
|
||||
if (!StringToResultFunctions.ContainsKey(key))
|
||||
{ // This is really roundabout, but it has to be
|
||||
if (!StringToResultFunctions.ContainsKey(key)) { // This is really roundabout, but it has to be
|
||||
return null;
|
||||
}
|
||||
|
||||
var resultFunction = StringToResultFunctions[key];
|
||||
if (resultFunction == null)
|
||||
{
|
||||
if (resultFunction == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resultFunction.Evaluate(c, otherARgs.ToArray());
|
||||
}
|
||||
|
||||
public override IExpression Optimize(out bool somethingChanged)
|
||||
public override IExpression Optimize()
|
||||
{
|
||||
var optimizedFunctions = new Dictionary<string, IExpression>();
|
||||
somethingChanged = false;
|
||||
|
||||
foreach (var (k, e) in StringToResultFunctions)
|
||||
{
|
||||
var opt = e.Optimize(out var sc);
|
||||
somethingChanged |= sc;
|
||||
if (!opt.Types.Any())
|
||||
{
|
||||
var opt = e.Optimize();
|
||||
|
||||
var typeOptStr = string.Join(";", opt.Types);
|
||||
var typeEStr = string.Join("; ", e.Types);
|
||||
if (!opt.Types.Any())
|
||||
{
|
||||
throw new NullReferenceException($"Optimized version is null, has different or empty types: " +
|
||||
$"\n{typeEStr}" +
|
||||
$"\n{typeOptStr}");
|
||||
|
@ -123,13 +121,7 @@ namespace AspectedRouting.Language.Functions
|
|||
optimizedFunctions[k] = opt;
|
||||
}
|
||||
|
||||
if (!somethingChanged)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
return new Mapping(optimizedFunctions);
|
||||
|
||||
}
|
||||
|
||||
public static Mapping Construct(params (string key, IExpression e)[] exprs)
|
||||
|
|
|
@ -13,8 +13,7 @@ namespace AspectedRouting.Language.Functions
|
|||
new Curry(Typs.Tags, Typs.Bool),
|
||||
new Curry(Typs.Tags, Typs.Bool))
|
||||
}
|
||||
)
|
||||
{ }
|
||||
) { }
|
||||
|
||||
public MemberOf(IEnumerable<Type> types) : base("memberOf", types) { }
|
||||
|
||||
|
@ -29,7 +28,7 @@ namespace AspectedRouting.Language.Functions
|
|||
" a flag `_relation:<aspect_name>=\"yes\"` will be set if the aspect matches on every way for where this aspect matches.\n" +
|
||||
"However, this plays poorly with parameters (e.g.: what if we want to cycle over a highway which is part of a certain cycling network with a certain `#network_name`?) " +
|
||||
"Luckily, parameters can only be simple values. To work around this problem, an extra tag is introduced for _every single profile_:" +
|
||||
"`_relation:<profile_name>:<aspect_name>=yes'. The subfunction is thus executed `countOf(relations) * countOf(profiles)` time, yielding `countOf(profiles)` tags." +
|
||||
"`_relation:<profile_name>:<aspect_name>=yes'. The subfunction is thus executed `countOr(relations) * countOf(profiles)` time, yielding `countOf(profiles)` tags." +
|
||||
" The profile function then picks the tags for himself and strips the `<profile_name>:` away from the key.\n\n" +
|
||||
"\n\n" +
|
||||
"In the test.csv, one can simply use `_relation:<aspect_name>=yes` to mimic relations in your tests";
|
||||
|
@ -43,40 +42,31 @@ namespace AspectedRouting.Language.Functions
|
|||
var tags = (Dictionary<string, string>) arguments[1].Evaluate(c);
|
||||
var name = c.AspectName.TrimStart('$');
|
||||
|
||||
if (tags.TryGetValue("_relation:" + name, out var v))
|
||||
{
|
||||
if (tags.TryGetValue("_relation:" + name, out var v)) {
|
||||
return v;
|
||||
}
|
||||
|
||||
// In the case of tests, relations might be added with "_relation:1:<key>"
|
||||
// So, we create this table as dictionary
|
||||
var relationTags = new Dictionary<string, Dictionary<string, string>>();
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
if (!tag.Key.StartsWith("_relation:"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var tag in tags) {
|
||||
if (tag.Key.StartsWith("_relation:")) {
|
||||
var keyParts = tag.Key.Split(":");
|
||||
if (keyParts.Length != 3)
|
||||
{
|
||||
if (keyParts.Length != 3) {
|
||||
continue;
|
||||
}
|
||||
var relationName = keyParts[1];
|
||||
if (!relationTags.ContainsKey(relationName))
|
||||
{
|
||||
if (!relationTags.ContainsKey(relationName)) {
|
||||
relationTags.Add(relationName, new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
relationTags[relationName].Add(keyParts[2], tag.Value);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var relationTagging in relationTags)
|
||||
{
|
||||
foreach (var relationTagging in relationTags) {
|
||||
var result = arguments[0].Evaluate(c, new Constant(relationTagging.Value));
|
||||
if (result.Equals("yes"))
|
||||
{
|
||||
if (result.Equals("yes")) {
|
||||
return "yes";
|
||||
}
|
||||
}
|
||||
|
@ -87,8 +77,7 @@ namespace AspectedRouting.Language.Functions
|
|||
public override IExpression Specialize(IEnumerable<Type> allowedTypes)
|
||||
{
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
if (unified == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
@ -42,8 +42,7 @@ namespace AspectedRouting.Language.Functions
|
|||
public override IExpression Specialize(IEnumerable<Type> allowedTypes)
|
||||
{
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
if (unified == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -57,33 +56,27 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
var tags = (Dictionary<string, string>) arguments[2].Evaluate(c);
|
||||
|
||||
foreach (var oo in neededKeys)
|
||||
{
|
||||
foreach (var oo in neededKeys) {
|
||||
var o = oo;
|
||||
while (o is IExpression e)
|
||||
{
|
||||
while (o is IExpression e) {
|
||||
o = e.Evaluate(c);
|
||||
}
|
||||
|
||||
if (!(o is string tagKey))
|
||||
{
|
||||
if (!(o is string tagKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!tags.ContainsKey(tagKey))
|
||||
{
|
||||
if (!tags.ContainsKey(tagKey)) {
|
||||
// A required key is missing
|
||||
// Normally, we return no; but there is a second chance
|
||||
// IF the mapping returns 'yes' on null, we make an exception and ignore it
|
||||
var applied = function.Evaluate(c, new Constant(new Dictionary<string, string> {
|
||||
{tagKey, ""}
|
||||
}));
|
||||
if (applied == null)
|
||||
{
|
||||
if (applied == null) {
|
||||
return "no";
|
||||
}
|
||||
if (applied.Equals("yes") || (applied is IEnumerable<object> l && l.Count() > 0 && l.ToList()[0].Equals("yes")))
|
||||
{
|
||||
if (applied.Equals("yes") || (applied is IEnumerable<object> l && l.Count() > 0 && l.ToList()[0].Equals("yes")) ) {
|
||||
continue; // We ignore the absence of the key
|
||||
}
|
||||
return "no";
|
||||
|
@ -94,8 +87,7 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
if (result.Any(o =>
|
||||
o == null ||
|
||||
o is string s && (s.Equals("no") || s.Equals("false"))))
|
||||
{
|
||||
o is string s && (s.Equals("no") || s.Equals("false")))) {
|
||||
// The mapped function is executed. If the mapped function gives 'no', null or 'false' for any value, "no" is returned
|
||||
return "no";
|
||||
}
|
||||
|
|
|
@ -37,11 +37,6 @@ namespace AspectedRouting.Language.Functions
|
|||
|
||||
public IExpression Specialize(IEnumerable<Type> allowedTypes)
|
||||
{
|
||||
/* var filtered = allowedTypes.Where(at => !(at is Curry));
|
||||
if (filtered.Count() == 0)
|
||||
{
|
||||
return null;
|
||||
}*/
|
||||
var unified = Types.SpecializeTo(allowedTypes);
|
||||
if (unified == null)
|
||||
{
|
||||
|
@ -54,17 +49,15 @@ namespace AspectedRouting.Language.Functions
|
|||
public IExpression PruneTypes(System.Func<Type, bool> allowedTypes)
|
||||
{
|
||||
var passedTypes = this.Types.Where(allowedTypes);
|
||||
if (!passedTypes.Any())
|
||||
{
|
||||
if (!passedTypes.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Parameter(passedTypes, this.ParamName);
|
||||
}
|
||||
|
||||
public IExpression Optimize(out bool somethingChanged)
|
||||
public IExpression Optimize()
|
||||
{
|
||||
somethingChanged = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -78,26 +71,9 @@ namespace AspectedRouting.Language.Functions
|
|||
f(this);
|
||||
}
|
||||
|
||||
public bool Equals(IExpression other)
|
||||
{
|
||||
if (other is Parameter p)
|
||||
{
|
||||
return p.ParamName.Equals(this.ParamName);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string Repr()
|
||||
{
|
||||
return "new Parameter(\"" + this.ParamName + "\")";
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return ParamName;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
|
@ -62,7 +62,7 @@ namespace AspectedRouting.Language.Functions
|
|||
default: return int.Parse(arg);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine("Could not parse " + arg + " as " + expectedType);
|
||||
return null;
|
||||
|
|
|
@ -34,8 +34,7 @@ namespace AspectedRouting.Language.Functions
|
|||
{
|
||||
var f = arguments[0];
|
||||
var tags = (Dictionary<string, string>) arguments[1].Evaluate(c);
|
||||
if (tags == null)
|
||||
{
|
||||
if (tags == null) {
|
||||
return null;
|
||||
}
|
||||
var result = new List<object>();
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language.Functions;
|
||||
using AspectedRouting.Language.Typ;
|
||||
|
@ -32,60 +31,38 @@ namespace AspectedRouting.Language
|
|||
/// Optimize a single expression, eventually recursively (e.g. a list can optimize all the contents)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IExpression Optimize(out bool somethingChanged);
|
||||
IExpression Optimize();
|
||||
|
||||
/// <summary>
|
||||
/// Optimize with the given argument, e.g. listdot can become a list of applied arguments.
|
||||
/// By default, this should return 'this.Apply(argument)'
|
||||
/// </summary>
|
||||
/// <param name="argument"></param>
|
||||
/// <returns></returns>
|
||||
// IExpression OptimizeWithArgument(IExpression argument);
|
||||
void Visit(Func<IExpression, bool> f);
|
||||
|
||||
bool Equals(IExpression other);
|
||||
|
||||
/**
|
||||
* Builds a string representation that can be used to paste into C# test programs
|
||||
*/
|
||||
string Repr();
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static class ExpressionExtensions
|
||||
{
|
||||
|
||||
public static void PrintRepr(this IExpression e)
|
||||
{
|
||||
Console.WriteLine(e.Repr() + "\n\n-----------\n");
|
||||
}
|
||||
public static object Run(this IExpression e, Context c, Dictionary<string, string> tags)
|
||||
{
|
||||
try
|
||||
{
|
||||
try {
|
||||
var result = e.Apply(new Constant(tags)).Evaluate(c);
|
||||
while (result is IExpression ex)
|
||||
{
|
||||
while (result is IExpression ex) {
|
||||
result = ex.Apply(new Constant(tags)).Evaluate(c);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
catch (Exception err) {
|
||||
throw new Exception($"While evaluating the expression {e} with arguments a list of tags", err);
|
||||
}
|
||||
}
|
||||
|
||||
public static double EvaluateDouble(this IExpression e, string paramName, Context c, params IExpression[] arguments)
|
||||
{
|
||||
return Utils.AsDouble(e.Evaluate(c, arguments), paramName);
|
||||
}
|
||||
|
||||
public static IExpression Specialize(this IExpression e, Type t)
|
||||
{
|
||||
if (t == null)
|
||||
{
|
||||
if (t == null) {
|
||||
throw new NullReferenceException("Cannot specialize to null");
|
||||
}
|
||||
|
||||
|
@ -96,19 +73,16 @@ namespace AspectedRouting.Language
|
|||
{
|
||||
var newTypes = new HashSet<Type>();
|
||||
|
||||
foreach (var oldType in e.Types)
|
||||
{
|
||||
foreach (var oldType in e.Types) {
|
||||
var newType = oldType.Substitute(substitutions);
|
||||
if (newType == null)
|
||||
{
|
||||
if (newType == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
newTypes.Add(newType);
|
||||
}
|
||||
|
||||
if (!newTypes.Any())
|
||||
{
|
||||
if (!newTypes.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -135,17 +109,13 @@ namespace AspectedRouting.Language
|
|||
var allExpressions = new HashSet<IExpression>();
|
||||
specializedExpressions = allExpressions;
|
||||
|
||||
foreach (var expr in exprs)
|
||||
{
|
||||
if (specializedTypes == null)
|
||||
{
|
||||
specializedTypes = expr.Types; // This is t
|
||||
foreach (var expr in exprs) {
|
||||
if (specializedTypes == null) {
|
||||
specializedTypes = expr.Types;
|
||||
}
|
||||
else
|
||||
{
|
||||
else {
|
||||
var newlySpecialized = Typs.WidestCommonTypes(specializedTypes, expr.Types);
|
||||
if (!newlySpecialized.Any())
|
||||
{
|
||||
if (!newlySpecialized.Any()) {
|
||||
throw new ArgumentException("Could not find a common ground for types "+specializedTypes.Pretty()+ " and "+expr.Types.Pretty());
|
||||
}
|
||||
|
||||
|
@ -155,8 +125,7 @@ namespace AspectedRouting.Language
|
|||
|
||||
}
|
||||
|
||||
foreach (var expr in exprs)
|
||||
{
|
||||
foreach (var expr in exprs) {
|
||||
var e = expr.Specialize(specializedTypes);
|
||||
allExpressions.Add(e);
|
||||
}
|
||||
|
|
|
@ -30,20 +30,16 @@ namespace AspectedRouting.Language.Typ
|
|||
var results = new HashSet<Type>();
|
||||
|
||||
allowedTypes = allowedTypes.ToList();
|
||||
foreach (var t0 in types0)
|
||||
{
|
||||
foreach (var allowed in allowedTypes)
|
||||
{
|
||||
foreach (var t0 in types0) {
|
||||
foreach (var allowed in allowedTypes) {
|
||||
var unified = t0.Unify(allowed, reverseSuperSet);
|
||||
if (unified != null)
|
||||
{
|
||||
if (unified != null) {
|
||||
results.Add(unified);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (results.Any())
|
||||
{
|
||||
if (results.Any()) {
|
||||
return results;
|
||||
}
|
||||
|
||||
|
@ -63,14 +59,12 @@ namespace AspectedRouting.Language.Typ
|
|||
public static Type Unify(this Type t0, Type t1, bool reverseSuperset = false)
|
||||
{
|
||||
var table = t0.UnificationTable(t1, reverseSuperset);
|
||||
if (table == null)
|
||||
{
|
||||
if (table == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var subbed = t0.Substitute(table);
|
||||
if (reverseSuperset)
|
||||
{
|
||||
if (reverseSuperset) {
|
||||
return SelectSmallestUnion(t1, subbed);
|
||||
}
|
||||
|
||||
|
@ -85,8 +79,7 @@ namespace AspectedRouting.Language.Typ
|
|||
/// <returns></returns>
|
||||
private static Type SelectSmallestUnion(this Type wider, Type smaller)
|
||||
{
|
||||
switch (wider)
|
||||
{
|
||||
switch (wider) {
|
||||
case Var a:
|
||||
return a;
|
||||
case ListType l when smaller is ListType lsmaller:
|
||||
|
@ -100,8 +93,7 @@ namespace AspectedRouting.Language.Typ
|
|||
cWider.ResultType.SelectSmallestUnion(cSmaller.ResultType);
|
||||
return new Curry(arg, result);
|
||||
default:
|
||||
if (wider.IsSuperSet(smaller) && !smaller.IsSuperSet(wider))
|
||||
{
|
||||
if (wider.IsSuperSet(smaller) && !smaller.IsSuperSet(wider)) {
|
||||
return smaller;
|
||||
}
|
||||
|
||||
|
@ -119,8 +111,7 @@ namespace AspectedRouting.Language.Typ
|
|||
public static IEnumerable<Type> UnifyAll(this Type t0, IEnumerable<Type> t1)
|
||||
{
|
||||
var result = t1.Select(t => t0.Unify(t)).ToHashSet();
|
||||
if (result.Any(x => x == null))
|
||||
{
|
||||
if (result.Any(x => x == null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -130,8 +121,7 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
public static Type Substitute(this Type t0, Dictionary<string, Type> substitutions)
|
||||
{
|
||||
switch (t0)
|
||||
{
|
||||
switch (t0) {
|
||||
case Var a when substitutions.TryGetValue(a.Name, out var t):
|
||||
return t;
|
||||
case ListType l:
|
||||
|
@ -161,8 +151,7 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
bool AddSubs(string key, Type valueToAdd)
|
||||
{
|
||||
if (substitutionsOn0.TryGetValue(key, out var oldSubs))
|
||||
{
|
||||
if (substitutionsOn0.TryGetValue(key, out var oldSubs)) {
|
||||
return oldSubs.Equals(valueToAdd);
|
||||
}
|
||||
|
||||
|
@ -172,15 +161,12 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
bool AddAllSubs(Dictionary<string, Type> table)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
if (table == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (key, tp) in table)
|
||||
{
|
||||
if (!AddSubs(key, tp))
|
||||
{
|
||||
foreach (var (key, tp) in table) {
|
||||
if (!AddSubs(key, tp)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -188,33 +174,27 @@ namespace AspectedRouting.Language.Typ
|
|||
return true;
|
||||
}
|
||||
|
||||
switch (t0)
|
||||
{
|
||||
switch (t0) {
|
||||
case Var a:
|
||||
if (!AddSubs(a.Name, t1))
|
||||
{
|
||||
if (!AddSubs(a.Name, t1)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
break;
|
||||
case ListType l0 when t1 is ListType l1:
|
||||
{
|
||||
case ListType l0 when t1 is ListType l1: {
|
||||
var table = l0.InnerType.UnificationTable(l1.InnerType, reverseSupersetRelation);
|
||||
if (!AddAllSubs(table))
|
||||
{
|
||||
if (!AddAllSubs(table)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case Curry curry0 when t1 is Curry curry1:
|
||||
{
|
||||
case Curry curry0 when t1 is Curry curry1: {
|
||||
// contravariance for arguments: reversed
|
||||
var tableA = curry0.ArgType.UnificationTable(curry1.ArgType, !reverseSupersetRelation);
|
||||
var tableB = curry0.ResultType.UnificationTable(curry1.ResultType, reverseSupersetRelation);
|
||||
if (!(AddAllSubs(tableA) && AddAllSubs(tableB)))
|
||||
{
|
||||
if (!(AddAllSubs(tableA) && AddAllSubs(tableB))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -223,19 +203,16 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
default:
|
||||
|
||||
if (t1 is Var v)
|
||||
{
|
||||
if (t1 is Var v) {
|
||||
AddSubs(v.Name, t0);
|
||||
break;
|
||||
}
|
||||
|
||||
if (!reverseSupersetRelation && !t0.IsSuperSet(t1))
|
||||
{
|
||||
if (!reverseSupersetRelation && !t0.IsSuperSet(t1)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (reverseSupersetRelation && !t1.IsSuperSet(t0))
|
||||
{
|
||||
if (reverseSupersetRelation && !t1.IsSuperSet(t0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -250,28 +227,23 @@ namespace AspectedRouting.Language.Typ
|
|||
// We do not have to worry about overlapping names, as they should be cleaned before calling this method
|
||||
|
||||
bool appliedTransitivity;
|
||||
do
|
||||
{
|
||||
do {
|
||||
appliedTransitivity = false;
|
||||
var keys = substitutionsOn0.Keys.ToList();
|
||||
foreach (var key in keys)
|
||||
{
|
||||
foreach (var key in keys) {
|
||||
var val = substitutionsOn0[key];
|
||||
var usedVars = val.UsedVariables();
|
||||
var isContained = keys.Any(usedVars.Contains);
|
||||
if (!isContained)
|
||||
{
|
||||
if (!isContained) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var newVal = val.Substitute(substitutionsOn0);
|
||||
if (newVal.Equals(val))
|
||||
{
|
||||
if (newVal.Equals(val)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (newVal.UsedVariables().Contains(key) && !newVal.Equals(new Var(key)))
|
||||
{
|
||||
if (newVal.UsedVariables().Contains(key) && !newVal.Equals(new Var(key))) {
|
||||
// The substitution contains itself; and it is bigger then itself
|
||||
// This means that $a is substituted by e.g. ($a -> $x), implying an infinite and contradictory type
|
||||
return null;
|
||||
|
@ -288,19 +260,16 @@ namespace AspectedRouting.Language.Typ
|
|||
public static HashSet<string> UsedVariables(this Type t0, HashSet<string> addTo = null)
|
||||
{
|
||||
addTo ??= new HashSet<string>();
|
||||
switch (t0)
|
||||
{
|
||||
switch (t0) {
|
||||
case Var a:
|
||||
addTo.Add(a.Name);
|
||||
break;
|
||||
case ListType l0:
|
||||
{
|
||||
case ListType l0: {
|
||||
l0.InnerType.UsedVariables(addTo);
|
||||
break;
|
||||
}
|
||||
|
||||
case Curry curry0:
|
||||
{
|
||||
case Curry curry0: {
|
||||
curry0.ArgType.UsedVariables(addTo);
|
||||
curry0.ResultType.UsedVariables(addTo);
|
||||
break;
|
||||
|
@ -313,13 +282,11 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
public static bool IsSuperSet(this Type t0, Type t1)
|
||||
{
|
||||
if (t0 is Var || t1 is Var)
|
||||
{
|
||||
if (t0 is Var || t1 is Var) {
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (t0)
|
||||
{
|
||||
switch (t0) {
|
||||
case StringType _ when t1 is BoolType _:
|
||||
return true;
|
||||
case DoubleType _ when t1 is PDoubleType _:
|
||||
|
@ -338,8 +305,7 @@ namespace AspectedRouting.Language.Typ
|
|||
case ListType l0 when t1 is ListType l1:
|
||||
return l0.InnerType.IsSuperSet(l1.InnerType);
|
||||
|
||||
case Curry c0 when t1 is Curry c1:
|
||||
{
|
||||
case Curry c0 when t1 is Curry c1: {
|
||||
return c0.ResultType.IsSuperSet(c1.ResultType) &&
|
||||
c1.ArgType.IsSuperSet(c0.ArgType); // contravariance for arguments: reversed order!
|
||||
}
|
||||
|
@ -363,8 +329,7 @@ namespace AspectedRouting.Language.Typ
|
|||
|
||||
// The substitution table
|
||||
var subsTable = new Dictionary<string, Type>();
|
||||
foreach (var v in variablesToRename)
|
||||
{
|
||||
foreach (var v in variablesToRename) {
|
||||
var newValue = Var.Fresh(alreadyUsed);
|
||||
subsTable.Add(v, newValue);
|
||||
alreadyUsed.Add(newValue.Name);
|
||||
|
@ -377,8 +342,7 @@ namespace AspectedRouting.Language.Typ
|
|||
public static List<Type> Uncurry(this Type t)
|
||||
{
|
||||
var args = new List<Type>();
|
||||
while (t is Curry c)
|
||||
{
|
||||
while (t is Curry c) {
|
||||
args.Add(c.ArgType);
|
||||
t = c.ResultType;
|
||||
}
|
||||
|
@ -401,16 +365,12 @@ namespace AspectedRouting.Language.Typ
|
|||
{
|
||||
var widest = new HashSet<Type>();
|
||||
|
||||
foreach (var type0 in t0)
|
||||
{
|
||||
foreach (var type1 in t1)
|
||||
{
|
||||
foreach (var type0 in t0) {
|
||||
foreach (var type1 in t1) {
|
||||
var t = WidestCommonType(type0, type1);
|
||||
if (t != null)
|
||||
{
|
||||
if (t != null) {
|
||||
var (type, subsTable) = t.Value;
|
||||
if (subsTable != null)
|
||||
{
|
||||
if (subsTable != null) {
|
||||
type = type.Substitute(subsTable);
|
||||
}
|
||||
widest.Add(type);
|
||||
|
@ -437,18 +397,15 @@ namespace AspectedRouting.Language.Typ
|
|||
{
|
||||
// First things first: we try to unify
|
||||
|
||||
if (t0 is Curry c0 && t1 is Curry c1)
|
||||
{
|
||||
if (t0 is Curry c0 && t1 is Curry c1) {
|
||||
var arg = SmallestCommonType(c0.ArgType, c1.ArgType);
|
||||
var result = WidestCommonType(c0.ResultType, c1.ResultType);
|
||||
if (arg == null)
|
||||
{
|
||||
if (arg == null) {
|
||||
return null;
|
||||
}
|
||||
var (argT, subs0) = arg.Value;
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
var (resultT, subs1) = result.Value;
|
||||
|
@ -456,35 +413,28 @@ namespace AspectedRouting.Language.Typ
|
|||
}
|
||||
|
||||
|
||||
if (t0 is Var v)
|
||||
{
|
||||
if (t1 is Var vx)
|
||||
{
|
||||
if (v.Name == vx.Name)
|
||||
{
|
||||
if (t0 is Var v) {
|
||||
if (t1 is Var vx) {
|
||||
if (v.Name == vx.Name) {
|
||||
return (t0, null);
|
||||
}
|
||||
}
|
||||
return (t1, new Dictionary<string, Type> {{v.Name, t1}});
|
||||
}
|
||||
|
||||
if (t1 is Var v1)
|
||||
{
|
||||
if (t1 is Var v1) {
|
||||
return (t0, new Dictionary<string, Type> {{v1.Name, t1}});
|
||||
}
|
||||
if (t0 == t1 || t0.Equals(t1))
|
||||
{
|
||||
if (t0 == t1 || t0.Equals(t1)) {
|
||||
return (t0, null);
|
||||
}
|
||||
var t0IsSuperT1 = t0.IsSuperSet(t1);
|
||||
var t1IsSuperT0 = t1.IsSuperSet(t0);
|
||||
if (t0IsSuperT1 && !t1IsSuperT0)
|
||||
{
|
||||
if (t0IsSuperT1 && !t1IsSuperT0) {
|
||||
return (t0, null);
|
||||
}
|
||||
|
||||
if (t1IsSuperT0 && !t0IsSuperT1)
|
||||
{
|
||||
if (t1IsSuperT0 && !t0IsSuperT1) {
|
||||
return (t1, null);
|
||||
}
|
||||
|
||||
|
@ -494,25 +444,20 @@ namespace AspectedRouting.Language.Typ
|
|||
private static Dictionary<string, Type> MergeDicts(Dictionary<string, Type> subs0,
|
||||
Dictionary<string, Type> subs1)
|
||||
{
|
||||
if (subs0 == null && subs1 == null)
|
||||
{
|
||||
if (subs0 == null && subs1 == null) {
|
||||
return null;
|
||||
}
|
||||
var subsTable = new Dictionary<string, Type>();
|
||||
|
||||
void AddSubs(Dictionary<string, Type> dict)
|
||||
{
|
||||
if (dict == null)
|
||||
{
|
||||
if (dict == null) {
|
||||
return;
|
||||
}
|
||||
foreach (var kv in dict)
|
||||
{
|
||||
if (subsTable.TryGetValue(kv.Key, out var t))
|
||||
{
|
||||
foreach (var kv in dict) {
|
||||
if (subsTable.TryGetValue(kv.Key, out var t)) {
|
||||
// We have seen this variable-type-name before... We should check if it matches
|
||||
if (t.Equals(kv.Value))
|
||||
{
|
||||
if (t.Equals(kv.Value)) {
|
||||
// Ok! No problem!
|
||||
// It is already added anyway, so we continue
|
||||
continue;
|
||||
|
@ -522,10 +467,8 @@ namespace AspectedRouting.Language.Typ
|
|||
throw new Exception(t + " != " + kv.Value);
|
||||
}
|
||||
|
||||
if (kv.Value is Var v)
|
||||
{
|
||||
if (v.Name == kv.Key)
|
||||
{
|
||||
if (kv.Value is Var v) {
|
||||
if (v.Name == kv.Key) {
|
||||
// Well, this is a useless substitution...
|
||||
continue;
|
||||
}
|
||||
|
@ -538,8 +481,7 @@ namespace AspectedRouting.Language.Typ
|
|||
AddSubs(subs0);
|
||||
AddSubs(subs1);
|
||||
|
||||
if (!subsTable.Any())
|
||||
{
|
||||
if (!subsTable.Any()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -560,18 +502,15 @@ namespace AspectedRouting.Language.Typ
|
|||
/// <returns></returns>
|
||||
public static (Type, Dictionary<string, Type> substitutionTable)? SmallestCommonType(Type t0, Type t1)
|
||||
{
|
||||
if (t0 is Curry c0 && t1 is Curry c1)
|
||||
{
|
||||
if (t0 is Curry c0 && t1 is Curry c1) {
|
||||
var arg = WidestCommonType(c0.ArgType, c1.ArgType);
|
||||
var result = SmallestCommonType(c0.ResultType, c1.ResultType);
|
||||
if (arg == null)
|
||||
{
|
||||
if (arg == null) {
|
||||
return null;
|
||||
}
|
||||
var (argT, subs0) = arg.Value;
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
var (resultT, subs1) = result.Value;
|
||||
|
@ -579,30 +518,25 @@ namespace AspectedRouting.Language.Typ
|
|||
}
|
||||
|
||||
|
||||
if (t0 is Var v)
|
||||
{
|
||||
if (t0 is Var v) {
|
||||
return (t1, new Dictionary<string, Type> {{v.Name, t1}});
|
||||
}
|
||||
|
||||
if (t1 is Var v1)
|
||||
{
|
||||
if (t1 is Var v1) {
|
||||
return (t0, new Dictionary<string, Type> {{v1.Name, t1}});
|
||||
}
|
||||
|
||||
if (t0 == t1 || t0.Equals(t1))
|
||||
{
|
||||
if (t0 == t1 || t0.Equals(t1)) {
|
||||
return (t0, null);
|
||||
}
|
||||
|
||||
var t0IsSuperT1 = t0.IsSuperSet(t1);
|
||||
var t1IsSuperT0 = t1.IsSuperSet(t0);
|
||||
if (t0IsSuperT1 && !t1IsSuperT0)
|
||||
{
|
||||
if (t0IsSuperT1 && !t1IsSuperT0) {
|
||||
return (t0, null);
|
||||
}
|
||||
|
||||
if (t1IsSuperT0 && !t0IsSuperT1)
|
||||
{
|
||||
if (t1IsSuperT0 && !t0IsSuperT1) {
|
||||
return (t1, null);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,148 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
using AspectedRouting.IO.itinero2;
|
||||
using AspectedRouting.IO.md;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
using AspectedRouting.Tests;
|
||||
|
||||
namespace AspectedRouting
|
||||
{
|
||||
/**
|
||||
* Prints to the specified location
|
||||
*/
|
||||
public class Printer
|
||||
{
|
||||
private readonly List<(AspectMetadata aspect, AspectTestSuite tests)> _aspects;
|
||||
private readonly Context _context;
|
||||
private readonly string _outputDirectory;
|
||||
private readonly ProfileMetaData _profile;
|
||||
private readonly List<BehaviourTestSuite> _profileTests;
|
||||
private readonly bool _includeTests;
|
||||
|
||||
public Printer(string outputDirectory, ProfileMetaData profile, Context context,
|
||||
List<(AspectMetadata aspect, AspectTestSuite tests)> aspects,
|
||||
List<BehaviourTestSuite> profileTests, bool includeTests)
|
||||
{
|
||||
_outputDirectory = outputDirectory;
|
||||
_profile = profile;
|
||||
_context = context;
|
||||
_aspects = aspects;
|
||||
_profileTests = profileTests;
|
||||
_includeTests = includeTests;
|
||||
|
||||
|
||||
if (!Directory.Exists($"{outputDirectory}/profile-documentation/")) {
|
||||
Directory.CreateDirectory($"{outputDirectory}/profile-documentation/");
|
||||
}
|
||||
|
||||
if (!Directory.Exists($"{outputDirectory}/itinero1/")) {
|
||||
Directory.CreateDirectory($"{outputDirectory}/itinero1/");
|
||||
}
|
||||
|
||||
if (!Directory.Exists($"{outputDirectory}/itinero2/")) {
|
||||
Directory.CreateDirectory($"{outputDirectory}/itinero2/");
|
||||
}
|
||||
}
|
||||
|
||||
public void PrintUsedTags()
|
||||
{
|
||||
var profile = _profile;
|
||||
var context = _context;
|
||||
Console.WriteLine("\n\n\n---------- " + profile.Name +
|
||||
" : used tags and corresponding values --------------");
|
||||
foreach (var (key, values) in profile.AllExpressions(context).PossibleTags()) {
|
||||
var vs = "*";
|
||||
if (values.Any()) {
|
||||
vs = string.Join(", ", values);
|
||||
}
|
||||
|
||||
Console.WriteLine(key + ": " + vs);
|
||||
}
|
||||
|
||||
Console.WriteLine("\n\n\n------------------------");
|
||||
}
|
||||
|
||||
public void WriteProfile1()
|
||||
{
|
||||
var aspectTests = _aspects.Select(a => a.tests).ToList();
|
||||
|
||||
var luaProfile = new LuaPrinter1(_profile, _context,
|
||||
aspectTests,
|
||||
_profileTests
|
||||
).ToLua();
|
||||
|
||||
var itinero1ProfileFile = Path.Combine($"{_outputDirectory}/itinero1/" + _profile.Name + ".lua");
|
||||
File.WriteAllText(itinero1ProfileFile, luaProfile);
|
||||
Console.WriteLine($"Written {new FileInfo(itinero1ProfileFile).FullName}");
|
||||
}
|
||||
|
||||
public void WriteAllProfile2()
|
||||
{
|
||||
foreach (var (behaviourName,_) in _profile.Behaviours) {
|
||||
WriteProfile2(behaviourName);
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteProfile2(string behaviourName)
|
||||
{
|
||||
var aspectTests = _aspects.Select(a => a.tests).ToList();
|
||||
|
||||
var lua2behaviour = new LuaPrinter2(
|
||||
_profile,
|
||||
behaviourName,
|
||||
_context,
|
||||
aspectTests,
|
||||
_profileTests.Where(testsSuite => testsSuite.BehaviourName == behaviourName),
|
||||
_includeTests
|
||||
).ToLua();
|
||||
|
||||
var itinero2ProfileFile = Path.Combine($"{_outputDirectory}/itinero2/{_profile.Name}.{behaviourName}.lua");
|
||||
File.WriteAllText(
|
||||
itinero2ProfileFile,
|
||||
lua2behaviour);
|
||||
Console.WriteLine($"Written {new FileInfo(itinero2ProfileFile).FullName}");
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void PrintMdInfo()
|
||||
{
|
||||
var profileMd = new MarkDownSection();
|
||||
profileMd.AddTitle(_profile.Name, 1);
|
||||
|
||||
profileMd.Add(_profile.Description);
|
||||
profileMd.AddTitle("Default parameters", 4);
|
||||
profileMd.Add("| name | value | ", "| ---- | ---- | ",
|
||||
string.Join("\n",
|
||||
_profile.DefaultParameters.Select(delegate(KeyValuePair<string, IExpression> kv)
|
||||
{
|
||||
var v = kv.Value.Evaluate(_context);
|
||||
if (!(v is string || v is int || v is double)) {
|
||||
v = "_special value_";
|
||||
}
|
||||
|
||||
return $" | {kv.Key} | {v} |";
|
||||
}))
|
||||
);
|
||||
foreach (var (behaviourName, vars) in _profile.Behaviours) {
|
||||
var behaviourMd = new ProfileToMD(_profile, behaviourName, _context);
|
||||
|
||||
File.WriteAllText(
|
||||
$"{_outputDirectory}/profile-documentation/{_profile.Name}.{behaviourName}.md",
|
||||
behaviourMd.ToString());
|
||||
profileMd.AddTitle($"[{behaviourName}](./{_profile.Name}.{behaviourName}.md)", 2);
|
||||
profileMd.Add(vars["description"].Evaluate(_context).ToString());
|
||||
profileMd.Add(behaviourMd.MainFormula());
|
||||
}
|
||||
|
||||
File.WriteAllText(
|
||||
$"{_outputDirectory}/profile-documentation/{_profile.Name}.md",
|
||||
profileMd.ToString());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,10 +1,10 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using AspectedRouting.IO;
|
||||
using AspectedRouting.IO.itinero1;
|
||||
using AspectedRouting.IO.itinero2;
|
||||
using AspectedRouting.IO.jsonParser;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
|
@ -18,21 +18,19 @@ namespace AspectedRouting
|
|||
this IEnumerable<string> jsonFileNames, List<string> testFileNames, Context context)
|
||||
{
|
||||
var aspects = new List<(AspectMetadata aspect, AspectTestSuite tests)>();
|
||||
foreach (var file in jsonFileNames) {
|
||||
foreach (var file in jsonFileNames)
|
||||
{
|
||||
var fi = new FileInfo(file);
|
||||
|
||||
var aspect = JsonParser.AspectFromJson(context, File.ReadAllText(file), fi.Name);
|
||||
if (aspect == null) {
|
||||
continue;
|
||||
}
|
||||
if (aspect == null) continue;
|
||||
|
||||
|
||||
var testName = aspect.Name + ".test.csv";
|
||||
var testPath = testFileNames.FindTest(testName);
|
||||
AspectTestSuite tests = null;
|
||||
if (!string.IsNullOrEmpty(testPath) && File.Exists(testPath)) {
|
||||
if (!string.IsNullOrEmpty(testPath) && File.Exists(testPath))
|
||||
tests = AspectTestSuite.FromString(aspect, File.ReadAllText(testPath));
|
||||
}
|
||||
|
||||
aspects.Add((aspect, tests));
|
||||
}
|
||||
|
@ -43,13 +41,10 @@ namespace AspectedRouting
|
|||
private static string FindTest(this IEnumerable<string> testFileNames, string testName)
|
||||
{
|
||||
var testPaths = testFileNames.Where(nm => nm.EndsWith(testName)).ToList();
|
||||
if (testPaths.Count > 1) {
|
||||
if (testPaths.Count > 1)
|
||||
Console.WriteLine("[WARNING] Multiple tests found for " + testName + ", using only one arbitrarily");
|
||||
}
|
||||
|
||||
if (testPaths.Count > 0) {
|
||||
return testPaths.First();
|
||||
}
|
||||
if (testPaths.Count > 0) return testPaths.First();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
@ -60,32 +55,35 @@ namespace AspectedRouting
|
|||
{
|
||||
var result = new List<(ProfileMetaData profile, List<BehaviourTestSuite> profileTests)>();
|
||||
foreach (var jsonFile in jsonFiles)
|
||||
try {
|
||||
try
|
||||
{
|
||||
var profile =
|
||||
JsonParser.ProfileFromJson(context, File.ReadAllText(jsonFile), new FileInfo(jsonFile),
|
||||
lastChange);
|
||||
if (profile == null) {
|
||||
continue;
|
||||
}
|
||||
if (profile == null) continue;
|
||||
|
||||
profile.SanityCheckProfile(context);
|
||||
|
||||
var profileTests = new List<BehaviourTestSuite>();
|
||||
foreach (var behaviourName in profile.Behaviours.Keys) {
|
||||
foreach (var behaviourName in profile.Behaviours.Keys)
|
||||
{
|
||||
var path = testFiles.FindTest($"{profile.Name}.{behaviourName}.behaviour_test.csv");
|
||||
if (path != null && File.Exists(path)) {
|
||||
if (path != null && File.Exists(path))
|
||||
{
|
||||
var test = BehaviourTestSuite.FromString(context, profile, behaviourName,
|
||||
File.ReadAllText(path));
|
||||
profileTests.Add(test);
|
||||
}
|
||||
else {
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[{profile.Name}] WARNING: no test found for behaviour {behaviourName}");
|
||||
}
|
||||
}
|
||||
|
||||
result.Add((profile, profileTests));
|
||||
}
|
||||
catch (Exception e) {
|
||||
catch (Exception e)
|
||||
{
|
||||
// PrintError(jsonFile, e);
|
||||
throw new Exception("In the file " + jsonFile, e);
|
||||
}
|
||||
|
@ -97,55 +95,58 @@ namespace AspectedRouting
|
|||
{
|
||||
var profile = profiles["emergency_vehicle"];
|
||||
var behaviour = profile.Behaviours.Keys.First();
|
||||
do {
|
||||
do
|
||||
{
|
||||
Console.Write(profile.Name + "." + behaviour + " > ");
|
||||
var read = Console.ReadLine();
|
||||
if (read == null) {
|
||||
return; // End of stream has been reached
|
||||
}
|
||||
if (read == null) return; // End of stream has been reached
|
||||
|
||||
if (read == "") {
|
||||
if (read == "")
|
||||
{
|
||||
Console.WriteLine("looƆ sᴉ dɐWʇǝǝɹʇSuǝdO");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read.Equals("quit")) {
|
||||
return;
|
||||
}
|
||||
if (read.Equals("quit")) return;
|
||||
|
||||
if (read.Equals("help")) {
|
||||
Console.WriteLine(
|
||||
Utils.Lines(
|
||||
"select <behaviourName> to change behaviour or <vehicle.behaviourName> to change vehicle",
|
||||
Utils.Lines("select <behaviourName> to change behaviour or <vehicle.behaviourName> to change vehicle",
|
||||
""));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read.Equals("clear")) {
|
||||
if (read.Equals("clear"))
|
||||
{
|
||||
for (var i = 0; i < 80; i++) Console.WriteLine();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read.StartsWith("select")) {
|
||||
if (read.StartsWith("select"))
|
||||
{
|
||||
var beh = read.Substring("select".Length + 1).Trim();
|
||||
|
||||
if (beh.Contains(".")) {
|
||||
if (beh.Contains("."))
|
||||
{
|
||||
var profileName = beh.Split(".")[0];
|
||||
if (!profiles.TryGetValue(profileName, out var newProfile)) {
|
||||
if (!profiles.TryGetValue(profileName, out var newProfile))
|
||||
{
|
||||
Console.Error.WriteLine("Profile " + profileName + " not found, ignoring");
|
||||
continue;
|
||||
}
|
||||
|
||||
profile = newProfile;
|
||||
beh = beh.Substring(beh.IndexOf(".", StringComparison.Ordinal) + 1);
|
||||
beh = beh.Substring(beh.IndexOf(".") + 1);
|
||||
}
|
||||
|
||||
if (profile.Behaviours.ContainsKey(beh)) {
|
||||
if (profile.Behaviours.ContainsKey(beh))
|
||||
{
|
||||
behaviour = beh;
|
||||
Console.WriteLine("Switched to " + beh);
|
||||
}
|
||||
else {
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Behaviour not found. Known behaviours are:\n " +
|
||||
string.Join("\n ", profile.Behaviours.Keys));
|
||||
}
|
||||
|
@ -156,27 +157,23 @@ namespace AspectedRouting
|
|||
|
||||
var tagsRaw = read.Split(";").Select(s => s.Trim());
|
||||
var tags = new Dictionary<string, string>();
|
||||
foreach (var str in tagsRaw) {
|
||||
if (str == "") {
|
||||
continue;
|
||||
}
|
||||
foreach (var str in tagsRaw)
|
||||
{
|
||||
if (str == "") continue;
|
||||
|
||||
try {
|
||||
var strSplit = str.Split("=");
|
||||
var k = strSplit[0].Trim();
|
||||
var v = strSplit[1].Trim();
|
||||
tags[k] = v;
|
||||
}
|
||||
catch (Exception) {
|
||||
Console.Error.WriteLine("Could not parse tag: " + str);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
try
|
||||
{
|
||||
var result = profile.Run(c, behaviour, tags);
|
||||
Console.WriteLine(result);
|
||||
}
|
||||
catch (Exception e) {
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
Console.WriteLine(e.Message);
|
||||
}
|
||||
|
@ -186,7 +183,8 @@ namespace AspectedRouting
|
|||
private static void PrintError(string file, Exception exception)
|
||||
{
|
||||
var msg = exception.Message;
|
||||
while (exception.InnerException != null) {
|
||||
while (exception.InnerException != null)
|
||||
{
|
||||
exception = exception.InnerException;
|
||||
msg += "\n " + exception.Message;
|
||||
}
|
||||
|
@ -194,59 +192,37 @@ namespace AspectedRouting
|
|||
Console.WriteLine($"Error in the file {file}:\n {msg}");
|
||||
}
|
||||
|
||||
private static void PrintUsedTags(ProfileMetaData profile, Context context)
|
||||
{
|
||||
Console.WriteLine("\n\n\n---------- " + profile.Name + " --------------");
|
||||
foreach (var (key, values) in profile.AllExpressions(context).PossibleTags())
|
||||
{
|
||||
var vs = "*";
|
||||
if (values.Any()) vs = string.Join(", ", values);
|
||||
|
||||
private static int Main(string[] args)
|
||||
Console.WriteLine(key + ": " + vs);
|
||||
}
|
||||
|
||||
Console.WriteLine("\n\n\n------------------------");
|
||||
}
|
||||
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
var errMessage = MainWithError(args);
|
||||
if (errMessage == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Console.WriteLine(errMessage);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
private static void WriteOutputFiles(Context context,
|
||||
List<(AspectMetadata aspect, AspectTestSuite tests)> aspects, string outputDir,
|
||||
List<(ProfileMetaData profile, List<BehaviourTestSuite> profileTests)> profiles, bool includeTests)
|
||||
{
|
||||
foreach (var (profile, profileTests) in profiles) {
|
||||
var printer = new Printer(outputDir, profile, context, aspects, profileTests, includeTests);
|
||||
printer.PrintUsedTags();
|
||||
printer.WriteProfile1();
|
||||
printer.PrintMdInfo();
|
||||
printer.WriteAllProfile2();
|
||||
}
|
||||
|
||||
File.WriteAllText($"{outputDir}/ProfileMetadata.json",
|
||||
Utils.GenerateExplanationJson(profiles.Select(p => p.profile), context)
|
||||
);
|
||||
File.WriteAllText($"{outputDir}/UsedTags.json",
|
||||
Utils.GenerateTagsOverview(profiles.Select(p => p.profile), context)
|
||||
);
|
||||
if (errMessage != null) Console.WriteLine(errMessage);
|
||||
}
|
||||
|
||||
public static string MainWithError(string[] args)
|
||||
{
|
||||
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
|
||||
if (args.Length < 2) {
|
||||
return
|
||||
"Usage: <directory where all aspects and profiles can be found> <outputdirectory> [--include-tests]\n" +
|
||||
"The flag '--include-tests' will append some self-tests in the lua files";
|
||||
}
|
||||
if (args.Length < 2)
|
||||
return "Usage: <directory where all aspects and profiles can be found> <outputdirectory>";
|
||||
|
||||
var inputDir = args[0];
|
||||
var outputDir = args[1];
|
||||
var includeTests = args.Contains("--include-tests");
|
||||
var runRepl = !args.Contains("--no-repl");
|
||||
|
||||
if (!Directory.Exists(outputDir)) {
|
||||
Directory.CreateDirectory(outputDir);
|
||||
}
|
||||
if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir);
|
||||
|
||||
MdPrinter.GenerateHelpText(outputDir + "helpText.md");
|
||||
Console.WriteLine("Written helptext to " + outputDir);
|
||||
|
||||
|
||||
var files = Directory.EnumerateFiles(inputDir, "*.json", SearchOption.AllDirectories)
|
||||
|
@ -256,10 +232,9 @@ namespace AspectedRouting
|
|||
.ToList();
|
||||
tests.Sort();
|
||||
|
||||
foreach (var test in tests) {
|
||||
if (test.EndsWith(".test.csv") || test.EndsWith(".behaviour_test.csv")) {
|
||||
continue;
|
||||
}
|
||||
foreach (var test in tests)
|
||||
{
|
||||
if (test.EndsWith(".test.csv") || test.EndsWith(".behaviour_test.csv")) continue;
|
||||
|
||||
throw new ArgumentException(
|
||||
$"Invalid name for csv file ${test}, should end with either '.behaviour_test.csv' or '.test.csv'");
|
||||
|
@ -272,9 +247,11 @@ namespace AspectedRouting
|
|||
foreach (var (aspect, _) in aspects) context.AddFunction(aspect.Name, aspect);
|
||||
|
||||
var lastChange = DateTime.UnixEpoch;
|
||||
foreach (var file in files) {
|
||||
foreach (var file in files)
|
||||
{
|
||||
var time = new FileInfo(file).LastWriteTimeUtc;
|
||||
if (lastChange < time) {
|
||||
if (lastChange < time)
|
||||
{
|
||||
lastChange = time;
|
||||
}
|
||||
}
|
||||
|
@ -285,33 +262,58 @@ namespace AspectedRouting
|
|||
// With everything parsed and typechecked, time for tests
|
||||
var testsOk = true;
|
||||
foreach (var (aspect, t) in aspects)
|
||||
if (t == null) {
|
||||
if (t == null)
|
||||
Console.WriteLine($"[{aspect.Name}] WARNING: no tests found: please add {aspect.Name}.test.csv");
|
||||
}
|
||||
else {
|
||||
else
|
||||
testsOk &= t.Run();
|
||||
}
|
||||
|
||||
|
||||
foreach (var (profile, profileTests) in profiles)
|
||||
foreach (var test in profileTests)
|
||||
testsOk &= test.Run(context);
|
||||
|
||||
if (testsOk) {
|
||||
WriteOutputFiles(context, aspects, outputDir, profiles, includeTests);
|
||||
if (!testsOk) return "Some tests failed, quitting now without generating output";
|
||||
|
||||
foreach (var (profile, profileTests) in profiles)
|
||||
{
|
||||
PrintUsedTags(profile, context);
|
||||
|
||||
var aspectTests = aspects.Select(a => a.tests).ToList();
|
||||
var luaProfile = new LuaPrinter1(profile, context,
|
||||
aspectTests,
|
||||
profileTests
|
||||
).ToLua();
|
||||
File.WriteAllText(outputDir + "/" + profile.Name + ".lua", luaProfile);
|
||||
|
||||
foreach (var (behaviourName, _) in profile.Behaviours)
|
||||
{
|
||||
var lua2behaviour = new LuaPrinter2(
|
||||
profile,
|
||||
behaviourName,
|
||||
context,
|
||||
aspectTests,
|
||||
profileTests.Where(testsSuite => testsSuite.BehaviourName == behaviourName),
|
||||
lastChange
|
||||
).ToLua();
|
||||
if (!Directory.Exists($"{outputDir}/itinero2/"))
|
||||
Directory.CreateDirectory($"{outputDir}/itinero2/");
|
||||
File.WriteAllText(
|
||||
$"{outputDir}/itinero2/{profile.Name}.{behaviourName}.lua",
|
||||
lua2behaviour);
|
||||
}
|
||||
}
|
||||
|
||||
File.WriteAllText($"{outputDir}/ProfileMetadata.json",
|
||||
Utils.GenerateExplanationJson(profiles.Select(p => p.profile), context)
|
||||
);
|
||||
|
||||
if (runRepl) {
|
||||
if (!args.Contains("--no-repl"))
|
||||
Repl(context, profiles
|
||||
.Select(p => p.profile)
|
||||
.ToDictionary(p => p.Name, p => p));
|
||||
}
|
||||
else {
|
||||
else
|
||||
Console.WriteLine("Not starting REPL as --no-repl is specified");
|
||||
}
|
||||
|
||||
return !testsOk ? "Some tests failed, quitting now without generating output" : null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
|
@ -17,8 +16,7 @@ namespace AspectedRouting.Tests
|
|||
AspectMetadata functionToApply,
|
||||
IEnumerable<(string expected, Dictionary<string, string> tags)> tests)
|
||||
{
|
||||
if (functionToApply == null)
|
||||
{
|
||||
if (functionToApply == null) {
|
||||
throw new NullReferenceException("functionToApply is null");
|
||||
}
|
||||
|
||||
|
@ -34,10 +32,8 @@ namespace AspectedRouting.Tests
|
|||
|
||||
var tests = new List<(string, Dictionary<string, string>)>();
|
||||
|
||||
foreach (var test in all.GetRange(1, all.Count - 1))
|
||||
{
|
||||
if (string.IsNullOrEmpty(test.Trim()))
|
||||
{
|
||||
foreach (var test in all.GetRange(1, all.Count - 1)) {
|
||||
if (string.IsNullOrEmpty(test.Trim())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -45,10 +41,8 @@ namespace AspectedRouting.Tests
|
|||
var expected = testData[0];
|
||||
var vals = testData.GetRange(1, testData.Count - 1);
|
||||
var tags = new Dictionary<string, string>();
|
||||
for (var i = 0; i < keys.Count; i++)
|
||||
{
|
||||
if (i < vals.Count && !string.IsNullOrEmpty(vals[i]))
|
||||
{
|
||||
for (var i = 0; i < keys.Count; i++) {
|
||||
if (i < vals.Count && !string.IsNullOrEmpty(vals[i])) {
|
||||
tags[keys[i]] = vals[i].Trim(new []{'"'}).Replace("\"","\\\"");
|
||||
}
|
||||
}
|
||||
|
@ -66,10 +60,8 @@ namespace AspectedRouting.Tests
|
|||
public AspectTestSuite WithoutRelationTests()
|
||||
{
|
||||
var newTests = new List<(string expected, Dictionary<string, string> tags)>();
|
||||
foreach (var (expected, tags) in Tests)
|
||||
{
|
||||
if (tags.Keys.Any(key => key.StartsWith("_relation") && key.Split(":").Length == 3))
|
||||
{
|
||||
foreach (var (expected, tags) in Tests) {
|
||||
if (tags.Keys.Any(key => key.StartsWith("_relation") && key.Split(":").Length ==3)) {
|
||||
continue;
|
||||
}
|
||||
newTests.Add((expected, tags));
|
||||
|
@ -83,57 +75,46 @@ namespace AspectedRouting.Tests
|
|||
{
|
||||
var failed = false;
|
||||
var testCase = 0;
|
||||
foreach (var test in Tests)
|
||||
{
|
||||
foreach (var test in Tests) {
|
||||
testCase++;
|
||||
var context = new Context().WithAspectName("unittest");
|
||||
foreach (var (key, value) in test.tags)
|
||||
{
|
||||
if (key.StartsWith("#"))
|
||||
{
|
||||
foreach (var (key, value) in test.tags) {
|
||||
if (key.StartsWith("#")) {
|
||||
context.AddParameter(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
var actual = FunctionToApply.Evaluate(context, new Constant(test.tags));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(test.expected))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(test.expected)) {
|
||||
failed = true;
|
||||
Console.WriteLine(
|
||||
$"[{FunctionToApply.Name}] Line {testCase + 1} failed:\n The expected value is not defined or only whitespace. Do you want null? Write null in your test as expected value\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (test.expected == "null" && actual == null)
|
||||
{
|
||||
if (test.expected == "null" && actual == null) {
|
||||
// Test ok
|
||||
continue;
|
||||
}
|
||||
|
||||
if (actual == null)
|
||||
{
|
||||
if (actual == null) {
|
||||
Console.WriteLine(
|
||||
$"[{FunctionToApply.Name}] Line {testCase + 1} failed:\n Expected: {test.expected}\n actual value is not defined (null)\n tags: {test.tags.Pretty()}\n");
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
var doesMatch = (actual is double d && Math.Abs(double.Parse(test.expected, NumberStyles.Any, CultureInfo.InvariantCulture) - d) < 0.0001)
|
||||
|| actual.ToString().Equals(test.expected);
|
||||
|
||||
if (!doesMatch)
|
||||
{
|
||||
if (!actual.ToString().Equals(test.expected) &&
|
||||
!(actual is double actualD && Math.Abs(double.Parse(test.expected) - actualD) < 0.0001)
|
||||
) {
|
||||
failed = true;
|
||||
Console.WriteLine(
|
||||
$"[{FunctionToApply.Name}] Line {testCase + 1} failed:\n Expected: {test.expected}\n actual: {actual}\n tags: {test.tags.Pretty()}\n");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
catch (Exception e) {
|
||||
Console.WriteLine(
|
||||
$"[{FunctionToApply.Name}] Line {testCase + 1} ERROR:\n Expected: {test.expected}\n error message: {e.Message}\n tags: {test.tags.Pretty()}\n");
|
||||
Console.WriteLine(e);
|
||||
|
|
|
@ -20,13 +20,11 @@ namespace AspectedRouting.Tests
|
|||
|
||||
private static string str(string s)
|
||||
{
|
||||
if (s == null)
|
||||
{
|
||||
if (s == null) {
|
||||
return "<null>";
|
||||
}
|
||||
|
||||
if (s == "")
|
||||
{
|
||||
if (s == "") {
|
||||
return "<empty string>";
|
||||
}
|
||||
|
||||
|
@ -44,14 +42,5 @@ namespace AspectedRouting.Tests
|
|||
"because \n "+str(PriorityExplanation)
|
||||
);
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
if (!(obj is ProfileResult other))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return other.Access == this.Access && other.Oneway == this.Oneway && other.Priority == this.Priority && other.Speed == this.Speed;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AspectedRouting.Language;
|
||||
using AspectedRouting.Language.Expression;
|
||||
|
@ -69,13 +68,13 @@ namespace AspectedRouting.Tests
|
|||
var speed = 0.0;
|
||||
if (!string.IsNullOrEmpty(testData[2]))
|
||||
{
|
||||
speed = double.Parse(testData[2], NumberStyles.Any, CultureInfo.InvariantCulture);
|
||||
speed = double.Parse(testData[2]);
|
||||
}
|
||||
|
||||
var weight = 0.0;
|
||||
if (!string.IsNullOrEmpty(testData[3]))
|
||||
{
|
||||
weight = double.Parse(testData[3], NumberStyles.Any, CultureInfo.InvariantCulture);
|
||||
weight = double.Parse(testData[3]);
|
||||
}
|
||||
|
||||
|
||||
|
@ -140,10 +139,10 @@ namespace AspectedRouting.Tests
|
|||
|
||||
public bool RunTest(Context c, int i, ProfileResult expected, Dictionary<string, string> tags)
|
||||
{
|
||||
void Err(string message, object exp, object act, string extra = "")
|
||||
void Err(string message, object exp, object act)
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"[{Profile.Name}.{BehaviourName}]: Test on line {i + 1} failed: {message}: expected {exp} but got {act};\n{extra}\n {{{tags.Pretty()}}}");
|
||||
$"[{Profile.Name}.{BehaviourName}]: Test on line {i + 1} failed: {message}; expected {exp} but got {act}\n {{{tags.Pretty()}}}");
|
||||
}
|
||||
|
||||
var actual = Profile.Run(c, BehaviourName, tags);
|
||||
|
@ -178,19 +177,10 @@ namespace AspectedRouting.Tests
|
|||
|
||||
if (Math.Abs(actual.Priority - expected.Priority) > 0.0001)
|
||||
{
|
||||
Err($"weight incorrect",
|
||||
Err($"weight incorrect. Calculation is {string.Join(" + ", actual.PriorityExplanation)}",
|
||||
expected.Priority,
|
||||
actual.Priority,
|
||||
$"Calculation is \n{actual.PriorityExplanation}");
|
||||
success = false;
|
||||
}
|
||||
|
||||
if (actual.Priority >= 100 || actual.Priority <= -100)
|
||||
{/*
|
||||
Err($"priority is not within range of -100 and +100. This is needed due to a bug in Itinero2.0, see https://github.com/itinero/routing2/issues/30",
|
||||
actual.Priority + " < 100 && -100 < "+actual.Priority,
|
||||
actual.Priority);
|
||||
success = false;*/
|
||||
success = false;
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -31,7 +31,9 @@ namespace AspectedRouting
|
|||
public static int Multiply(this IEnumerable<int> ints)
|
||||
{
|
||||
var factor = 1;
|
||||
foreach (var i in ints) factor += i;
|
||||
foreach (var i in ints) {
|
||||
factor += i;
|
||||
}
|
||||
|
||||
return factor;
|
||||
}
|
||||
|
@ -48,34 +50,6 @@ namespace AspectedRouting
|
|||
return data.SubArray(index, data.Length - index);
|
||||
}
|
||||
|
||||
public static string Quoted(this string s)
|
||||
{
|
||||
return "\"" + s + "\"";
|
||||
}
|
||||
|
||||
public static string GenerateTagsOverview(IEnumerable<ProfileMetaData> profiles, Context context)
|
||||
{
|
||||
var allExpressions = new List<IExpression>();
|
||||
foreach (var profile in profiles)
|
||||
foreach (var behaviour in profile.Behaviours)
|
||||
allExpressions.AddRange(profile.AllExpressions(context));
|
||||
|
||||
var explanations = new List<string>();
|
||||
foreach (var tag in allExpressions.PossibleTags())
|
||||
{
|
||||
var values = new List<string>(tag.Value);
|
||||
values.Sort();
|
||||
explanations.Add(tag.Key.Quoted() + ": [" +
|
||||
string.Join(", ", values.Select(v => v.Quoted()))
|
||||
+ "]");
|
||||
}
|
||||
|
||||
explanations.Sort();
|
||||
|
||||
|
||||
return "{\n " + string.Join(",\n ", explanations) + "\n}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a JSON file where all the profiles are listed, together with descriptions and other metadata.
|
||||
/// Useful for other apps, e.g. the routing api to have
|
||||
|
@ -88,65 +62,32 @@ namespace AspectedRouting
|
|||
{
|
||||
var metaItems = new List<string>();
|
||||
|
||||
foreach (var profile in profiles)
|
||||
{
|
||||
foreach (var profile in profiles) {
|
||||
var profileName = profile.Name;
|
||||
var author = profile.Author;
|
||||
var profileDescription = profile.Description;
|
||||
|
||||
|
||||
foreach (var behaviour in profile.Behaviours)
|
||||
{
|
||||
foreach (var behaviour in profile.Behaviours) {
|
||||
var behaviourDescription = behaviour.Value["description"].Evaluate(new Context()) as string;
|
||||
behaviourDescription ??= "";
|
||||
var keys = new List<string>();
|
||||
foreach (var tag in profile.AllExpressions(context).PossibleTags()) keys.Add(tag.Key.Quoted());
|
||||
|
||||
var meta = new Dictionary<string, string>
|
||||
{
|
||||
var keys = string.Join(", ",
|
||||
profile.AllExpressions(context).PossibleTags().Select(tag => $"\"{tag.Key}\"")
|
||||
);
|
||||
var meta = new Dictionary<string, string> {
|
||||
{"name", behaviour.Key},
|
||||
{"type", profileName},
|
||||
{"author", author},
|
||||
{"description", behaviourDescription + " (" + profileDescription + ")"}
|
||||
};
|
||||
|
||||
var json = string.Join(",", meta.Select(d =>
|
||||
$"\"{d.Key}\": \"{d.Value}\""));
|
||||
|
||||
metaItems.Add($"{{{json}, " +
|
||||
$"\"usedKeys\": [{string.Join(", ", keys)}] }}\n");
|
||||
metaItems.Add("{" + json + ", \"usedKeys\": [" + keys + "] }\n");
|
||||
}
|
||||
}
|
||||
|
||||
return "[" + string.Join(",\n", metaItems) + "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an object, converts it to a double.
|
||||
* throws an exception if not a double
|
||||
*/
|
||||
public static double AsDouble(object obj, string paramName)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
throw new Exception($"Invalid value as result for {paramName}: got null");
|
||||
}
|
||||
switch (obj)
|
||||
{
|
||||
case bool b:
|
||||
return b ? 1.0 : 0.0;
|
||||
case double d:
|
||||
return d;
|
||||
case int j:
|
||||
return j;
|
||||
case string s:
|
||||
if (s.Equals("yes")) return 1.0;
|
||||
|
||||
if (s.Equals("no")) return 0.0;
|
||||
|
||||
throw new Exception($"Invalid value as result for {paramName}: got string {s}");
|
||||
default:
|
||||
throw new Exception($"Invalid value as result for {paramName}: got object {obj}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -33,7 +33,7 @@ To call a function in an aspect, one creates a hash in the JSON where exactly on
|
|||
}
|
||||
```
|
||||
|
||||
Interpreting the above expression will aways yield `no` when evaluating, as the parameters have different values. The type of the above expression is thus `Bool`.
|
||||
Interpreting the above expression will always yield `no` when evaluating, as the parameters have different values. The type of the above expression is thus `Bool`.
|
||||
|
||||
If no key has a function invocation (thus no key starts with `$`), the hash is interpreted as a mapping:
|
||||
|
||||
|
|
|
@ -1,53 +1,3 @@
|
|||
# Building a profile
|
||||
|
||||
A profile is a .json-file, which consists of a few metadatafields (which are simple strings),
|
||||
some expressions to calculate values based on tags, a list of parameters with their default values and
|
||||
a list of profiles containing the actual parameter value for that profile.
|
||||
|
||||
|
||||
# Vehicle.json
|
||||
|
||||
- Metadata: these tags will be copied to the routerdb, but can not be used for routeplanning. A prime example is `name` (the streetname), as it is useful for routeplanning but very useful for navigation afterwards
|
||||
- vehicletypes: used for turn restrictions, legacy for use with itinero 1.0
|
||||
- defaults: a dictionary of `{"#paramName": "value"}`, used in determining the weight of an edge. note: the `#` has to be included
|
||||
- `access` is a field in the vehicle file. It should be an expression returning a string. If (and only if) this string is `no`, the way will be marked as not accessible and no more values will be calculated. All other values are regarded as being accessible. When calculated, the tag `access` with the calculated value is written into the tag table for the other aspects to use.
|
||||
- `oneway` is a field in the vehicle file. It should be an expression returning `both`, `with` or `against`.
|
||||
When calculated, the tag `oneway` is added to the tags for the other aspects to be calculated.
|
||||
- `speed`: an expression indicating how fast the vehicle can go there. It should take into account legal, practical and social aspects. An example expression could be `{"$min", ["$legal_maxspeed", "#defaultspeed"]}`
|
||||
- `obstacleaccess` and `obstaclecost` are two (optional) expressions that calculate whether an obstacle can be passed and if so, if there is a penalty for this. See detailed explanations below
|
||||
|
||||
- `priorities`: a table of `{'#paramName', expression}` determining the priority (1/cost) of a way, per meter. The formula used is `paramName * expression + paramName0 * expression0 + ...` (`speed`, `access` and `oneway` can be used here as tags indicate the earlier defined respective aspects). Use a weight == 1 to get the shortest route or `$speed` to get the fastest route
|
||||
- `scalingfactor` works in tandem with priority. The _total_ resistance of a link is `priority * scalingfactor`. If this function returns `null`, this will be defaulted to 1.
|
||||
|
||||
|
||||
# Calculating oneway and forward/backward speeds
|
||||
|
||||
There are two possibilities in order to calculate the possible direction of a traveller can go over an edge:
|
||||
|
||||
1) This can be indicated explicitely with the 'oneway'-field. If this expression returns `both`, the edge is traversable in two directions. If it is either `with` or `against`, then it is not
|
||||
2) This can be indicated with having a speed or factor which is equal to (or smaller then) 0, in conjunction with a `_direction=with` or `_direction=against` tag. Bicycle lanes are an excellent example for this: a `cycleway:right=yes; cycleway:left=no`, the speed and factor for `_direction=with` could be far greater then for `_direction=against`
|
||||
|
||||
Note that `_direction=with` and `_direction=against` are _not_ supported in Itinero1.0 profiles. For maximal compatibility and programming comfort, a mixture of both techniques should be used. For example, one aspect interpreting the legal onewayness in tandem with one aspect determining comfort by direction is optimal.
|
||||
|
||||
# Obstacle costs
|
||||
|
||||
(Note: this only works with itinero2.0)
|
||||
|
||||
Obstacles are objects which are encountered on nodes, e.g. bollards, traffic lights but also turn restrictions.
|
||||
|
||||
The first property for this is `obstacleaccess` which calculates wether or not a vehicle can pass the obstacle.
|
||||
The possible values are:
|
||||
|
||||
- "no" of "false": the current vehicle _cannot_ pass this obstacle and should take a different route
|
||||
- "yes", "true", `null` or any other value: the current vehicle _can_ pass this obstacle. The turn cost will be calculated
|
||||
|
||||
If `obstacleaccess` is not `no` or `false`, then `obstaclecost` will be triggered. This possible return values are:
|
||||
|
||||
- a positive number, indicating the cost for passing this obstacle
|
||||
- 0: there is no cost to cross this obstacle
|
||||
- null: this profile has no knowledge of a cost. Use the default implementation to check for turn restrictions
|
||||
|
||||
If the resulting cost is null, the default implementation will be used.
|
||||
|
||||
# Functions
|
||||
|
||||
|
@ -64,11 +14,27 @@ Aspects can use the following (extra) tags:
|
|||
- `access` will become the value calculated in the field `access` (not available to calculate access)
|
||||
- `oneway` will become the value calculated in the field `oneway` (not available to calculate access and speed)
|
||||
|
||||
## Why is `access`, `oneway` and `speed` copied onto the tags?
|
||||
|
||||
`speed` is copied in order for the profile to be able to make a `fast` profile (and accessible as `$speed`).
|
||||
Access is copied so that `highway=cycleway` and `highway=cycleway;bicycle=designated` will render the same result.
|
||||
# Vehicle.json
|
||||
|
||||
- Metdata: these tags will be copied to the routerdb, but can not be used for routeplanning. A prime example is `name` (the streetname), as it is useful for routeplanning but very useful for navigation afterwards
|
||||
- vehicletypes: used for turn restrictions, legacy for use with itinero 1.0
|
||||
- defaults: a dictionary of `{"#paramName": "value"}`, used in determining the weight of an edge. note: the `#` has to be included
|
||||
- `access` is a field in the vehicle file. It should be an expression returning a string. If (and only if) this string is `no`, the way will be marked as not accessible and no more values will be calculated. All other values are regarded as being accessible. When calculated, the tag `access` with the calculated value is written into the tag table or the other aspects to use.
|
||||
- `oneway` is a field in the vehicle file. It should be an expression returning `both`, `with` or `against`.
|
||||
When calculated, the tag `oneway` is added to the tags for the other aspects to be calculated.
|
||||
- `speed`: an expression indicating how fast the vehicle can go there. It should take into account legal, practical and social aspects. An example expression could be `{"$min", ["$legal_maxspeed", "#defaultspeed"]}`
|
||||
|
||||
- `priorities`: a table of `{'#paramName', expression}` determining the priority (1/cost) of a way, per meter. The formula used is `paramName * expression + paramName0 * expression0 + ...` (`speed`, `access` and `oneway` can be used here as tags indicate the earlier defined respective aspects). Use a weight == 1 to get the shortest route or `$speed` to get the fastest route
|
||||
|
||||
# Calculating oneway and forward/backward speeds
|
||||
|
||||
There are two possibilities in order to calculate the possible direction of a traveller can go over an edge:
|
||||
|
||||
1) This can be indicated explicitely with the 'oneway'-field. If this expression returns `both`, the edge is traversable in two directions. If it is either `with` or `against`, then it is not
|
||||
2) This can be indicated with having a speed or factor which is equal to (or smaller then) 0, in conjunction with a `_direction=with` or `_direction=against` tag. Bicycle lanes are an excellent example for this: a `cycleway:right=yes; cycleway:left=no`, the speed and factor for `_direction=with` could be far greater then for `_direction=against`
|
||||
|
||||
Note that `_direction=with` and `_direction=against` are _not_ supported in Itinero1.0 profiles. For maximal compatibility and programming comfort, a mixture of both techniques should be used. For example, one aspect interpreting the legal onewayness in tandem with one aspect determining comfort by direction is optimal.
|
||||
|
||||
|
||||
# Pitfalls
|
3
javascript/.babelrc
Normal file
3
javascript/.babelrc
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"presets": ["@babel/preset-env"]
|
||||
}
|
17
javascript/.npmignore
Normal file
17
javascript/.npmignore
Normal file
|
@ -0,0 +1,17 @@
|
|||
# Node modules
|
||||
node_modules
|
||||
npm_debug.log
|
||||
|
||||
# Git
|
||||
.git
|
||||
|
||||
# Apple
|
||||
.DS_Store
|
||||
|
||||
|
||||
# Route Examples
|
||||
.routeExamples
|
||||
.tagExamples
|
||||
|
||||
# Visual Studio Code
|
||||
.vscode
|
38
javascript/.tagExamples/example.js
Normal file
38
javascript/.tagExamples/example.js
Normal file
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
* Example tags
|
||||
*/
|
||||
const tags1 = {
|
||||
"highway": "residential", // 1 // Expect "yes"
|
||||
"surface": "paved", // 0.99
|
||||
}
|
||||
|
||||
const tags2 = {
|
||||
"bicycle": "yes", // Expect "yes"
|
||||
"cycleway": "lane",
|
||||
"highway": "secondary",
|
||||
"maxspeed": "50",
|
||||
}
|
||||
|
||||
const tags3 = {
|
||||
"cyclestreet": "yes",
|
||||
"highway": "residential", // Expect "yes"
|
||||
"maxspeed": "30",
|
||||
"surface": "asphalt"
|
||||
}
|
||||
|
||||
const tags4 = {
|
||||
"highway": "track", // Expect "yes"
|
||||
"surface": "asphalt",
|
||||
"incline": "10%"
|
||||
}
|
||||
|
||||
const tags5 = {
|
||||
"access": "no", // Expect "no"
|
||||
"bicycle": "official",
|
||||
"area": "yes"
|
||||
}
|
||||
|
||||
const tags6 = {
|
||||
"surface":"dirt",
|
||||
"highway":"track",
|
||||
}
|
220
javascript/BuildingAProfile.md
Normal file
220
javascript/BuildingAProfile.md
Normal file
|
@ -0,0 +1,220 @@
|
|||
# Building a routeplanner
|
||||
|
||||
This document was originally written as blog post. It gives a practical, example first example to build a custom route planner.
|
||||
|
||||
In order to deploy:
|
||||
|
||||
- Build your profile by creating the relevant `.json`-files in a directory; take a peek at `Examples`
|
||||
- Run the project: `cd AspectedRouting && dotnet run <inputdir> <outputdir>` (make sure the outputDirectory is _not_ a subdirectory of the input directory)
|
||||
- In outputDir, you will find a bunch of lua-scripts which can be used with itinero
|
||||
|
||||
## A step by step example for an aspect
|
||||
|
||||
Let us recreate (a small part) of the legal access aspect for cyclists. The file will answer the question: __can a bicycle enter this road?__
|
||||
|
||||
First, we start with some metadata:
|
||||
|
||||
```
|
||||
"name": "bicycle.legal_access",
|
||||
"description": "Can a bicycle enter this road segment?",
|
||||
"unit": "Yes, No",
|
||||
```
|
||||
|
||||
The `name` field is an important one, as the aspect can be called with it in other files. The `description` and `unit`-fields however are purely as documentation - but are nonetheless important. Writing down exactly what an aspect means helps to clarify what is calculated before coding it and makes life easier down the road.
|
||||
|
||||
### Building the access-function
|
||||
|
||||
To call a function in an aspect, one creates a hash in the JSON where exactly one key starts with a `$`. The rest of the key determines which function is called, the value of the key is its first argument whereas the other keys in the hash function as other parameters. One could for example check that two values are the same with:
|
||||
|
||||
```
|
||||
{
|
||||
"$eq": "someValue",
|
||||
"b": "otherValue"
|
||||
}
|
||||
```
|
||||
|
||||
Interpreting the above expression will aways yield `no` when evaluating, as the parameters have different values. The type of the above expression is thus `Bool`.
|
||||
|
||||
If no key has a function invocation (thus no key starts with `$`), the hash is interpreted as a mapping:
|
||||
|
||||
```
|
||||
{
|
||||
"yes": "yes"
|
||||
"no": "no"
|
||||
"customers": "no"
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The above expression is a function of type `string -> double`. If invoked, it will convert `yes` into the value `yes` and `customers` into the value `no`. Any string not in the mapping will result in `null`.
|
||||
|
||||
|
||||
Every expression in AspectedRouting is implicitly yet strongly typed at compile time. Having types around is cool and good for correctness, but can be constraining and the cause of boilerplate. Therefore, expressions are allowed to have _multiple_ types. Due to the context of how it is called and what the parameters of functions are, the compiler can determine exaclty which type is meant.
|
||||
|
||||
For example, a mapping like above can also be used to match OSM-keys:
|
||||
|
||||
```
|
||||
{
|
||||
"access": {
|
||||
"yes": "no",
|
||||
"no": "no",
|
||||
"customers":"no"
|
||||
},
|
||||
"bicycle": "$id",
|
||||
"construction": "no"
|
||||
}
|
||||
```
|
||||
|
||||
There is a lot to unpack here. A mapping as above is either a function taking a `string` and returning a value, or it is a function taking a `Tags`-collection and returning a collection of calculated values.
|
||||
|
||||
For example, passing in the collection `access=customers` in the above function will result into the value `["no"]`. Passing `access=dismount;bicycle=yes` will result in `[null, "yes"]` - the value corresponding with `access` is passed into the mapping `{"yes":"yes", "customers":"no", ...}` where no match is found resulting in `null`. The value for `bicycle` is passed into the `$id` function which simply passes back its argument.
|
||||
|
||||
At last, there is the cryptical `"construction":"no"`. This expression indicates that if a construction-tag is present, the resulting value should always be `no`. But how does it work exactly? When writing a constant (such as `"no"`) in an Aspected-Routing file, it is interpreted as either being the literal constant _or_ as being a function which ignores the parameter! `"no"` has thus the types `string` and `a -> string`. When used in a single mapping with type `string -> string` it is clear the first one is meant, when used in a tagsmapping with type `Tags -> string` (e.g. `{"key": "f"}`, the type of the function `f` should be `string -> b`, clearly indicating that `"no"` should be interpreted as the function which ignores the parameter. If this sounds like magic to you - don't worry about it too much. In practice, you just type what feels logical and it'll work out.
|
||||
|
||||
#### Combining multiple tags
|
||||
|
||||
The above aspect is already pretty close to a working access-calculation for cyclists - but we still have a collection of values, not a single one. We have a clear order in which we want to evaluate the tags. This too can be done with a builtin function, namely `$firstMatchOf` with the type `[string] -> (Tags -> [a]) -> (Tags -> a)`. For those not familiar with this notation for the types, this reads as: given a list of `string` and a function (which converts tags into a list of `a`), I'll give back a function that converts `Tags` into some `a`
|
||||
|
||||
It is used in the following way:
|
||||
|
||||
```
|
||||
{
|
||||
"$firstMatchOf":["bicycle", "construction", "access"],
|
||||
"f": { ... above code ... }
|
||||
}
|
||||
```
|
||||
|
||||
At last, what if _none_ of the tags match? What do we do then? For that, there is `$default: a -> (x -> a) -> (x -> a)`. More comprehensively, this function needs a (default) value `a`, and a function calculating some `a` based on `x` and it'll give back a function that calculates an `a` based on an `x`.
|
||||
|
||||
Here too is an example clearer then trying to explain it:
|
||||
|
||||
```
|
||||
{
|
||||
"$default": "no",
|
||||
"f": { ... above code ... }
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### Combining everything
|
||||
|
||||
Everything together, this gives a very basic implementation of where a cyclists can cycle! If we throw it all together, we get the following JSON file:
|
||||
|
||||
|
||||
```
|
||||
{
|
||||
|
||||
"name": "bicycle.legal_access",
|
||||
"description": "Gives, for each type of highway, whether or not a normal bicycle can enter legally.\nNote that legal access is a bit 'grey' in the case of roads marked private and permissive, in which case these values are returned ",
|
||||
"unit": "yes, no",
|
||||
|
||||
|
||||
"$default": "no",
|
||||
"f": {
|
||||
"$firstMatchOf": ["bicycle", "construction", "access"],
|
||||
"f": {
|
||||
"access": {
|
||||
"yes": "no",
|
||||
"no": "no",
|
||||
"customers":"no"
|
||||
},
|
||||
"bicycle": "$id",
|
||||
"construction": "no"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
It should be noted that the _actual_ implementation is more complicated then that. There are more tags to keep track of, but the above explanation should be enough to get a grasp of [legal-access-aspect for bicycles](https://github.com/pietervdvn/AspectedRouting/blob/master/Examples/bicycle/aspects/bicycle.legal_access.json). An overview of all the functions and available types, have a look [here](https://github.com/pietervdvn/AspectedRouting/blob/master/Examples/TypesAndFunctions.md)
|
||||
|
||||
### Building a profile
|
||||
|
||||
Having accessibility alone isn't enough to create a route planner for cyclists. In a similar way, one can create an aspect that defines [if the street is a oneway](https://github.com/pietervdvn/AspectedRouting/blob/master/Examples/bicycle/aspects/bicycle.oneway.json) or how [comfortable a street is](https://github.com/pietervdvn/AspectedRouting/blob/master/Examples/bicycle/aspects/bicycle.comfort.json). (Please note that the linked examples are stripped down examples. Our actual routeplanner has a few more aspect files and more tags).
|
||||
|
||||
At last, we have to combine those aspects into something that actually creates the profile. This is done by another JSON-file, such as [this one](https://github.com/pietervdvn/AspectedRouting/blob/master/Examples/bicycle/bicycle.json). Lets break it down:
|
||||
|
||||
```
|
||||
{
|
||||
"name": "bicycle",
|
||||
"description": "Profile for a normal bicycle",
|
||||
```
|
||||
|
||||
This is some metadata, mostly meant for humans.
|
||||
|
||||
```
|
||||
|
||||
"defaults": {
|
||||
"#maxspeed": 20,
|
||||
"#timeNeeded": 0,
|
||||
"#comfort": 0,
|
||||
"#distance": 0,
|
||||
},
|
||||
```
|
||||
|
||||
This declares some variables, which can only be used in the scope of the profile. Variables always start with `#` and are either a `number`, a `boolean` or a `string`. They are used to below the actual aspects of the profile:
|
||||
|
||||
```
|
||||
"access": "$bicycle.legal_access",
|
||||
```
|
||||
This states when a segment is accessible. It expects a function `Tags -> string` and a segment is considered not accessible if this value is `"no"`; it is accessible otherwise.
|
||||
|
||||
```
|
||||
"oneway": "$bicycle.oneway",
|
||||
```
|
||||
This indicates if the street is a oneway, it expects a function `Tags -> string` where the resulting value is one of `both`,`with` or `against`
|
||||
|
||||
|
||||
```
|
||||
"speed": {
|
||||
"$min": [
|
||||
"#defaultSpeed",
|
||||
"$legal_maxspeed_be"
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
This states how fast a bicycle would be going on the segment; it expects a function `Tags -> number`. It is the first interesting case: both the variable `#maxspeed` (defined in `defaults`) is used, together with a function calculating the _legal_ max speed for a road segment. The lowest of the two is taken, by the function `$min`
|
||||
|
||||
```
|
||||
"behaviours": {
|
||||
"fastest": {
|
||||
"description": "The fastest route to your destination",
|
||||
"#timeNeeded": 1,
|
||||
},
|
||||
"shortest": {
|
||||
"description": "The shortest route, independent of of speed",
|
||||
"#distance": 1,
|
||||
},
|
||||
"comfort": {
|
||||
"description": "A comfortable route preferring well-paved roads, smaller roads and a bit of scenery at the cost of speed",
|
||||
"#comfort": 1
|
||||
},
|
||||
"electric":{
|
||||
"description": "An electrical bicycle",
|
||||
"#maxspeed": 25,
|
||||
"#comfort":1,
|
||||
"#timeNeeded": 5
|
||||
},
|
||||
"electric_fastest":{
|
||||
"description": "An electrical bicycle, focussed on speed",
|
||||
"#maxspeed": 25,
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
The above code defines _behaviours_ of the cyclist. It allows to overwrite a variable which influences the routeplanning. For example, the behavour `electrical` above will overwrite the maxspeed, changing the `speed`-aspect at the top of the file. However, these variables are most important in the priority below:
|
||||
|
||||
```
|
||||
"priority": {
|
||||
"#comfort": "$bicycle.comfort",
|
||||
"#timeNeeded": "$speed",
|
||||
"#distance": "$distance",
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The priority is the core of the customizibility and calculates the priority of the segment. First, the function on the right is calculated with the tags of the segment - e.g. for a segment with tags `highway=residential;surface=sett;` this will yield `{"#comfort": 0.9, "#timeNeeded": 25, "#distance": 1}`.
|
||||
|
||||
These values are multiplied with the variables and summed, giving the _priority_ of the segment - where the variable are set by the requested profile; e.g. for `electrical` this will yield `(#comfort = 1) * 0.9 + (#timeNeeded = 5) * 25 + (#distance = 0) * 1`, giving the priority of `125.9`. The _cost_ per meter is then the inverted value, thus `1 / 125.9` or approximately `0.008/m`. This cost seems relatively low - but that doesn't matter as all costs are in the same range.
|
23
javascript/README.md
Normal file
23
javascript/README.md
Normal file
|
@ -0,0 +1,23 @@
|
|||
# StressMap interpreter
|
||||
CLI program that generates a stress score based on a RuleSet JSON file and a tag object.
|
||||
|
||||
## Installation
|
||||
`npm i mapcomplete-stressmap`
|
||||
|
||||
## How to use
|
||||
This program can be used from the command line interface:
|
||||
`node mapcomplete-stressmap [ruleset.json] [tags object]`
|
||||
|
||||
Example tags:
|
||||
```json
|
||||
{
|
||||
"cyclestreet": "yes",
|
||||
"highway": "residential", // Expect "yes"
|
||||
"maxspeed": "30",
|
||||
"surface": "asphalt"
|
||||
}
|
||||
```
|
||||
|
||||
Guidelines on JSON Ruleset (from [AspectedRouting](https://www.github.com/pietervdvn/AspectedRouting.git))
|
||||
|
||||
[Building a Profile](./BuildingAProfile.md)
|
191
javascript/RuleSet.js
Normal file
191
javascript/RuleSet.js
Normal file
|
@ -0,0 +1,191 @@
|
|||
/**
|
||||
* RuleSet Class
|
||||
* Constructor
|
||||
* @param name {string} Name of RuleSet
|
||||
* @param defaultValue {number} Default score value
|
||||
* @param values {object} Main data object
|
||||
*/
|
||||
class RuleSet {
|
||||
constructor(config) {
|
||||
delete config["name"]
|
||||
delete config["unit"]
|
||||
delete config["description"]
|
||||
this.program = config
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* getScore calculates a score for the RuleSet
|
||||
* @param tags {object} Active tags to compare against
|
||||
*/
|
||||
runProgram(tags, program = this.program) {
|
||||
if (typeof program !== "object") {
|
||||
return program;
|
||||
}
|
||||
|
||||
let functionName /*: string*/ = undefined;
|
||||
let functionArguments /*: any */ = undefined
|
||||
let otherValues = {}
|
||||
Object.entries(program).forEach(
|
||||
entry => {
|
||||
const [key, value] = entry
|
||||
if (key.startsWith("$")) {
|
||||
functionName = key
|
||||
functionArguments = value
|
||||
} else {
|
||||
otherValues[key] = value
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (functionName === undefined) {
|
||||
return this.interpretAsDictionary(program, tags)
|
||||
}
|
||||
|
||||
if (functionName === '$multiply') {
|
||||
return this.multiplyScore(tags, functionArguments);
|
||||
} else if (functionName === '$firstMatchOf') {
|
||||
this.order = keys;
|
||||
return this.getFirstMatchScore(tags);
|
||||
} else if (functionName === '$min') {
|
||||
return this.getMinValue(tags, functionArguments);
|
||||
} else if (functionName === '$max') {
|
||||
return this.getMaxValue(tags, functionArguments);
|
||||
} else if (functionName === '$default') {
|
||||
return this.defaultV(functionArguments, otherValues, tags)
|
||||
} else {
|
||||
console.error(`Error: Program ${functionName} is not implemented yet. ${JSON.stringify(program)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a 'program' without function invocation, interprets it as a dictionary
|
||||
*
|
||||
* E.g., given the program
|
||||
*
|
||||
* {
|
||||
* highway: {
|
||||
* residential: 30,
|
||||
* living_street: 20
|
||||
* },
|
||||
* surface: {
|
||||
* sett : 0.9
|
||||
* }
|
||||
*
|
||||
* }
|
||||
*
|
||||
* in combination with the tags {highway: residential},
|
||||
*
|
||||
* the result should be [30, undefined];
|
||||
*
|
||||
* For the tags {highway: residential, surface: sett} we should get [30, 0.9]
|
||||
*
|
||||
*
|
||||
* @param program
|
||||
* @param tags
|
||||
* @return {(undefined|*)[]}
|
||||
*/
|
||||
interpretAsDictionary(program, tags) {
|
||||
return Object.entries(tags).map(tag => {
|
||||
const [key, value] = tag;
|
||||
const propertyValue = program[key]
|
||||
if (propertyValue === undefined) {
|
||||
return undefined
|
||||
}
|
||||
if (typeof propertyValue !== "object") {
|
||||
return propertyValue
|
||||
}
|
||||
return propertyValue[value]
|
||||
});
|
||||
}
|
||||
|
||||
defaultV(subProgram, otherArgs, tags) {
|
||||
const normalProgram = Object.entries(otherArgs)[0][1]
|
||||
const value = this.runProgram(tags, normalProgram)
|
||||
if (value !== undefined) {
|
||||
return value;
|
||||
}
|
||||
return this.runProgram(tags, subProgram)
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies the default score with the proper values
|
||||
* @param tags {object} the active tags to check against
|
||||
* @param subprogram which should generate a list of values
|
||||
* @returns score after multiplication
|
||||
*/
|
||||
multiplyScore(tags, subprogram) {
|
||||
let number = 1
|
||||
this.runProgram(tags, subprogram).filter(r => r !== undefined).forEach(r => number *= parseFloat(r))
|
||||
return number.toFixed(2);
|
||||
}
|
||||
|
||||
getFirstMatchScore(tags) {
|
||||
let matchFound = false;
|
||||
let match = "";
|
||||
let i = 0;
|
||||
|
||||
for (let key of this.order) {
|
||||
i++;
|
||||
for (let entry of Object.entries(JSON.parse(tags))) {
|
||||
const [tagKey, tagValue] = entry;
|
||||
|
||||
if (key === tagKey) {
|
||||
const valueReply = this.checkValues(entry);
|
||||
|
||||
if (!!valueReply) {
|
||||
match = valueReply;
|
||||
matchFound = true;
|
||||
return match;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchFound) {
|
||||
match = this.defaultValue;
|
||||
return match;
|
||||
}
|
||||
}
|
||||
|
||||
checkValues(tag) {
|
||||
const [tagKey, tagValue] = tag;
|
||||
const options = Object.entries(this.scoreValues[1])
|
||||
|
||||
for (let option of options) {
|
||||
const [optKey, optValues] = option;
|
||||
|
||||
if (optKey === tagKey) {
|
||||
return optValues[`${tagValue}`];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
getMinValue(tags, subprogram) {
|
||||
console.log("Running min with", tags, subprogram)
|
||||
const minArr = subprogram.map(part => {
|
||||
if (typeof (part) === 'object') {
|
||||
const calculatedValue = this.runProgram(tags, part)
|
||||
return parseFloat(calculatedValue)
|
||||
} else {
|
||||
return parseFloat(part);
|
||||
}
|
||||
}).filter(v => !isNaN(v));
|
||||
return Math.min(...minArr);
|
||||
}
|
||||
|
||||
getMaxValue(tags, subprogram) {
|
||||
const maxArr = subprogram.map(part => {
|
||||
if (typeof (part) === 'object') {
|
||||
return parseFloat(this.runProgram(tags, part))
|
||||
} else {
|
||||
return parseFloat(part);
|
||||
}
|
||||
}).filter(v => !isNaN(v));
|
||||
return Math.max(...maxArr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export default RuleSet;
|
68
javascript/__tests__/ruleSetTests.js
Normal file
68
javascript/__tests__/ruleSetTests.js
Normal file
|
@ -0,0 +1,68 @@
|
|||
import { expect, jest } from '@jest/globals';
|
||||
import RuleSet from '../RuleSet.js';
|
||||
|
||||
describe('RuleSet', () => {
|
||||
const exampleJSON = {
|
||||
"name": "real.name",
|
||||
"$default": "1",
|
||||
"value": {
|
||||
"$multiply": {
|
||||
"example": {
|
||||
"score": "1.2"
|
||||
},
|
||||
"other": {
|
||||
"thing": "1",
|
||||
"something": "1.2",
|
||||
"other_thing": "1.4"
|
||||
}
|
||||
},
|
||||
"$firstMatchOf": [
|
||||
"area",
|
||||
"empty",
|
||||
"things"
|
||||
],
|
||||
"value": {
|
||||
"area": {
|
||||
"yes": "no"
|
||||
},
|
||||
"access:": {
|
||||
"no": "no",
|
||||
"customers": "private"
|
||||
},
|
||||
"$multiply": {
|
||||
"access": {
|
||||
"dismount": 0.15
|
||||
},
|
||||
"highway": {
|
||||
"path": 0.5
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
}
|
||||
};
|
||||
const tags = {
|
||||
"example": "score",
|
||||
"other": "something",
|
||||
"highway": "track",
|
||||
"surface": "sett",
|
||||
"cycleway": "lane"
|
||||
}
|
||||
test('it should resolve', () => {
|
||||
const ruleSet = exampleJSON;
|
||||
const { name, $default, $multiply, value} = ruleSet;
|
||||
|
||||
if (!!value) {
|
||||
const currentSet = new RuleSet(name, $default, value);
|
||||
currentSet.runProgram(tags);
|
||||
expect(currentSet.runProgram).resolves;
|
||||
expect(currentSet.toString).resolves;
|
||||
} else {
|
||||
const currentSet = new RuleSet(name, $default, {$multiply});
|
||||
currentSet.toString();
|
||||
currentSet.runProgram(tags);
|
||||
}
|
||||
|
||||
})
|
||||
})
|
7
javascript/index.js
Normal file
7
javascript/index.js
Normal file
|
@ -0,0 +1,7 @@
|
|||
import interpret from './interpret.js';
|
||||
import RuleSet from './RuleSet.js';
|
||||
|
||||
export {
|
||||
interpret,
|
||||
RuleSet
|
||||
};
|
37
javascript/interpret.js
Normal file
37
javascript/interpret.js
Normal file
|
@ -0,0 +1,37 @@
|
|||
/**
|
||||
* Import packages
|
||||
*/
|
||||
import fs from 'fs';
|
||||
import {argv} from 'process';
|
||||
import RuleSet from './RuleSet.js';
|
||||
|
||||
const app = {
|
||||
init() {
|
||||
if (!!argv && argv.length < 4) {
|
||||
console.info(`Invalid command. In order to run the JavaScript interpreter please use the following format:
|
||||
> node index.js [ruleset JSON file] [tags]`)
|
||||
} else if (!!argv && argv.length === 4) {
|
||||
const definitionFile = argv[2];
|
||||
const tags = argv[3];
|
||||
const result = this.interpret(definitionFile, tags);
|
||||
console.log(result)
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Interpret JsonFile and apply it as a tag. To use with CLI only
|
||||
* @param definitionFile {any} JSON input defining the score distribution
|
||||
* @param tags {any} OSM tags as key/value pairs
|
||||
*/
|
||||
interpret(definitionFile, tags) {
|
||||
if (typeof tags === "string") {
|
||||
tags = JSON.parse(tags)
|
||||
}
|
||||
const rawData = fs.readFileSync(definitionFile);
|
||||
const program = JSON.parse(rawData);
|
||||
return new RuleSet(program).runProgram(tags)
|
||||
}
|
||||
};
|
||||
|
||||
app.init();
|
||||
|
||||
export default app;
|
9616
javascript/package-lock.json
generated
Normal file
9616
javascript/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
26
javascript/package.json
Normal file
26
javascript/package.json
Normal file
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"name": "aspected-routing",
|
||||
"version": "0.2.0",
|
||||
"description": "Calculates a score based on a .Json-file which contains an Aspected-Routing function. This is a (partial) javascript port",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
},
|
||||
"jest": {
|
||||
"transform": {
|
||||
"^.+\\.jsx?$": "babel-jest"
|
||||
}
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "Charlotte Delvaux",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.14.7",
|
||||
"@types/jest": "^26.0.24",
|
||||
"@types/node": "^16.3.1",
|
||||
"babel-jest": "^27.0.6",
|
||||
"jest": "^27.0.6",
|
||||
"ts-node": "^10.1.0"
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue