value is a function while a set was expected while evaluating 'outputs' - nix

I'm getting the above error when attempting to check a flake; I'm trying to use flake-compat on a non-NixOS system for compatibility with home-manager.
This is the flake that's causing the trace below:
error: value is a function while a set was expected
at /nix/store/l22dazwy8cgxdvndhq45br310nap92x3-source/etc/nixos/flake.nix:167:136:
166|
167| outputs = inputs#{ self, nix, nixpkgs, flake-utils, flake-compat, ... }: with builtins; with nixpkgs.lib; with flake-utils.lib; let
|
^
168|
… while evaluating 'outputs'
at /nix/store/l22dazwy8cgxdvndhq45br310nap92x3-source/etc/nixos/flake.nix:167:15:
166|
167| outputs = inputs#{ self, nix, nixpkgs, flake-utils, flake-compat, ... }: with builtins; with nixpkgs.lib; with flake-utils.lib; let
| ^
168|
… from call site
at «string»:45:21:
44|
45| outputs = flake.outputs (inputs // { self = result; });
| ^
46|
… while evaluating anonymous lambda
at «string»:10:13:
9| builtins.mapAttrs
10| (key: node:
| ^
11| let
… from call site
… while evaluating the attribute 'root'
… while evaluating anonymous lambda
at «string»:2:23:
1|
2| lockFileStr: rootSrc: rootSubdir:
| ^
3|
… from call site
Unfortunately, I cannot provide a minimal reproducible example as I do not know from where in the flake this error is originating.

Turns out, my lib value was actually a function; unfortunately, since nix flakes is still unstable, it didn't quite show where this was happening.

Related

Matching std::optional<bool> with Clang AST

I'm trying to write a clang-tidy check for std::optional<bool> r = 5 to catch implicit conversions to bool.
|-DeclStmt <line:4:5, col:30>
| `-VarDecl <col:5, col:29> col:25 r 'std::optional<bool>':'std::optional<bool>' cinit
| `-ExprWithCleanups <col:29> 'std::optional<bool>':'std::optional<bool>'
| `-ImplicitCastExpr <col:29> 'std::optional<bool>':'std::optional<bool>' <ConstructorConversion>
| `-CXXConstructExpr <col:29> 'std::optional<bool>':'std::optional<bool>' 'void (int &&) noexcept(is_nothrow_constructible_v<bool, int>)'
| `-MaterializeTemporaryExpr <col:29> 'int' xvalue
| `-IntegerLiteral <col:29> 'int' 5
So far, I have match implicitCastExpr(hasDescendant(cxxConstructExpr())) where I'm matching for an implicitCastExpr with a cxxConstructoExpr. The problem is I want to narrow the match on cxxConstructExpr to find only cases where bool is the template argument. Does anyone know how to do this?
Inside cxxConstructExpr(...), you also need to use hasType, classTemplateSpecializationDecl, hasTemplateArgument, refersToType, and booleanType.
Here is a shell script invoking clang-query that finds implicit conversions to std::optional<bool> from a type other than bool:
#!/bin/sh
query='m
implicitCastExpr( # Implicit conversion
hasSourceExpression( # from a
cxxConstructExpr( # constructor expr
hasType( # whose type is
classTemplateSpecializationDecl( # a template specialization
hasName("::std::optional"), # of std::optional
hasTemplateArgument( # with template argument
0, refersToType(booleanType()) # bool,
)
)
),
unless( # unless
hasArgument( # the constructor argument
0, expr( # is an expr with
hasType( # type
booleanType() # bool.
)
)
)
)
)
)
)'
clang-query -c="$query" "$#"
(I use a shell script so I can format the query expression and add comments.)
Test input test.cc:
// test.cc
// Test clang-query finding implicit conversions to optional<bool>.
#include <optional> // std::optional
void f()
{
std::optional<bool> r = 5; // reported
std::optional<int> s = 6; // not reported
std::optional<bool> t = false; // not reported
}
// EOF
Invocation of the script (saved as cmd.sh):
$ ./cmd.sh test.cc -- --std=c++17
Match #1:
[...path...]/test.cc:8:27: note: "root" binds here
std::optional<bool> r = 5; // reported
^
1 match.
I used Clang+LLVM-14.0.0, although I don't think I've used anything particularly recent here.
Figuring out these match expressions can be quite difficult. The main reference is the AST Matcher Reference, but even with that, it often requires a lot of trial and error.

Is it possible to have F# able to recognize an overlap of DU and use the right one itself?

type GenericResult =
| Ok
| Error of string
type LoginResult =
| Ok
| UserNotFound
| WrongPassword
let check something:GenericResult =
match something with
//| true -> Ok // error:This expression was expected to be of type "GenericREsult" but here has type "LoginResult"
| true -> GenericResult.Ok // I'm forced to specify GenericResult.Ok
| false -> Error "aargg!"
let checkLogin something:LoginResult =
match something with
| true -> Ok // here I don't need to specify the DU because this is defined after
| _ -> WrongPassword
I'd like to use just "Ok" in both the methods, without the need to specify the DU.
I see that in case of clashing of the value the last one is the "predefined".
Ideally I'd like to have a sort of inheritance
to reuse part of a DU in another DU.
For example:
type GenericResult =
| Ok
| Error of string
type LoginResult =
//| GenericResult.Ok
| UserNotFound
| WrongPassword
type SaveResult =
| Created
| Updated
//| GenericResult.Error
let checkLogin something: LoginResult | GenericResult.Ok =
match something with
| true -> Ok
| _ -> WrongPassword
[EDIT]
The real scenario where I feel the need for this feature is this with 3 different results from 3 different logic classes.
There will be in the future more cases so the multiplication of duplicated DU values will increase.
// DUs ordered from the most specific to the most generic
type BalanceUpdateResult =
| Created
| Updated
| InvalidRequest of string
type DeleteResult =
| Ok
| InvalidRequest of string
type Result<'T> =
| Ok of 'T
| NotValid of string
| Error of string
The goal is to have a clean match syntax in the consumer, where the value of the DU will evenctually be used to raise an exception or to return the created value, for example.
// balance update function (result is BalanceUpdateResult):
match result with
| Created -> this.createOkWithStatus 201
| Updated -> this.createOkWithStatus 200
| InvalidRequest error -> this.createErrorForConflict error
// company creation function (result is Result<Company>):
match result with
| Result.Ok newItem ->
context.Logger.Log $"Company created. New Id:{newItem.Id}, Name:{newItem.Name}."
this.createCreated newItem
| NotValid error -> base.createErrorForConflict error
| Error error -> base.createError error
Here, for example, InvalidRequest is not accepted in the second case because it belongs to the wrong DU.
Having to specify the DU everywhere results in a mess like the following example (see the many Result<_>.):
interface ICompanyLogic with
member this.Create(company:Company):Result<Company> =
match normalize company |> validate with
| NotValid msg -> Result<_>.NotValid msg
| Valid validCompany ->
match companyRepository.Exists(validCompany.Name) with
| true -> Result<_>.NotValid($"A company with name \"{validCompany.Name}\" already exists.")
| _ ->
let newCompany = assignNewId validCompany
companyRepository.Create(newCompany)
Result<_>.Ok(newCompany)
member this.Update (company:Company):Result<Company> =
let checkNameExists company =
match companyRepository.GetByName company.Name with
| Some c when c.Id <> company.Id -> NotValid $"A company with name \"{company.Name}\" already exists."
| _ -> Valid company
match normalize company |> validate with
| NotValid msg -> Result<_>.NotValid msg
| Valid c -> match checkNameExists c with
| Valid c -> companyRepository.Update c; Result<_>.Ok c
| NotValid msg -> Result<_>.NotValid msg
I think the best way to achieve what you are trying to do would be to start with a generic Result type that has a type parameter representing the error type:
type Result<'TError> =
| Ok
| Error of 'TError
This allows you to use different types for representing errors, including string, but also another DU to capture more specific error types. You can then define GenericResult and LoginResult as two type aliases:
type LoginError =
| UserNotFound
| WrongPassword
type GenericResult = Result<string>
type LoginResult = Result<LoginError>
To report a login error, you would now use Error WrongPassword to wrap the specific error in the generic Error constructor. The implementation of your two functions looks as follows:
let check something:GenericResult =
match something with
| true -> Ok
| false -> Error "aargg!"
let checkLogin something:LoginResult =
match something with
| true -> Ok
| _ -> Error WrongPassword
Unlike TypeScript union type, F# DU are meant to be composed and not extensible - see Thomas answer for a solution using this approach.
Since F# does not offer a direct solution, you may consider renaming cases like InvalidRequest in order to be more specific and to help differentiate them when reading the code. With these specific names, you can also merge all result types into a big Event DU like what's usually done in an event sourced system:
type Event =
// BalanceUpdateResult
| BalanceCreated
| BalanceUpdated
| BalanceUpdateError of string
// DeleteResult
| DeleteOk
| DeleteError of string
// ...
Ok, as explained by Romain multiple DUs cannot solve my problem.
I decided to use the built-in type Result<'T,'TError>.
It allows me to avoid create many DUs that inevitably will have clash of names, forcing the use the full DU prefix in the code.
I solved the problem that drove me to create custom DUs with the inspiring example from Thomas reply.
(with Result<,>) I have the possibility to have dinstinct Errors or Oks.
(note the Result<unit,_> and the Result<BalanceUpdateRequest,_>)
type ICompanyLogic =
abstract member Create:Company -> Result<Company, string> // CreateResult
abstract member Update:Company -> Result<Company, string> // UpdateResult
abstract member Delete:string -> Result<unit,string> // DeleteResult
type BalanceUpdateResult =
| Created
| Updated
type IBalanceLogic =
abstract member CreateOrUpdate: request:BalanceUpdateRequest -> Result<BalanceUpdateResult, string>
Apart BalanceUpdateResult all the other DUs where replaced buy the Result<'T,'TError>.
I just maintained a couple one for specific tasks:
type CompanyValidation = Valid of Company | NotValid of string
type ValidateResult = Valid | NotValid of string
In the end with this solution:
I don't need to define many DUs
I can customize the Result... within as many values I want (storing a sub-DU in the Ok or Error union case)
I don't need to use prefix or use synonims to avoid clash (code result much cleaner)

Pattern Matching does not allow me to change values

so I am currently working on a new programming language tr-lang
and I am currently in the process of writing the parser of the language
this piece of code is where the bug lies
BlockToken::İse(bip) => {
let ise = &mut parsed[bip]; // Access method 1
match ise.typ {
TokenType::İse ( mut yoksa ) => {
yoksa = Some(ip);
},
TokenType::Yoksa ( mut tp ) => {
tp = Some(ip);
},
_ => unreachable!(),
}
ip + 1
},
BlockToken::İken(bip) => {
let iken = parsed.get_mut(bip).unwrap(); // Trying other access methods
match iken.typ {
TokenType::İken ( mut yoksa ) => {
yoksa = Some(ip + 1);
},
_ => unreachable!(),
}
bip
},
_ => unimplemented!(),
};
and this is part of the code that parses and produces an executable program
and it gives a few warnings but i think the problem lies in these ones:
warning: variable `yoksa` is assigned to, but never used
--> src/parser/parser.rs:121:54
|
121 | ... TokenType::İse ( mut yoksa ) => {
| ^^^^^
|
= note: consider using `_yoksa` instead
warning: value assigned to `yoksa` is never read
--> src/parser/parser.rs:122:37
|
122 | ... yoksa = Some(ip);
| ^^^^^
|
= help: maybe it is overwritten before being read?
warning: variable `tp` is assigned to, but never used
--> src/parser/parser.rs:124:56
|
124 | ... TokenType::Yoksa ( mut tp ) => {
| ^^
|
= note: consider using `_tp` instead
warning: value assigned to `tp` is never read
--> src/parser/parser.rs:125:37
|
125 | ... tp = Some(ip);
| ^^
|
= help: maybe it is overwritten before being read?
warning: variable `yoksa` is assigned to, but never used
--> src/parser/parser.rs:134:55
|
134 | ... TokenType::İken ( mut yoksa ) => {
| ^^^^^
|
= note: consider using `_yoksa` instead
warning: value assigned to `yoksa` is never read
--> src/parser/parser.rs:135:37
|
135 | ... yoksa = Some(ip + 1);
| ^^^^^
|
= help: maybe it is overwritten before being read?
as you can see for some reason even though i pattern-match like usual when i try to set the value to something else it treats the variables as different
and instead of changing the value of yoksa/tp the end result just does not change anything
i tried changing the way i access ise/iken however it didn't change anything
i also tried using if let instead of match
it doesn't change the value of ise.typ.yoksa or ise.typ.tp
for extra info BlockToken is this enum
enum BlockToken {
İse(usize),
İken(usize),
İkiNoktaNokta(usize),
}
Token is this struct
struct Token {
pub typ: TokenType,
pub line: usize,
pub col: usize,
}
what i want from here is the ability to change the contents of the enum structs İse, İken and Yoksa
it can be unsafe although a safe method is preferred
Use Option::replace to fit the new value into the mutable option:
yoksa.replace(ip + 1);
Also you probably want a mutable reference:
TokenType::İken(ref mut yoksa)
I think you need to match on a mutable reference when matching otherwise you are just creating a local variable and mutating that.
For example this code:
#[derive(Debug)]
enum Blah {
A(u64),
}
mod test {
use super::Blah;
#[test]
fn test_match() {
let mut a = Blah::A(23);
println!("{:?}", a);
match a {
Blah::A(ref mut x) => *x = 5,
}
println!("{:?}", a);
}
}
will output:
running 1 test
A(23)
A(5)
If you run it with cargo test -- --nocapture.

How to get a null value when using the head function with an empty list

I have a cypher query like this.
START dep=node:cities(city_code = "JGS"),
arr=node:cities(city_code = "XMN")
MATCH dep-[way:BRANCH2BRANCH_AIRWAY*0..1]->()-->arr
RETURN length(way), transfer.city_code,
extract(w in way: w.min_consume_time) AS consumeTime
The relationship named "way" is a optional one, so the property named "consumeTime" will be a empty list when the relationship "way" not exsit.
The query result is:
| 0 | "JGS" | [] |
| 1 | "SZX" | [3600] |
When I want to use the head function with the property "consumeTime", it return a error "Invalid query: head of empty list".
How can I get a result like this?
| 0 | "JGS" | null |
| 1 | "SZX" | 3600 |
This would be trivial with conditional expressions, which is something I think is important to add to Cypher: https://github.com/neo4j/community/issues/899
Here's a somewhat hacky query using reduce for you that requires 1.9-SNAPSHOT:
START dep=node:cities(city_code = "JGS"),
arr=node:cities(city_code = "XMN")
MATCH dep-[way:BRANCH2BRANCH_AIRWAY*0..1]->()-->arr
WITH length(way) as wayLength,
transfer.city_code as transferCityCode,
extract(w in way: w.min_consume_time) AS consumeTime
WITH wayLength,
transferCityCode,
consumeTime,
// reverse the consumeTime list, so that we can get the head from the end
reduce(acc=[], x in consumeTime: x + acc) reverseConsumeTime
RETURN wayLength,
transferCityCode,
consumeTime,
// return null if empty, else the end of the list
reduce(acc=null, x in reverseConsumeTime: x) as headOrNull;
This query could be improved a fair amount with the following syntax to reverse a collection:
reverse(coll) or conditional expressions to check for an empty list.

Puzzling error message in Happy parser

I'm building a JavaScript parser in Haskell using Happy and I'm running into an error message that, no matter how hard I try, I can't debug.
I can't really post all the code here as it is thousands of lines long. I'll try to post the relevant bits and if anyone can help me I'd be immensely grateful!
This error message is very long so please bear with me. I've left out most of the HappyAbsSyn part. I can provide the full error message if it will help.
Parser.hs:800:28:
Couldn't match expected type `Expression'
with actual type `PrimaryExpr'
Expected type: Int
-> Int
-> Token
-> HappyState
Token
(HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
PostFix)
-> P a1)
-> [HappyState
Token
(HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
PostFix)
-> P a1)]
-> HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
Actual type: Int
-> Int
-> Token
-> HappyState
Token
(HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
t630)
-> P a0)
-> [HappyState
Token
(HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
t630)
-> P a0)]
-> HappyStk
(HappyAbsSyn
FuncDecl
... etc etc ...
t630)
-> P a0
In the first argument of `happyGoto', namely `action_90'
In the expression: happyGoto action_90
Got that? Ok, so the first thing I did was look at line 800 in Parser.hs (The file generated by Happy).
799: action_60 (7) = happyGoto action_71
800: action_60 (28) = happyGoto action_90
801: action_60 (33) = happyGoto action_15
action_90 is defined as:
action_90 (100) = happyShift action_224
action_90 _ = happyFail
This obviously doesn't make much sense unless we understand what the codes correspond to. I asked Happy to generate an info file when I compiled and this is (I think) the appropriate part:
-----------------------------------------------------------------------------
Grammar
-----------------------------------------------------------------------------
%start_parse -> program (0)
... etc etc ...
statement -> ID ':' statement (28)
... etc etc ...
primaryExpr -> THIS (100)
... etc etc ...
So it looks like it's something to do with an ID statement. I'm really quite confused by this point. Does anyone have any suggestions of where I should go from here? I'm guessing that to work through this, you'd need to see the Abstract Syntax. Here is a bit of it. Again, I'm happy to show more if it helps.
data Expression
= Assignment Assignment
deriving Show
data Assignment
= CondExpr CondExpr
| Assign LeftExpr AssignOp Assignment
| AssignFuncDecl FuncDecl
deriving Show
data FuncDecl
= FuncDecl (Maybe String) [String] [Source]
deriving Show
data Statement
= EmptyStmt
| IfStmt IfStmt
| IterativeStmt IterativeStmt
| ExprStmt Expression
| Block [Statement]
| VarStmt [VarDecl]
| TryStmt TryStmt
| ContinueStmt (Maybe String)
| BreakStmt (Maybe String)
| ReturnStmt (Maybe Expression)
| WithStmt Expression Statement
| LabelledStmt String Statement
| Switch Switch
| ThrowExpr Expression
deriving Show
data PrimaryExpr
= ExpLitInt Integer
| ExpLitStr String
| ExpId String
| ExpBrackExp PrimaryExpr
| ExpThis
| ExpRegex String
| ExpArray ArrayLit
| ExpObject [(Property, Assignment)]
deriving Show
I'm sorry this is so long. I'm at my wits end here. Any help or pointers would be amazing.

Resources