Bill Sun 3 years ago
parent 2bd7fdac52
commit 3d01d60374

2
.gitignore vendored

@ -33,3 +33,5 @@ test*.c*
**/x64 **/x64
*.user *.user
*.filters *.filters
*.tmp
server.bin

Binary file not shown.

@ -1,8 +1,4 @@
all: snippet:
g++ mmw.cpp --std=c++1z -shared -fPIC -Ofast -march=native -g0 -s -o mmw.so g++ -shared --std=c++1z out.cpp -O3 -march=native -o dll.so
avx512: clean:
g++ mmw.cpp --std=c++1z -shared -fPIC -Ofast -mavx512f -g0 -s -o mmw.so rm *.shm -rf
debug:
g++ mmw.cpp --std=c++1z -shared -fPIC -O0 -march=native -g3 -o mmw.so
clean:
rm mmw.so -rf

@ -0,0 +1,8 @@
all:
g++ mmw.cpp --std=c++1z -shared -fPIC -Ofast -march=native -g0 -s -o mmw.so
avx512:
g++ mmw.cpp --std=c++1z -shared -fPIC -Ofast -mavx512f -g0 -s -o mmw.so
debug:
g++ mmw.cpp --std=c++1z -shared -fPIC -O0 -march=native -g3 -o mmw.so
clean:
rm mmw.so -rf

@ -1,12 +1,12 @@
# AQuery Compiler # AQuery Compiler
AQuery Compiler that compiles AQuery into [K9](https://shakti.com/). AQuery Compiler that compiles AQuery into [c](https://shakti.com/).
Frontend built on top of [mo-sql-parsing](https://github.com/klahnakoski/mo-sql-parsing). Frontend built on top of [mo-sql-parsing](https://github.com/klahnakoski/mo-sql-parsing).
## Roadmap ## Roadmap
- [x] SQL Parser -> AQuery Parser - [x] SQL Parser -> AQuery Parser
- [ ] Data acquisition/output from/to csv file (By Jan. 21) - [ ] Data acquisition/output from/to csv file (By Jan. 21)
- -> AQuery-K9 Compiler - -> AQuery-c Compiler
- Simple query (By Jan. 21) - Simple query (By Jan. 21)
- [ ] Nested queries (Jan. 28) - [ ] Nested queries (Jan. 28)
- [ ] -> Optimizing Compiler - [ ] -> Optimizing Compiler

@ -0,0 +1,61 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0, 1\n",
"1, 1\n",
"1, 2\n",
"1, 2\n"
]
}
],
"source": [
"class A:\n",
" def s(self, *_):\n",
" print(\"A\")\n",
"\n",
"class B(A):\n",
" def s(self, a, b = 1, *_):\n",
" print(f'{a}, {b}')\n",
"\n",
"t = B()\n",
"t.s(0)\n",
"t.s(1)\n",
"t.s(1,2)\n",
"t.s(1,2,3)"
]
}
],
"metadata": {
"interpreter": {
"hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
},
"kernelspec": {
"display_name": "Python 3.10.2 64-bit",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}

Binary file not shown.

@ -64,7 +64,7 @@ def parser(literal_string, ident, sqlserver=False):
var_name = ~RESERVED + ident var_name = ~RESERVED + ident
inline_kblock = (L_INLINE + SkipTo(R_INLINE, include=True))("k9") inline_kblock = (L_INLINE + SkipTo(R_INLINE, include=True))("c")
# EXPRESSIONS # EXPRESSIONS
expr = Forward() expr = Forward()
column_type, column_definition, column_def_references = get_column_type( column_type, column_definition, column_def_references = get_column_type(

1273
csv.h

File diff suppressed because it is too large Load Diff

@ -1,24 +1,39 @@
from typing import List
from pyparsing import col
from engine.utils import base62uuid from engine.utils import base62uuid
# replace column info with this later. # replace column info with this later.
class ColRef: class ColRef:
def __init__(self, k9name, _ty, cobj, cnt, table, name, id, compound = False): def __init__(self, cname, _ty, cobj, cnt, table:'TableInfo', name, id, compound = False):
self.k9name = k9name self.cname = cname
self.cxt_name = None
self.type = _ty self.type = _ty
self.cobj = cobj self.cobj = cobj
self.cnt = cnt self.cnt = cnt
self.table = table self.table = table
self.name = name self.name = name
self.id = id self.id = id # position in table
self.order_pending = None # order_pending self.order_pending = None # order_pending
self.compound = compound # compound field (list as a field) self.compound = compound # compound field (list as a field)
self.views = [] self.views = []
self.__arr__ = (k9name, _ty, cobj, cnt, table, name, id) self.__arr__ = (cname, _ty, cobj, cnt, table, name, id)
def reference(self):
cxt = self.table.cxt
self.table.reference()
if self not in cxt.columns_in_context:
counter = 0
base_name = self.table.table_name + '_' + self.name
if base_name in cxt.columns_in_context.values():
while (f'{base_name}_{counter}') in cxt.columns_in_context.values():
counter += 1
base_name = f'{base_name}_{counter}'
self.cxt_name = base_name
cxt.columns_in_context[self] = base_name
cxt.emit(f'auto& {base_name} = *(ColRef<{self.type}> *)(&{self.table.cxt_name}->colrefs[{self.id}]);')
elif self.cxt_name is None:
self.cxt_name = cxt.columns_in_context[self]
return self.cxt_name
def __getitem__(self, key): def __getitem__(self, key):
if type(key) is str: if type(key) is str:
return getattr(self, key) return getattr(self, key)
@ -29,7 +44,7 @@ class ColRef:
self.__arr__[key] = value self.__arr__[key] = value
def __str__(self): def __str__(self):
return self.k9name return self.cname
class TableInfo: class TableInfo:
@ -40,7 +55,10 @@ class TableInfo:
self.columns_byname = dict() # column_name, type self.columns_byname = dict() # column_name, type
self.columns = [] self.columns = []
self.cxt = cxt self.cxt = cxt
self.cxt_name = None
self.views = set() self.views = set()
#keep track of temp vars
self.local_vars = dict()
self.rec = None self.rec = None
self.groupinfo = None self.groupinfo = None
self.add_cols(cols) self.add_cols(cols)
@ -49,25 +67,47 @@ class TableInfo:
self.order = [] # assumptions self.order = [] # assumptions
cxt.tables_byname[self.table_name] = self # construct reverse map cxt.tables_byname[self.table_name] = self # construct reverse map
def reference(self):
if self not in self.cxt.tables_in_context:
counter = 0
base_name = self.table_name
if base_name in self.cxt.tables_in_context.values():
while (f'{base_name}_{counter}') in self.cxt.tables_in_context.values():
counter += 1
base_name = f'{base_name}_{counter}'
self.cxt_name = base_name
self.cxt.tables_in_context[self] = base_name
type_tags = '<'
for c in self.columns:
type_tags += c.type + ','
if type_tags.endswith(','):
type_tags = type_tags[:-1]
type_tags += '>'
self.cxt.emit(f'auto& {base_name} = *(TableInfo{type_tags} *)(cxt->tables[{self.table_name}]);')
def refer_all(self):
for c in self.columns:
c.reference()
def add_cols(self, cols, new = True): def add_cols(self, cols, new = True):
for c in cols: for i, c in enumerate(cols):
self.add_col(c, new) self.add_col(c, new, i)
def add_col(self, c, new = True): def add_col(self, c, new = True, i = 0):
_ty = c['type'] _ty = c['type']
if new: if new:
k9name = 'c' + base62uuid(7) cname =f'{self.table_name}->colrefs[{i}].scast<int>()'
_ty = _ty if type(c) is ColRef else list(_ty.keys())[0] _ty = _ty if type(c) is ColRef else list(_ty.keys())[0]
col_object = ColRef(k9name, _ty, c, 1, self,c['name'], len(self.columns)) col_object = ColRef(cname, _ty, c, 1, self,c['name'], len(self.columns))
else: else:
col_object = c col_object = c
k9name = c.k9name cname = c.cname
self.cxt.k9cols_byname[k9name] = col_object self.cxt.ccols_byname[cname] = col_object
self.columns_byname[c['name']] = col_object self.columns_byname[c['name']] = col_object
self.columns.append(col_object) self.columns.append(col_object)
def construct(self): def construct(self):
for c in self.columns: for c in self.columns:
self.cxt.emit(f'{c.k9name}:()') self.cxt.emit(f'{c.cname}:()')
@property @property
def n_cols(self): def n_cols(self):
return len(self.columns) return len(self.columns)
@ -97,18 +137,18 @@ class TableInfo:
self.rec.append(col) self.rec.append(col)
return col return col
def get_k9colname_d(self, col_name): def get_ccolname_d(self, col_name):
return self.get_col_d(col_name).k9name return self.get_col_d(col_name).cname
def get_col(self, col_name): def get_col(self, col_name):
self.materialize_orderbys() self.materialize_orderbys()
col = self.get_col_d(col_name) col = self.get_col_d(col_name)
if type(col.order_pending) is str: if type(col.order_pending) is str:
self.cxt.emit_no_flush(f'{col.k9name}:{col.k9name}[{col.order_pending}]') self.cxt.emit_no_flush(f'{col.cname}:{col.cname}[{col.order_pending}]')
col.order_pending = None col.order_pending = None
return col return col
def get_k9colname(self, col_name): def get_ccolname(self, col_name):
return self.get_col(col_name).k9name return self.get_col(col_name).cname
def add_alias(self, alias): def add_alias(self, alias):
# TODO: Exception when alias already defined. # TODO: Exception when alias already defined.
@ -130,9 +170,9 @@ class TableInfo:
else: else:
ret = datasource.get_col(parsedColExpr[1]) ret = datasource.get_col(parsedColExpr[1])
if self.groupinfo is not None and ret: if self.groupinfo is not None and ret:
ret = f"{ret.k9name}[{'start' if ret in self.groupinfo.referenced else 'range'}]" ret = f"{ret.reference()}[{'start' if ret in self.groupinfo.referenced else 'range'}]"
else: else:
ret = ret.k9name ret = ret.reference()
return ret return ret
class View: class View:
@ -147,17 +187,23 @@ class View:
self.context.emit(f'{self.name}:()') self.context.emit(f'{self.name}:()')
class Context: class Context:
function_head = 'extern \"C\" int dllmain(Context* cxt){ \n'
def __init__(self): def __init__(self):
self.tables:List[TableInfo] = [] self.tables:List[TableInfo] = []
self.tables_byname = dict() self.tables_byname = dict()
self.k9cols_byname = dict() self.ccols_byname = dict()
self.gc_name = 'gc_' + base62uuid(4)
self.tmp_names = set()
self.udf_map = dict() self.udf_map = dict()
self.headers = set(['\"./server/libaquery.h\"'])
self.finalized = False
# read header # read header
self.k9code = '' self.ccode = ''
self.k9codelet = '' self.ccodelet = ''
with open('header.k', 'r') as outfile: self.columns_in_context = dict()
self.k9code = outfile.read() self.tables_in_context = dict()
with open('header.cxx', 'r') as outfile:
self.ccode = outfile.read()
# datasource will be availible after `from' clause is parsed # datasource will be availible after `from' clause is parsed
# and will be deactivated when the `from' is out of scope # and will be deactivated when the `from' is out of scope
self.datasource = None self.datasource = None
@ -171,17 +217,28 @@ class Context:
def gen_tmptable(self): def gen_tmptable(self):
from engine.utils import base62uuid from engine.utils import base62uuid
return f't{base62uuid(7)}' return f't{base62uuid(7)}'
def reg_tmp(self, name, f):
self.tmp_names.add(name)
self.emit(f"{self.gc_name}.reg({{{name}, 0,0{'' if f is None else ',{f}'}}});")
def define_tmp(self, typename, isPtr = True, f = None):
name = 'tmp_' + base62uuid()
if isPtr:
self.emit(f'auto* {name} = new {typename};')
self.reg_tmp(name, f)
else:
self.emit(f'auto {name} = {typename};')
return name
def emit(self, codelet): def emit(self, codelet):
self.k9code += self.k9codelet + codelet + '\n' self.ccode += self.ccodelet + codelet + '\n'
self.k9codelet = '' self.ccodelet = ''
def emit_no_flush(self, codelet): def emit_no_flush(self, codelet):
self.k9code += codelet + '\n' self.ccode += codelet + '\n'
def emit_flush(self): def emit_flush(self):
self.k9code += self.k9codelet + '\n' self.ccode += self.ccodelet + '\n'
self.k9codelet = '' self.ccodelet = ''
def emit_nonewline(self, codelet): def emit_nonewline(self, codelet):
self.k9codelet += codelet self.ccodelet += codelet
def datsource_top(self): def datsource_top(self):
if len(self.ds_stack) > 0: if len(self.ds_stack) > 0:
@ -200,19 +257,33 @@ class Context:
return ds return ds
else: else:
return None return None
def finalize(self):
if not self.finalized:
headers = ''
for h in self.headers:
if h[0] != '"':
headers += '#include <' + h + '>\n'
else:
headers += '#include ' + h + '\n'
self.ccode = headers + self.function_head + self.ccode + 'return 0;\n}'
self.headers = set()
return self.ccode
def __str__(self): def __str__(self):
return self.k9code self.finalize()
return self.ccode
def __repr__(self) -> str: def __repr__(self) -> str:
return self.__str__() return self.__str__()
class ast_node: class ast_node:
types = dict() types = dict()
header = []
def __init__(self, parent:"ast_node", node, context:Context = None): def __init__(self, parent:"ast_node", node, context:Context = None):
self.context = parent.context if context is None else context self.context = parent.context if context is None else context
self.parent = parent self.parent = parent
self.datasource = None self.datasource = None
for h in self.header:
self.context.headers.add(h)
self.init(node) self.init(node)
self.produce(node) self.produce(node)
self.spawn(node) self.spawn(node)

@ -7,10 +7,15 @@ class create_table(ast_node):
def produce(self, node): def produce(self, node):
ct = node[self.name] ct = node[self.name]
tbl = self.context.add_table(ct['name'], ct['columns']) tbl = self.context.add_table(ct['name'], ct['columns'])
# create tables in k9 # create tables in c
for c in ct['columns']: self.emit(f"auto {tbl.table_name} = new TableInfo(\"{tbl.table_name}\", {tbl.n_cols});")
self.emit(f"{tbl.get_k9colname(c['name'])}:()") self.emit("cxt->tables.insert({\"" + tbl.table_name + f"\", {tbl.table_name}"+"});")
self.context.tables_in_context[tbl] = tbl.table_name
tbl.cxt_name = tbl.table_name
for i, c in enumerate(ct['columns']):
# TODO: more self awareness
self.emit(f"{tbl.table_name}->colrefs[{i}].ty = types::AINT;")
class insert(ast_node): class insert(ast_node):
name = 'insert' name = 'insert'
def produce(self, node): def produce(self, node):
@ -20,16 +25,17 @@ class insert(ast_node):
values = node['query']['select'] values = node['query']['select']
if len(values) != table.n_cols: if len(values) != table.n_cols:
raise ValueError("Column Mismatch") raise ValueError("Column Mismatch")
table.refer_all()
for i, s in enumerate(values): for i, s in enumerate(values):
if 'value' in s: if 'value' in s:
k9name = table.columns[i][0] cname = table.columns[i].cxt_name
self.emit(f"{k9name}:{k9name},{s['value']}") self.emit(f"{cname}.emplace_back({s['value']});")
else: else:
# subquery, dispatch to select astnode # subquery, dispatch to select astnode
pass pass
class k9(ast_node): class c(ast_node):
name='k9' name='c'
def produce(self, node): def produce(self, node):
self.emit(node[self.name]) self.emit(node[self.name])
@ -47,7 +53,7 @@ class load(ast_node):
self.emit(f"{tablename}:({keys}!(+(`csv ? 1:\"{node['file']['literal']}\")))[{keys}]") self.emit(f"{tablename}:({keys}!(+(`csv ? 1:\"{node['file']['literal']}\")))[{keys}]")
for i, c in enumerate(table.columns): for i, c in enumerate(table.columns):
self.emit(f'{c.k9name}:{tablename}[{i}]') self.emit(f'{c.cname}:{tablename}[{i}]')
class outfile(ast_node): class outfile(ast_node):
name="_outfile" name="_outfile"
@ -64,17 +70,17 @@ class outfile(ast_node):
l_keys += '`' + c.name l_keys += '`' + c.name
if c.compound: if c.compound:
if l_compound: if l_compound:
l_cols=f'flatBOTH\'+(({ending(l_cols)});{c.k9name})' l_cols=f'flatBOTH\'+(({ending(l_cols)});{c.cname})'
else: else:
l_compound = True l_compound = True
if i >= 1: if i >= 1:
l_cols = f'flatRO\'+(({ending(l_cols)});{c.k9name})' l_cols = f'flatRO\'+(({ending(l_cols)});{c.cname})'
else: else:
l_cols = c.k9name + ';' l_cols = c.cname + ';'
elif l_compound: elif l_compound:
l_cols = f'flatLO\'+(({ending(l_cols)});{c.k9name})' l_cols = f'flatLO\'+(({ending(l_cols)});{c.cname})'
else: else:
l_cols += f"{c.k9name};" l_cols += f"{c.cname};"
if not l_compound: if not l_compound:
self.emit_no_ln(l_keys + '!(' + ending(l_cols) + ')') self.emit_no_ln(l_keys + '!(' + ending(l_cols) + ')')
else: else:

@ -54,7 +54,7 @@ class expr(ast_node):
else: else:
self.datasource = self.context.datasource self.datasource = self.context.datasource
self.udf_map = parent.context.udf_map self.udf_map = parent.context.udf_map
self.k9expr = '' self.cexpr = ''
self.func_maps = {**self.udf_map, **self.builtin_func_maps} self.func_maps = {**self.udf_map, **self.builtin_func_maps}
def produce(self, node): def produce(self, node):
@ -63,29 +63,29 @@ class expr(ast_node):
if key in self.func_maps: if key in self.func_maps:
# if type(val) in [dict, str]: # if type(val) in [dict, str]:
if type(val) is list and len(val) > 1: if type(val) is list and len(val) > 1:
k9func = self.func_maps[key] cfunc = self.func_maps[key]
k9func = k9func[len(val) - 1] if type(k9func) is list else k9func cfunc = cfunc[len(val) - 1] if type(cfunc) is list else cfunc
self.k9expr += f"{k9func}[" self.cexpr += f"{cfunc}("
for i, p in enumerate(val): for i, p in enumerate(val):
self.k9expr += expr(self, p).k9expr + (';'if i<len(val)-1 else '') self.cexpr += expr(self, p).cexpr + (';'if i<len(val)-1 else '')
else: else:
funcname = self.func_maps[key] funcname = self.func_maps[key]
funcname = funcname[0] if type(funcname) is list else funcname funcname = funcname[0] if type(funcname) is list else funcname
self.k9expr += f"{funcname}[" self.cexpr += f"{funcname}("
self.k9expr += expr(self, val).k9expr self.cexpr += expr(self, val).cexpr
self.k9expr += ']' self.cexpr += ')'
elif key in self.binary_ops: elif key in self.binary_ops:
l = expr(self, val[0]).k9expr l = expr(self, val[0]).cexpr
r = expr(self, val[1]).k9expr r = expr(self, val[1]).cexpr
self.k9expr += f'({l}{self.binary_ops[key]}{r})' self.cexpr += f'({l}{self.binary_ops[key]}{r})'
elif key in self.compound_ops: elif key in self.compound_ops:
x = [] x = []
if type(val) is list: if type(val) is list:
for v in val: for v in val:
x.append(expr(self, v).k9expr) x.append(expr(self, v).cexpr)
self.k9expr = self.compound_ops[key][1](x) self.cexpr = self.compound_ops[key][1](x)
elif key in self.unary_ops: elif key in self.unary_ops:
self.k9expr += f'({expr(self, val).k9expr}{self.unary_ops[key]})' self.cexpr += f'({expr(self, val).cexpr}{self.unary_ops[key]})'
else: else:
print(f'Undefined expr: {key}{val}') print(f'Undefined expr: {key}{val}')
@ -101,10 +101,10 @@ class expr(ast_node):
while type(p) is expr and not p.isvector: while type(p) is expr and not p.isvector:
p.isvector = True p.isvector = True
p = p.parent p = p.parent
self.k9expr = self.datasource.parse_tablenames(node, self.materialize_cols) self.cexpr = self.datasource.parse_tablenames(node, self.materialize_cols)
elif type(node) is bool: elif type(node) is bool:
self.k9expr = '1' if node else '0' self.cexpr = '1' if node else '0'
else: else:
self.k9expr = f'{node}' self.cexpr = f'{node}'
def __str__(self): def __str__(self):
return self.k9expr return self.cexpr

@ -15,7 +15,7 @@ class groupby(ast_node):
first_col = '' first_col = ''
for i, g in enumerate(node): for i, g in enumerate(node):
v = g['value'] v = g['value']
e = expr(self, v).k9expr e = expr(self, v).cexpr
# if v is compound expr, create tmp cols # if v is compound expr, create tmp cols
if type(v) is not str: if type(v) is not str:
tmpcol = 't' + base62uuid(7) tmpcol = 't' + base62uuid(7)
@ -41,16 +41,16 @@ class groupby(ast_node):
self.groupby_function = 'fgrp'+base62uuid(4) self.groupby_function = 'fgrp'+base62uuid(4)
grp = self.group grp = self.group
if self.n_grps <= 1: if self.n_grps <= 1:
k9fn = "{[range] start:*range;"+ ret + "}" cfn = "{[range] start:*range;"+ ret + "}"
self.emit(f'{out}:(({k9fn}\'{grp})[!{grp}])') self.emit(f'{out}:(({cfn}\'{grp})[!{grp}])')
self.parent.inv = False self.parent.inv = False
else: else:
k9fn = "{[ids;grps;ll;dim;x] " + \ cfn = "{[ids;grps;ll;dim;x] " + \
"start:grps[x][dim];" + \ "start:grps[x][dim];" + \
"end:$[x=0;ll;grps[x-1][dim]];" + \ "end:$[x=0;ll;grps[x-1][dim]];" + \
"range:(end-start)#((start-ll)#ids);" + \ "range:(end-start)#((start-ll)#ids);" + \
"start:ids[start];" + \ "start:ids[start];" + \
ret + '}' ret + '}'
self.emit(f'{self.groupby_function}:{k9fn}') self.emit(f'{self.groupby_function}:{cfn}')
self.emit(f'{out}:+({self.groupby_function}' + \ self.emit(f'{out}:+({self.groupby_function}' + \
f'[{grp}[1];{grp}[0];(#{grp}[0])+1;(#({grp}[0][0]))-1]\'!(#({grp}[0])))') f'[{grp}[1];{grp}[0];(#{grp}[0])+1;(#({grp}[0][0]))-1]\'!(#({grp}[0])))')

@ -1,7 +1,6 @@
from engine.ast import ColRef, TableInfo, View, ast_node, Context from engine.ast import ColRef, TableInfo, View, ast_node, Context
from engine.utils import base62uuid, seps from engine.utils import base62uuid, seps
from engine.expr import expr from engine.expr import expr
import k
class order_item: class order_item:
def __init__(self, name, node, order = True): def __init__(self, name, node, order = True):
@ -12,7 +11,7 @@ class order_item:
def materialize(self): def materialize(self):
if not self.materialized: if not self.materialized:
self.name = expr(self.node, self.name, False).k9expr self.name = expr(self.node, self.name, False).cexpr
self.materialized = True self.materialized = True
return ('' if self.order else '-') + f'({self.name})' return ('' if self.order else '-') + f'({self.name})'

@ -1,4 +1,3 @@
from attr import has
from engine.ast import ColRef, TableInfo, ast_node, Context, include from engine.ast import ColRef, TableInfo, ast_node, Context, include
from engine.groupby import groupby from engine.groupby import groupby
from engine.join import join from engine.join import join
@ -76,7 +75,7 @@ class projection(ast_node):
if self.group_node is not None: if self.group_node is not None:
# There is group by; # There is group by;
has_groupby = True has_groupby = True
k9expr = f'(' cexpr = f'('
flatten = False flatten = False
cols = [] cols = []
self.out_table = TableInfo('out_'+base62uuid(4), [], self.context) self.out_table = TableInfo('out_'+base62uuid(4), [], self.context)
@ -92,25 +91,25 @@ class projection(ast_node):
e = proj['value'] e = proj['value']
if type(e) is str: if type(e) is str:
cname = e # TODO: deal w/ alias cname = e # TODO: deal w/ alias
k9expr += (f"{self.datasource.parse_tablenames(proj['value'])}") cexpr += (f"{self.datasource.parse_tablenames(proj['value'])}")
elif type(e) is dict: elif type(e) is dict:
p_expr = expr(self, e) p_expr = expr(self, e)
cname = p_expr.k9expr cname = p_expr.cexpr
compound = True compound = True
k9expr += f"{cname}" cexpr += f"{cname}"
cname = ''.join([a if a in base62alp else '' for a in cname]) cname = ''.join([a if a in base62alp else '' for a in cname])
k9expr += ';'if i < len(self.projections)-1 else '' cexpr += ';'if i < len(self.projections)-1 else ''
compound = compound and has_groupby and self.datasource.rec not in self.group_node.referenced compound = compound and has_groupby and self.datasource.rec not in self.group_node.referenced
cols.append(ColRef(f'{disp_varname}[{i}]', 'generic', self.out_table, 0, None, cname, i, compound=compound)) cols.append(ColRef(f'{disp_varname}[{i}]', 'generic', self.out_table, 0, None, cname, i, compound=compound))
self.out_table.add_cols(cols, False) self.out_table.add_cols(cols, False)
k9expr += ')' cexpr += ')'
if has_groupby: if has_groupby:
self.group_node.finalize(k9expr, disp_varname) self.group_node.finalize(cexpr, disp_varname)
else: else:
self.emit(f'{disp_varname}:{k9expr}') self.emit(f'auto {disp_varname} = {cexpr};')
self.datasource.group_node = None self.datasource.group_node = None
has_orderby = 'orderby' in node has_orderby = 'orderby' in node
@ -126,7 +125,7 @@ class projection(ast_node):
if len(self.projections) > 1: if len(self.projections) > 1:
self.emit_no_ln(f"{'+' if self.inv else ''}{disp_varname}") self.emit_no_ln(f"{'+' if self.inv else ''}{disp_varname}")
else: else:
self.emit_no_ln(f'$[(#{disp_varname})>1;+,({disp_varname});+,(,{disp_varname})]') self.emit_no_ln(f'print({disp_varname});')
if flatten: if flatten:
self.emit_no_ln(f'{disp_varname}') self.emit_no_ln(f'{disp_varname}')
if has_orderby: if has_orderby:

@ -27,12 +27,12 @@ class filter(ast_node):
if type(self.value) is View: # cond filtered on tables. if type(self.value) is View: # cond filtered on tables.
self.emit(f'{self.value.name}:&{self.value.name}') self.emit(f'{self.value.name}:&{self.value.name}')
for o, c in zip(self.output.columns,self.value.table.columns): for o, c in zip(self.output.columns,self.value.table.columns):
self.emit(f'{o.k9name}:{c.k9name}[{self.value.name}]') self.emit(f'{o.cname}:{c.cname}[{self.value.name}]')
elif self.value is not None: # cond is scalar elif self.value is not None: # cond is scalar
tmpVar = 't'+base62uuid(7) tmpVar = 't'+base62uuid(7)
self.emit(f'{tmpVar}:{self.value}') self.emit(f'{tmpVar}:{self.value}')
for o, c in zip(self.output.columns, self.datasource.columns): for o, c in zip(self.output.columns, self.datasource.columns):
self.emit(f'{o.k9name}:$[{tmpVar};{c.k9name};()]') self.emit(f'{o.cname}:$[{tmpVar};{c.cname};()]')
def consume(self, node): def consume(self, node):
# TODO: optimizations after converting expr to cnf # TODO: optimizations after converting expr to cnf
@ -86,7 +86,7 @@ class filter(ast_node):
elif type(v) is View: elif type(v) is View:
if len(v.table.columns) > 0: if len(v.table.columns) > 0:
all_rows = View(self.context, v.table) all_rows = View(self.context, v.table)
self.emit(f'{all_rows.name}:(#{v.table.columns[0].k9name})#1') self.emit(f'{all_rows.name}:(#{v.table.columns[0].cname})#1')
self.emit(f'{v.name}:{all_rows.name}-{v.name}') self.emit(f'{v.name}:{all_rows.name}-{v.name}')
self.value = v self.value = v
else: else:
@ -97,10 +97,10 @@ class filter(ast_node):
if e.isvector: if e.isvector:
v = View(self.context, self.datasource) v = View(self.context, self.datasource)
v.construct() v.construct()
self.emit(f'{v.name}:{e.k9expr}') self.emit(f'{v.name}:{e.cexpr}')
self.value = v self.value = v
else: else:
self.value = e.k9expr self.value = e.cexpr
self.__materialize__() self.__materialize__()
print(node) print(node)

@ -0,0 +1,33 @@
from engine.ast import Context
class Types:
name = 'Any'
cname = 'void*'
ctype_name = "types::NONE"
def __init__(self, context:Context):
self.cxt = context
def cast_to(self, *_):
return self
def cast_from(self, *_):
return self
def __repr__(self) -> str:
return self.cname
class String(Types):
name = 'String'
cname = 'const char*'
ctype_name = "types::ASTR"
def cast_from(self, ty, val, container = None):
if type(ty) is Int:
self.cxt.emit()
class Int(Types):
name = "Int"
cname = "int"
ctype_name = "types::AINT"
class Float(Types):
name = "Float"
cname = "float"
ctype_name = "types::AFLOAT"

Binary file not shown.

@ -0,0 +1,46 @@
#include "./server/libaquery.h"
extern "C" int dllmain(Context* cxt){
auto stocks = new TableInfo("stocks", 2);
cxt->tables.insert({"stocks", stocks});
stocks->colrefs[0].ty = types::AINT;
stocks->colrefs[1].ty = types::AINT;
auto& stocks_timestamp = *(ColRef<int> *)(&stocks->colrefs[0]);
auto& stocks_price = *(ColRef<int> *)(&stocks->colrefs[1]);
stocks_timestamp.emplace_back(1);
stocks_price.emplace_back(15);
stocks_timestamp.emplace_back(2);
stocks_price.emplace_back(19);
stocks_timestamp.emplace_back(3);
stocks_price.emplace_back(16);
stocks_timestamp.emplace_back(4);
stocks_price.emplace_back(17);
stocks_timestamp.emplace_back(5);
stocks_price.emplace_back(15);
stocks_timestamp.emplace_back(6);
stocks_price.emplace_back(13);
stocks_timestamp.emplace_back(7);
stocks_price.emplace_back(5);
stocks_timestamp.emplace_back(8);
stocks_price.emplace_back(8);
stocks_timestamp.emplace_back(9);
stocks_price.emplace_back(7);
stocks_timestamp.emplace_back(10);
stocks_price.emplace_back(13);
stocks_timestamp.emplace_back(11);
stocks_price.emplace_back(11);
stocks_timestamp.emplace_back(12);
stocks_price.emplace_back(14);
stocks_timestamp.emplace_back(13);
stocks_price.emplace_back(10);
stocks_timestamp.emplace_back(14);
stocks_price.emplace_back(5);
stocks_timestamp.emplace_back(15);
stocks_price.emplace_back(2);
stocks_timestamp.emplace_back(16);
stocks_price.emplace_back(5);
auto d2PxTIVW = (max((stocks_price-min(stocks_timestamp))));
print(d2PxTIVW);
auto d2dVVnjL = (max((stocks_price-mins(stocks_price))));
print(d2dVVnjL);
return 0;
}

@ -0,0 +1,46 @@
#include "./server/libaquery.h"
#include <cstdio>
#include <threads.h>
extern "C" int dllmain(Context *cxt)
{
auto stocks = new TableInfo<int, int>("stocks", 2);
cxt->tables.insert(std::make_pair("stocks", stocks));
stocks->colrefs[0].ty = types::AINT;
stocks->colrefs[1].ty = types::AINT;
auto &stocks_0 = *(ColRef<int> *)(&stocks->colrefs[0]);
auto &stocks_1 = *(ColRef<int> *)(&stocks->colrefs[1]);
stocks_0.emplace_back(1);
stocks_1.emplace_back(15);
stocks_0.emplace_back(2);
stocks_1.emplace_back(19);
stocks_0.emplace_back(3);
stocks_1.emplace_back(16);
stocks_0.emplace_back(4);
stocks_1.emplace_back(17);
stocks_0.emplace_back(5);
stocks_1.emplace_back(15);
stocks_0.emplace_back(6);
stocks_1.emplace_back(13);
stocks_0.emplace_back(7);
stocks_1.emplace_back(5);
stocks_0.emplace_back(8);
stocks_1.emplace_back(8);
stocks_0.emplace_back(9);
stocks_1.emplace_back(7);
stocks_0.emplace_back(10);
stocks_1.emplace_back(13);
stocks_0.emplace_back(11);
stocks_1.emplace_back(11);
stocks_0.emplace_back(12);
stocks_1.emplace_back(14);
stocks_0.emplace_back(13);
stocks_1.emplace_back(10);
stocks_0.emplace_back(14);
stocks_1.emplace_back(5);
stocks_0.emplace_back(15);
stocks_1.emplace_back(2);
stocks_0.emplace_back(16);
stocks_1.emplace_back(5);
printf("%d\n", max(stocks_0 - min(stocks_1)));
return 0;
}

@ -1,15 +1,41 @@
import re import re
import time
import aquery_parser as parser import aquery_parser as parser
import engine import engine
import subprocess import subprocess
import mmap
import sys import sys
import os
from engine.utils import base62uuid
import atexit
def rm():
files = os.listdir('.')
for f in files:
if f.endswith('.shm'):
os.remove(f)
atexit.register(rm)
shm = base62uuid()
if sys.platform != 'win32': if sys.platform != 'win32':
import readline import readline
shm += '.shm'
basecmd = ['bash', '-c', 'rlwrap k'] basecmd = ['bash', '-c', 'rlwrap k']
mm = None
if not os.path.isfile(shm):
# create initial file
with open(shm, "w+b") as handle:
handle.write(b'\x01\x00') # [running, new job]
handle.flush()
mm = mmap.mmap(handle.fileno(), 2, access=mmap.ACCESS_WRITE, offset=0)
if mm is None:
exit(1)
else: else:
basecmd = ['bash.exe', '-c', 'rlwrap ./k'] basecmd = ['bash.exe', '-c', 'rlwrap ./k']
mm = mmap.mmap(0, 2, shm)
mm.write(b'\x01\x00')
mm.flush()
subprocess.Popen(["./server.bin", shm])
test_parser = True test_parser = True
# code to test parser # code to test parser
@ -21,6 +47,19 @@ res = parser.parse(q)
print(res) print(res)
# else:f
# if subprocess.call(['make', 'snippet']) == 0:
# mm.seek(0)
# mm.write(b'\x01\x01')
# time.sleep(.1)
# mm.seek(0)
# print(mm.read(2))
# mm.close()
# handle.close()
# os.remove(shm)
# exit()
keep = False keep = False
cxt = None cxt = None
while test_parser: while test_parser:
@ -35,10 +74,12 @@ while test_parser:
engine.generate(s, cxt) engine.generate(s, cxt)
else: else:
engine.generate(stmts_stmts, cxt) engine.generate(stmts_stmts, cxt)
print(cxt.k9code) print(cxt.ccode)
with open('out.k', 'wb') as outfile: with open('out.cpp', 'wb') as outfile:
outfile.write((cxt.k9code+'\n\\\\').encode('utf-8')) outfile.write((cxt.finalize()).encode('utf-8'))
subprocess.call(basecmd[:-1] + [basecmd[-1] + ' out.k']) if subprocess.call(['make', 'snippet']) == 0:
mm.seek(0,os.SEEK_SET)
mm.write(b'\x01\x01')
continue continue
elif q == 'k': elif q == 'k':
subprocess.call(basecmd) subprocess.call(basecmd)
@ -49,6 +90,13 @@ while test_parser:
elif q == 'keep': elif q == 'keep':
keep = not keep keep = not keep
continue continue
elif q == 'exit':
break
elif q == 'r':
if subprocess.call(['make', 'snippet']) == 0:
mm.seek(0,os.SEEK_SET)
mm.write(b'\x01\x01')
continue
trimed = ws.sub(' ', q.lower()).split(' ') trimed = ws.sub(' ', q.lower()).split(' ')
if trimed[0].startswith('f'): if trimed[0].startswith('f'):
fn = 'stock.a' if len(trimed) <= 1 or len(trimed[1]) == 0 \ fn = 'stock.a' if len(trimed) <= 1 or len(trimed[1]) == 0 \
@ -63,3 +111,6 @@ while test_parser:
except (ValueError) as e: except (ValueError) as e:
print(type(e), e) print(type(e), e)
mm.close()
handle.close()
os.remove(shm)

@ -1,3 +1,6 @@
debug: debug:
g++ -g3 -O0 server/server.cpp server/table.cpp -o a.out -Wall -Wextra -Wpedantic g++ -g3 -O0 server/server.cpp server/table.cpp -o a.out -Wall -Wextra -Wpedantic -lpthread
test:
g++ --std=c++1z -g3 -O0 server.cpp table.cpp -o a.out -Wall -Wextra -Wpedantic -lpthread

@ -0,0 +1,54 @@
#pragma once
#include <vector>
#include <utility>
#include <thread>
#include <chrono>
class GC {
template<class T>
using vector = std::vector<T>;
template<class ...T>
using tuple = std::tuple<T...>;
size_t current_size, max_size, interval, forced_clean;
bool running, alive;
// ptr, dealloc, ref, sz
vector<tuple<void*, void (*)(void*), uint32_t, uint32_t>> q;
std::thread handle;
void gc()
{
}
template <class T>
void reg(T* v, uint32_t ref, uint32_t sz,
void(*f)(void*) = [](void* v) {delete[] ((T*)v); }) {
current_size += sz;
if (current_size > max_size)
gc();
q.push_back({ v, f, ref, sz });
}
void daemon() {
using namespace std::chrono;
while (alive) {
if (running) {
gc();
std::this_thread::sleep_for(microseconds(interval));
}
else {
std::this_thread::sleep_for(10ms);
}
}
}
void start_deamon() {
handle = std::thread(&daemon);
alive = true;
}
void terminate_daemon() {
running = false;
alive = false;
using namespace std::chrono;
if (handle.joinable()) {
std::this_thread::sleep_for(microseconds(1000 + std::max(static_cast<size_t>(10000), interval)));
handle.join();
}
}
};

@ -2,8 +2,9 @@
#define _AQUERY_H #define _AQUERY_H
#include "table.h" #include "table.h"
#include <unordered_map>
class Context{ struct Context{
std::unordered_map<const char*, void*> tables;
std::unordered_map<const char*, uColRef *> cols;
}; };
#endif #endif

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.210806.1" targetFramework="native" />
</packages>

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<Rule Name="CppWinRT" DisplayName="C++/WinRT" Order="75" PageTemplate="generic" xmlns="http://schemas.microsoft.com/build/2009/properties">
<Rule.Categories>
<Category Name="General" DisplayName="General"/>
</Rule.Categories>
<Rule.DataSource>
<DataSource Persistence="ProjectFile" HasConfigurationCondition="false" Label="Globals" />
</Rule.DataSource>
<StringProperty Name="RootNamespace"
DisplayName="Root Namespace"
Description="Specifies the default namespace to be used with new files created in this project."
Category="General" />
<EnumProperty Name="CppWinRTVerbosity"
DisplayName="Verbosity"
Description="Sets the importance of C++/WinRT build messages"
Category="General">
<EnumValue Name="low" DisplayName="low" Description="Enables messages when MSBuild verbosity is set to at least 'detailed'" />
<EnumValue Name="normal" DisplayName="normal" Description="Enables messages when MSBuild verbosity is set to at least 'normal'" />
<EnumValue Name="high" DisplayName="high" Description="Enables messages when MSBuild verbosity is set to at least 'minimal'" />
</EnumProperty>
<EnumProperty Name="CppWinRTProjectLanguage"
DisplayName="Project Language"
Description="Sets the C++ dialect for the project. C++/WinRT provides full projection support, C++/CX permits consuming projection headers."
Category="General">
<EnumValue Name="C++/WinRT" DisplayName="C++/WinRT" Description="Enables full consuming and producing projection support and Xaml integration" />
<EnumValue Name="C++/CX" DisplayName="C++/CX" Description="Enables C++/CX code to generate and use consuming projections" />
</EnumProperty>
<BoolProperty Name="CppWinRTLibs"
DisplayName="Umbrella Library"
Description="Adds the WindowsApp.lib umbrella library for Windows Runtime imports"
Category="General" />
<BoolProperty Name="CppWinRTModernIDL"
DisplayName="Modern IDL"
Description="Enables midlrt.exe modern IDL support (disable for custom behavior such as proxy/stub generation)"
Category="General" />
<IntProperty Name="CppWinRTNamespaceMergeDepth"
DisplayName="Namespace Merge Depth"
Description="Overrides the depth of mdmerge.exe namespace merging (Xaml apps require 1)"
Category="General" />
<BoolProperty Name="CppWinRTRootNamespaceAutoMerge"
DisplayName="Use Root Namespace Merge Depth"
Description="Use the Root Namespace as the default merge depth"
Category="General" />
<BoolProperty Name="CppWinRTUsePrefixes"
DisplayName="Use Prefixes"
Description="Uses a dotted prefix namespace convention (versus a nested folder convention)"
Category="General" />
<StringProperty Name="CppWinRTParameters"
DisplayName="Additional Parameters"
Description="Additional cppwinrt.exe command-line parameters"
Category="General" />
<BoolProperty Name="CppWinRTFastAbi"
DisplayName="Fast ABI"
Description="Enables Fast ABI feature for both consuming and producing projections"
Category="General" />
<BoolProperty Name="CppWinRTOptimized"
DisplayName="Optimized"
Description="Enables component projection optimization features (e.g., unified construction)"
Category="General" />
<BoolProperty Name="CppWinRTGenerateWindowsMetadata"
DisplayName="Generate Windows Metadata"
Description="Enables or disables the generation of Windows Metadata"
Category="General" />
<BoolProperty Name="CppWinRTEnableDefaultCopyLocalFalse"
DisplayName="Enable C++/WinRT Copy Local Defaults"
Description="Enables or disables the default for copying binaries to the output folder to be false"
Category="General" />
</Rule>

@ -0,0 +1,66 @@
<!--
***********************************************************************************************
Copyright (C) Microsoft Corporation. All rights reserved.
***********************************************************************************************
-->
<!--Set compiler and linker options for projects requiring C++/WinRT. -->
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<!-- Only do this for MSBuild versions below 16.0
as it is since done automatically, see https://github.com/microsoft/msbuild/pull/3605-->
<MSBuildAllProjects Condition="'$(MSBuildToolsVersion)' &lt;= '15'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
</PropertyGroup>
<PropertyGroup>
<PreferredToolArchitecture>x64</PreferredToolArchitecture>
<CanReferenceWinRT>true</CanReferenceWinRT>
<CppWinRTPackage Condition="'$(CppWinRTEnabled)' != 'true'">true</CppWinRTPackage>
<CppWinRTPackage Condition="'$(CppWinRTPackage)' != 'true'">false</CppWinRTPackage>
<XamlLanguage Condition="'$(XamlLanguage)' == ''">CppWinRT</XamlLanguage>
<IsNativeLanguage>true</IsNativeLanguage>
<!-- This causes VS to add the platform WinMD references for the target SDK -->
<WinMDAssembly>true</WinMDAssembly>
<!--Set a value to prevent SDK's uap.props from setting it and pointing to the wrong headers-->
<CppWinRT_IncludePath>PreventSdkUapPropsAssignment</CppWinRT_IncludePath>
<CppWinRTEnableDefaultCopyLocalFalse Condition="'$(CppWinRTEnableDefaultCopyLocalFalse)' == ''">true</CppWinRTEnableDefaultCopyLocalFalse>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<CompileAsWinRT Condition="'$(CppWinRTProjectLanguage)' != 'C++/CX' And '%(ClCompile.CompileAsWinRT)' == ''">false</CompileAsWinRT>
<LanguageStandard Condition="'%(ClCompile.LanguageStandard)' == ''">stdcpp17</LanguageStandard>
</ClCompile>
<Midl Condition="'$(CppWinRTModernIDL)' != 'false'">
<EnableWindowsRuntime>true</EnableWindowsRuntime>
<MetadataFileName>$(IntDir)Unmerged\%(Filename).winmd</MetadataFileName>
<GenerateClientFiles Condition="'%(Midl.GenerateClientFiles)'==''">None</GenerateClientFiles>
<GenerateServerFiles Condition="'%(Midl.GenerateServerFiles)'==''">None</GenerateServerFiles>
<GenerateStublessProxies Condition="'%(Midl.GenerateStublessProxies)'==''">false</GenerateStublessProxies>
<GenerateTypeLibrary Condition="'%(Midl.GenerateTypeLibrary)'==''">false</GenerateTypeLibrary>
<HeaderFileName Condition="'%(Midl.HeaderFileName)'==''">nul</HeaderFileName>
<DllDataFileName Condition="'%(Midl.DllDataFileName)'==''">nul</DllDataFileName>
<InterfaceIdentifierFileName Condition="'%(Midl.InterfaceIdentifierFileName)'==''">nul</InterfaceIdentifierFileName>
<ProxyFileName Condition="'%(Midl.ProxyFileName)'==''">nul</ProxyFileName>
<TypeLibraryName Condition="'%(Midl.TypeLibraryName)'==''"></TypeLibraryName>
</Midl>
<ProjectReference Condition="'$(XamlLanguage)' != 'C++' and '$(CppWinRTEnableDefaultCopyLocalFalse)' == 'true'">
<!-- By default, for a C++/WinRT project,
don't copy project reference output to the output directory
of the current project for projects that are not an exe. -->
<Private Condition="'$(ConfigurationType)' != 'Application' and '$(OutputType)'!='winexe' and '$(OutputType)'!='exe' and '$(OutputType)'!='appcontainerexe'">false</Private>
</ProjectReference>
<Reference Condition="'$(XamlLanguage)' != 'C++' and '$(CppWinRTEnableDefaultCopyLocalFalse)' == 'true'">
<!-- By default, for a C++/WinRT project,
don't copy reference output to the output directory
of the current project for projects that are not an exe. -->
<Private Condition="'$(ConfigurationType)' != 'Application' and '$(OutputType)'!='winexe' and '$(OutputType)'!='exe' and '$(OutputType)'!='appcontainerexe'">false</Private>
</Reference>
</ItemDefinitionGroup>
<ItemGroup>
<PropertyPageSchema Include="$(MSBuildThisFileDirectory)\CppWinrtRules.Project.xml"/>
<ProjectCapability Include="CppWinRT" />
</ItemGroup>
</Project>

@ -0,0 +1,888 @@
<!--
***********************************************************************************************
Copyright (C) Microsoft Corporation. All rights reserved.
***********************************************************************************************
-->
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<!-- Only do this for MSBuild versions below 16.0
as it is since done automatically, see https://github.com/microsoft/msbuild/pull/3605-->
<MSBuildAllProjects Condition="'$(MSBuildToolsVersion)' &lt;= '15'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
</PropertyGroup>
<PropertyGroup>
<CppWinRTVerbosity Condition="'$(CppWinRTVerbosity)' == ''">normal</CppWinRTVerbosity>
<CppWinRTCommandVerbosity Condition="'$(CppWinRTVerbosity)' == 'high'">-verbose</CppWinRTCommandVerbosity>
<CppWinRTProjectWinMD>$(OutDir)$(RootNamespace).winmd</CppWinRTProjectWinMD>
<CppWinRTMergedDir>$(IntDir)Merged\</CppWinRTMergedDir>
<CppWinRTUnmergedDir>$(IntDir)Unmerged\</CppWinRTUnmergedDir>
<CppWinRTSkipUnchangedFiles Condition="'$(CppWinRTSkipUnchangedFiles)' == ''">true</CppWinRTSkipUnchangedFiles>
<CppWinRTUseHardlinksIfPossible Condition="'$(CppWinRTUseHardlinksIfPossible)' == ''">false</CppWinRTUseHardlinksIfPossible>
<CppWinRTWriteOnlyWhenDifferent Condition="('$(CppWinRTWriteOnlyWhenDifferent)' == '') And (('$(MSBuildToolsVersion)' == 'Current') Or ('$(MSBuildToolsVersion)' &gt;= '15'))">true</CppWinRTWriteOnlyWhenDifferent>
<CppWinRTWriteOnlyWhenDifferent Condition="'$(CppWinRTWriteOnlyWhenDifferent)' != 'true'">false</CppWinRTWriteOnlyWhenDifferent>
<CppWinRTHasHashTask Condition="('$(CppWinRTHasHashTask)' == '') And (('$(MSBuildToolsVersion)' == 'Current'))">true</CppWinRTHasHashTask>
<CppWinRTHasHashTask Condition="'$(CppWinRTHasHashTask)' != 'true'">false</CppWinRTHasHashTask>
<CppWinRTPackageDir Condition="'$(CppWinRTPackage)' == 'true' and '$(CppWinRTPackageDir)'==''">$([System.IO.Path]::GetFullPath($(MSBuildThisFileDirectory)))..\..\</CppWinRTPackageDir>
<CppWinRTPackageDir Condition="'$(CppWinRTPackage)' != 'true' and '$(CppWinRTPackageDir)'==''">$([System.IO.Path]::GetFullPath($(MSBuildThisFileDirectory)))</CppWinRTPackageDir>
<CppWinRTParameters Condition="'$(CppWinRTFastAbi)'=='true'">$(CppWinRTParameters) -fastabi</CppWinRTParameters>
<CppWinRTPath Condition="'$(CppWinRTPackage)' == 'true' and '$(CppWinRTPath)'==''">"$(CppWinRTPackageDir)bin\"</CppWinRTPath>
<CppWinRTPath Condition="'$(CppWinRTPackage)' != 'true' and '$(CppWinRTPath)'==''">"$(CppWinRTPackageDir)"</CppWinRTPath>
<!-- By default enable C++/WinRT to include target platform winmds if we didn't overide sdk references and the C++ Project system isn't already adding them -->
<!-- _PrepareForReferenceResolution adds the references if TargetPlatformIdentifier is UAP -->
<CppWinRTImplicitlyExpandTargetPlatform Condition="'$(CppWinRTImplicitlyExpandTargetPlatform)' == '' and '$(CppWinRTOverrideSDKReferences)' != 'true' and '$(TargetPlatformIdentifier)' != 'UAP'">true</CppWinRTImplicitlyExpandTargetPlatform>
<XamlLanguage Condition="'$(CppWinRTProjectLanguage)' == 'C++/CX'">C++</XamlLanguage>
<XamlNamespace Condition="'$(XamlNamespace)' == ''">Windows.UI.Xaml</XamlNamespace>
<XamlMetaDataProviderIdl Condition="'$(XamlMetaDataProviderIdl)'== ''">$(GeneratedFilesDir)XamlMetaDataProvider.idl</XamlMetaDataProviderIdl>
<XamlMetaDataProviderCpp Condition="'$(XamlMetaDataProviderCpp)'== ''">$(GeneratedFilesDir)XamlMetaDataProvider.cpp</XamlMetaDataProviderCpp>
<CppWinRTMdMergeResponseFile Condition="'$(CppWinRTMdMergeResponseFile)'==''">$(IntDir)$(MSBuildProjectFile).mdmerge.rsp</CppWinRTMdMergeResponseFile>
<CppWinRTMidlResponseFile Condition="'$(CppWinRTMidlResponseFile)'==''">$(IntDir)$(MSBuildProjectFile).midlrt.rsp</CppWinRTMidlResponseFile>
<CppWinRTPlatformProjectionResponseFile Condition="'$(CppWinRTPlatformProjectionResponseFile)'==''">$(IntDir)$(MSBuildProjectFile).cppwinrt_plat.rsp</CppWinRTPlatformProjectionResponseFile>
<CppWinRTReferenceProjectionResponseFile Condition="'$(CppWinRTReferenceProjectionResponseFile)'==''">$(IntDir)$(MSBuildProjectFile).cppwinrt_ref.rsp</CppWinRTReferenceProjectionResponseFile>
<CppWinRTComponentProjectionResponseFile Condition="'$(CppWinRTComponentProjectionResponseFile)'==''">$(IntDir)$(MSBuildProjectFile).cppwinrt_comp.rsp</CppWinRTComponentProjectionResponseFile>
<!-- For CX projects, CppWinRT will never output a winmd-->
<!-- NOTE: We don't set a default here as the default requires evaluation of project references
and this is done by the CppWinRTComputeGenerateWindowsMetadata target. -->
<CppWinRTGenerateWindowsMetadata Condition="'$(CppWinRTGenerateWindowsMetadata)' == '' AND '$(XamlLanguage)' == 'C++' ">false</CppWinRTGenerateWindowsMetadata>
<!-- For CX projects, turn off the component projection generation-->
<CppWinRTEnableComponentProjection Condition="'$(CppWinRTEnableComponentProjection)' == '' AND '$(XamlLanguage)' == 'C++' ">false</CppWinRTEnableComponentProjection>
<CppWinRTEnableComponentProjection Condition="'$(CppWinRTEnableComponentProjection)' == ''">true</CppWinRTEnableComponentProjection>
<CppWinRTEnablePlatformProjection Condition="'$(CppWinRTEnablePlatformProjection)' == ''">true</CppWinRTEnablePlatformProjection>
<CppWinRTEnableReferenceProjection Condition="'$(CppWinRTEnableReferenceProjection)' == ''">true</CppWinRTEnableReferenceProjection>
<GeneratedFilesDir Condition="'$(GeneratedFilesDir)' == ''">$(IntDir)Generated Files\</GeneratedFilesDir>
<!--Override SDK's uap.props setting to ensure version-matched headers-->
<CppWinRT_IncludePath>$(GeneratedFilesDir)</CppWinRT_IncludePath>
<!--TEMP: Override NuGet SDK's erroneous setting in uap.props -->
<WindowsSDK_MetadataFoundationPath Condition="('$(WindowsSDK_MetadataFoundationPath)'!='') And !Exists($(WindowsSDK_MetadataFoundationPath))">$(WindowsSDK_MetadataPathVersioned)</WindowsSDK_MetadataFoundationPath>
<!-- CAExcludePath is used to set an environment variable, so make sure this is defined on a single line. -->
<CAExcludePath>$(GeneratedFilesDir);$(CAExcludePath)</CAExcludePath>
<PrepareForBuildDependsOn>
$(PrepareForBuildDependsOn);
CppWinRTVerifyKitVersion;
</PrepareForBuildDependsOn>
<!-- Note: Before* targets run before Compute* targets. -->
<BeforeMidlCompileTargets>
$(BeforeMidlCompileTargets);CppWinRTAddXamlMetaDataProviderIdl;
</BeforeMidlCompileTargets>
<ComputeMidlInputsTargets>
$(ComputeMidlInputsTargets);CppWinRTComputeXamlGeneratedMidlInputs;CppWinRTSetMidlReferences;
</ComputeMidlInputsTargets>
<AfterMidlTargets>
$(AfterMidlTargets);
GetCppWinRTMdMergeInputs;
CppWinRTMergeProjectWinMDInputs;
CppWinRTGetResolvedWinMD;
CppWinRTCopyWinMDToOutputDirectory;
</AfterMidlTargets>
<ResolveReferencesDependsOn>
$(ResolveReferencesDependsOn);
CppWinRTImplicitlyExpandTargetPlatform
</ResolveReferencesDependsOn>
<ResolveAssemblyReferencesDependsOn>
$(ResolveAssemblyReferencesDependsOn);GetCppWinRTProjectWinMDReferences;CppWinRTMarkStaticLibrariesPrivate;
</ResolveAssemblyReferencesDependsOn>
<!-- Note: Before* targets run before Compute* targets. -->
<BeforeClCompileTargets>
$(BeforeClCompileTargets);CppWinRTAddXamlMetaDataProviderCpp;CppWinRTMakeProjections;
</BeforeClCompileTargets>
<!-- Ensure ComputeCompileInputsTargets runs at the end so that FixupCLCompileOptions is the last to run -->
<ComputeCompileInputsTargets>
CppWinRTComputeXamlGeneratedCompileInputs;$(ComputeCompileInputsTargets);CppWinRTHeapEnforcementOptOut;
</ComputeCompileInputsTargets>
<MarkupCompilePass1DependsOn>
$(MarkupCompilePass1DependsOn);CppWinRTAddXamlReferences
</MarkupCompilePass1DependsOn>
<MarkupCompilePass2DependsOn>
$(MarkupCompilePass2DependsOn);CppWinRTSetXamlLocalAssembly
</MarkupCompilePass2DependsOn>
<CleanDependsOn>
$(CleanDependsOn);CppWinRTClean
</CleanDependsOn>
<GetTargetPathDependsOn>
$(GetTargetPathDependsOn);CppWinRTGetResolvedWinMD
</GetTargetPathDependsOn>
<GetPackagingOutputsDependsOn>
$(GetPackagingOutputsDependsOn);CppWinRTGetResolvedWinMD
</GetPackagingOutputsDependsOn>
</PropertyGroup>
<!-- For a static library we don't want the winmd/lib/pdb to be packaged -->
<PropertyGroup Condition="'$(ConfigurationType)' == 'StaticLibrary'">
<IncludeCopyWinMDArtifactsOutputGroup>false</IncludeCopyWinMDArtifactsOutputGroup>
</PropertyGroup>
<Target Name="CppWinRTVerifyKitVersion" Condition="'$(CppWinRTOverrideSDKReferences)' != 'true'">
<PropertyGroup>
<_CppWinRT_RS4OrGreater>false</_CppWinRT_RS4OrGreater>
<_CppWinRT_RS4OrGreater Condition="'$(TargetPlatformVersion)' &gt;= '10.0.17134.0'">true</_CppWinRT_RS4OrGreater>
</PropertyGroup>
<VCMessage Code="MSB8036" Type="Error" Arguments="10.0.17134.0 (or later)" Condition="$(_CppWinRT_RS4OrGreater) != 'true'" />
</Target>
<Target Name="CppWinRTClean">
<ItemGroup>
<_FilesToDelete Remove="@(_FilesToDelete)"/>
<_FilesToDelete Include="$(GeneratedFilesDir)**"/>
<_FilesToDelete Include="$(CppWinRTMergedDir)**"/>
<_FilesToDelete Include="$(CppWinRTUnmergedDir)**"/>
<_FilesToDelete Include="$(CppWinRTProjectWinMD)"/>
</ItemGroup>
<Delete Files="@(_FilesToDelete)"/>
</Target>
<Target Name="CppWinRTHeapEnforcementOptOut" Condition="'@(ClCompile)' != ''">
<ItemGroup Condition="'$(CppWinRTHeapEnforcement)'=='' and ('@(Page)' != '' Or '@(ApplicationDefinition)' != '')">
<ClCompile>
<AdditionalOptions>%(ClCompile.AdditionalOptions) /DWINRT_NO_MAKE_DETECTION</AdditionalOptions>
</ClCompile>
</ItemGroup>
</Target>
<!--
The CppWinRTImplicitlyExpandTargetPlatform target will find the
appropriate platform in the requested SDK, gather the
list of references for that platform, and add them to the
ReferencePath item which is the ItemGroup which contains
resolved paths to pass to e.g. the compiler.
Xaml targets do this for UWP but for desktop,
apps can't opt-in to WinRT doing it for them.
-->
<Target Name="CppWinRTImplicitlyExpandTargetPlatform"
Condition="'$(CppWinRTImplicitlyExpandTargetPlatform)' == 'true'">
<ItemGroup>
<_TargetPlatformWinMDs Condition="'$(TargetPlatformSdkRootOverride)' != ''" Include="$(TargetPlatformSdkRootOverride)\References\$(XeWin10TargetVersion)\**\*.winmd">
<WinMDFile>true</WinMDFile>
<CopyLocal>false</CopyLocal>
<ReferenceGrouping>$(TargetPlatformMoniker)</ReferenceGrouping>
<ReferenceGroupingDisplayName>$(TargetPlatformDisplayName)</ReferenceGroupingDisplayName>
<ResolvedFrom>CppWinRTImplicitlyExpandTargetPlatform</ResolvedFrom>
<IsSystemReference>True</IsSystemReference>
</_TargetPlatformWinMDs>
<_TargetPlatformWinMDs Condition="'$(TargetPlatformSdkRootOverride)' == ''" Include="$(WindowsSDK_MetadataPathVersioned)\**\*.winmd">
<WinMDFile>true</WinMDFile>
<CopyLocal>false</CopyLocal>
<ReferenceGrouping>$(TargetPlatformMoniker)</ReferenceGrouping>
<ReferenceGroupingDisplayName>$(TargetPlatformDisplayName)</ReferenceGroupingDisplayName>
<ResolvedFrom>CppWinRTImplicitlyExpandTargetPlatform</ResolvedFrom>
<IsSystemReference>True</IsSystemReference>
</_TargetPlatformWinMDs>
</ItemGroup>
<Warning Condition="'@(_TargetPlatformWinMDs)' == ''"
Text="Could not find target platform winmds for the SDK specified by [$(SDKIdentifier), $(SDKVersion), $(TargetPlatformIdentifier), $(TargetPlatformMinVersion), $(TargetPlatformVersion)]"/>
<Message Importance="Low" Text="Including @(_TargetPlatformWinMDs)" />
<ItemGroup>
<ReferencePath Include="@(_TargetPlatformWinMDs)" />
<_ResolveAssemblyReferenceResolvedFiles Include="@(_TargetPlatformWinMDs)" />
<!-- Clear out 'temporary' variable -->
<_TargetPlatformWinMDs Remove="@(_TargetPlatformWinMDs)" />
</ItemGroup>
</Target>
<!-- Target used only to evaluate CppWinRTGenerateWindowsMetadata if it doesn't already have a value -->
<Target Name="CppWinRTComputeGenerateWindowsMetadata"
DependsOnTargets="CppWinRTComputeXamlGeneratedMidlInputs;GetCppWinRTProjectWinMDReferences;$(CppWinRTComputeGenerateWindowsMetadataDependsOn)">
<PropertyGroup>
<!-- For static libraries, only idl causes a winmd to be generated.
For exe/dll, static libraries that produce a WinMD will be merged,
so they also cause a WinMD to be generated-->
<CppWinRTGenerateWindowsMetadata Condition="'$(ConfigurationType)' != 'StaticLibrary' AND '@(CppWinRTStaticProjectWinMDReferences)@(Midl)'!= ''">true</CppWinRTGenerateWindowsMetadata>
<CppWinRTGenerateWindowsMetadata Condition="'$(ConfigurationType)' == 'StaticLibrary' AND '@(Midl)'!= ''">true</CppWinRTGenerateWindowsMetadata>
<!-- At this point we checked all cases where we do generate a WinMD.
The remaining option is no WinMD. -->
<CppWinRTGenerateWindowsMetadata Condition="'$(CppWinRTGenerateWindowsMetadata)'== ''">false</CppWinRTGenerateWindowsMetadata>
</PropertyGroup>
</Target>
<Target Name="CppWinRTComputeGetResolvedWinMD"
Condition="'$(CppWinRTGenerateWindowsMetadata)' == ''">
<!-- If CppWinRTGenerateWindowsMetadata is not defined, compute it.-->
<!-- We use Calltarget, so we don't run anything including DependsOnTargets
targets if $(CppWinRTGenerateWindowsMetadata) already has a value.-->
<CallTarget Targets="CppWinRTComputeGenerateWindowsMetadata" />
</Target>
<!-- This target hooks into the GetResolvedWinMD target used to resolve the WinMD for native projects
so it is aware of the C++/WinRT generated WinMD.
There is no good way to hook GetResolvedWinMD so we use BeforeTargets. -->
<Target Name="CppWinRTGetResolvedWinMD"
DependsOnTargets="CppWinRTComputeGetResolvedWinMD"
BeforeTargets="GetResolvedWinMD"
Returns="@(WinMDFullPath)">
<!-- Add C++/WinRT primary WinMD to the WinMDFullPath if CppWinRTGenerateWindowsMetadata is true -->
<ItemGroup>
<!-- Create ItemGroup to evaluate FullPath -->
<_CppWinRTProjectWinMDItems Include="$(CppWinRTProjectWinMD)" />
<WinMDFullPath Include="@(_CppWinRTProjectWinMDItems->FullPath()->Distinct()->ClearMetadata())" Condition="'$(CppWinRTGenerateWindowsMetadata)' == 'true'">
<TargetPath>$([System.IO.Path]::GetFileName('$(CppWinRTProjectWinMD)'))</TargetPath>
<Primary>true</Primary>
<Implementation Condition="'$(TargetExt)' == '.dll' or '$(TargetExt)' == '.exe'">$(WinMDImplementationPath)$(TargetName)$(TargetExt)</Implementation>
<FileType>winmd</FileType>
<WinMDFile>true</WinMDFile>
<ProjectName>$(MSBuildProjectName)</ProjectName>
<ProjectType>$(ConfigurationType)</ProjectType>
</WinMDFullPath>
<_CppWinRTProjectWinMDItems Remove="$(CppWinRTProjectWinMD)" />
</ItemGroup>
<Message Text="GetResolvedWinMD: @(WinMDFullPath->'%(FullPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!-- Static library reference WinMDs are merged into the project WinMD that
references it and might have the same name because they often share namespace.
Therefore they shouldn't be copied to the output folder
because they might override files in the output folder with the
same name, causing missing types. -->
<Target Name="CppWinRTMarkStaticLibrariesPrivate"
DependsOnTargets="ResolveProjectReferences"
Returns="@(_ResolvedProjectReferencePaths)">
<ItemGroup>
<_ResolvedProjectReferencePaths Condition="'%(_ResolvedProjectReferencePaths.ProjectType)' == 'StaticLibrary'">
<Private>false</Private>
</_ResolvedProjectReferencePaths>
</ItemGroup>
</Target>
<!--Define platform projection WinMD inputs-->
<Target Name="GetCppWinRTPlatformWinMDInputs"
DependsOnTargets="ResolveAssemblyReferences;GetCppWinRTPlatformWinMDReferences"
Returns="@(CppWinRTPlatformWinMDInputs)">
<ItemGroup>
<_CppWinRTPlatformWinMDInputs Remove="@(_CppWinRTPlatformWinMDInputs)" />
<_CppWinRTPlatformWinMDInputs Include="@(CppWinRTPlatformWinMDReferences)" />
<CppWinRTPlatformWinMDInputs Include="@(_CppWinRTPlatformWinMDInputs)">
<WinMDPath>%(FullPath)</WinMDPath>
</CppWinRTPlatformWinMDInputs>
</ItemGroup>
<Message Text="CppWinRTPlatformWinMDInputs: @(CppWinRTPlatformWinMDInputs->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!--Define platform WinMD references for modern IDL compilation-->
<Target Name="GetCppWinRTPlatformWinMDReferences"
DependsOnTargets="ResolveAssemblyReferences;$(GetCppWinRTPlatformWinMDReferencesDependsOn)"
Returns="@(CppWinRTPlatformWinMDReferences)">
<ItemGroup>
<_CppWinRTPlatformWinMDReferences Remove="@(_CppWinRTPlatformWinMDReferences)" />
<_CppWinRTPlatformWinMDReferences Include="@(ReferencePath)" Condition="'%(ReferencePath.IsSystemReference)' == 'true' and '%(ReferencePath.WinMDFile)' == 'true' and '%(ReferencePath.ReferenceSourceTarget)' == 'ResolveAssemblyReference'" />
<!-- Also include the winmds from the ImplicitlyExpandTargetPlatform target if it is enabled. -->
<_CppWinRTPlatformWinMDReferences Include="@(ReferencePath)" Condition="'%(ReferencePath.IsSystemReference)' == 'true' and '%(ReferencePath.WinMDFile)' == 'true' and '%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandTargetPlatform'" />
<!-- Also include the winmds from the CppWinRTImplicitlyExpandTargetPlatform target if it is enabled. -->
<_CppWinRTPlatformWinMDReferences Include="@(ReferencePath)" Condition="'%(ReferencePath.IsSystemReference)' == 'true' and '%(ReferencePath.WinMDFile)' == 'true' and '%(ReferencePath.ResolvedFrom)' == 'CppWinRTImplicitlyExpandTargetPlatform'" />
<_CppWinRTPlatformWinMDReferences Include="$(CppWinRTSDKReferences)" />
<CppWinRTPlatformWinMDReferences Remove="@(CppWinRTPlatformWinMDReferences)"/>
<CppWinRTPlatformWinMDReferences Include="@(_CppWinRTPlatformWinMDReferences->'%(FullPath)'->Distinct())">
<WinMDPath>%(FullPath)</WinMDPath>
</CppWinRTPlatformWinMDReferences>
</ItemGroup>
<Message Text="CppWinRTPlatformWinMDReferences: @(CppWinRTPlatformWinMDReferences->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!--Get direct WinMD references (including Nuget packages) for projections, IDL processing, and AppX packaging-->
<Target Name="GetCppWinRTDirectWinMDReferences"
DependsOnTargets="ExpandSDKReferences;ResolveAssemblyReferences;$(GetCppWinRTDirectWinMDReferencesDependsOn)"
Returns="@(CppWinRTDirectWinMDReferences)">
<ItemGroup>
<_CppWinRTDirectWinMDReferences Remove="@(_CppWinRTDirectWinMDReferences)" />
<_CppWinRTDirectWinMDReferences Include="@(ReferencePath)" Condition="'%(ReferencePath.IsSystemReference)' != 'true' and '%(ReferencePath.WinMDFile)' == 'true' and '%(ReferencePath.ReferenceSourceTarget)' == 'ResolveAssemblyReference'" />
<_CppWinRTDirectWinMDReferences Include="@(ReferencePath)" Condition="'%(ReferencePath.WinMDFile)' == 'true' and '%(ReferencePath.ReferenceSourceTarget)' == 'ExpandSDKReference'" />
<CppWinRTDirectWinMDReferences Remove="@(CppWinRTDirectWinMDReferences)"/>
<CppWinRTDirectWinMDReferences Include="@(_CppWinRTDirectWinMDReferences)">
<WinMDPath>%(FullPath)</WinMDPath>
</CppWinRTDirectWinMDReferences>
</ItemGroup>
<Message Text="CppWinRTDirectWinMDReferences: @(CppWinRTDirectWinMDReferences->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!--Get direct WinMD project references for projections, IDL processing, and AppX packaging-->
<Target Name="GetCppWinRTProjectWinMDReferences"
DependsOnTargets="ResolveProjectReferences;$(GetCppWinRTProjectWinMDReferencesDependsOn)"
Returns="@(CppWinRTStaticProjectWinMDReferences);@(CppWinRTDynamicProjectWinMDReferences)">
<ItemGroup>
<!-- Get static library project references -->
<_CppWinRTStaticProjectReferences Remove="@(_CppWinRTStaticProjectReferences)"/>
<_CppWinRTStaticProjectReferences Include="@(_ResolvedProjectReferencePaths)"
Condition= "'%(_ResolvedProjectReferencePaths.ProjectType)'=='StaticLibrary' AND
'%(_ResolvedProjectReferencePaths.WinMDFile)' == 'true'"/>
<!--Get dynamic library project references-->
<_CppWinRTDynamicProjectReferences Remove="@(_CppWinRTDynamicProjectReferences)"/>
<_CppWinRTDynamicProjectReferences Include="@(_ResolvedProjectReferencePaths)"
Condition= "'%(_ResolvedProjectReferencePaths.ProjectType)'!='StaticLibrary' AND
('%(_ResolvedProjectReferencePaths.WinMDFile)' == 'true' OR
('%(_ResolvedProjectReferencePaths.WinMDFile)' == '' AND '%(_ResolvedProjectReferencePaths.Extension)' == '.winmd'))"/>
</ItemGroup>
<ItemGroup>
<CppWinRTStaticProjectWinMDReferences Remove="@(CppWinRTStaticProjectWinMDReferences)" />
<CppWinRTStaticProjectWinMDReferences Include="@(_CppWinRTStaticProjectReferences)">
<WinMDPath>%(FullPath)</WinMDPath>
</CppWinRTStaticProjectWinMDReferences>
<CppWinRTDynamicProjectWinMDReferences Remove="@(CppWinRTDynamicProjectWinMDReferences)" />
<CppWinRTDynamicProjectWinMDReferences Include="@(_CppWinRTDynamicProjectReferences)">
<WinMDPath>%(FullPath)</WinMDPath>
</CppWinRTDynamicProjectWinMDReferences>
</ItemGroup>
<Message Text="CppWinRTStaticProjectWinMDReferences: @(CppWinRTStaticProjectWinMDReferences->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
<Message Text="CppWinRTDynamicProjectWinMDReferences: @(CppWinRTDynamicProjectWinMDReferences->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<Target Name="CppWinRTResolveReferences" DependsOnTargets="GetCppWinRTPlatformWinMDReferences;GetCppWinRTDirectWinMDReferences;GetCppWinRTProjectWinMDReferences;$(CppWinRTResolveReferencesDependsOn)" />
<!-- Calculates the input files and metadata directories to be passed to MdMerge -->
<Target Name="GetCppWinRTMdMergeInputs"
DependsOnTargets="CppWinRTComputeXamlGeneratedMidlInputs;CppWinRTResolveReferences;"
Returns="@(CppWinRTMdMergeMetadataDirectories);@(CppWinRTMdMergeInputs)">
<ItemGroup>
<_MdMergeInputs Remove="@(_MdMergeInputs)"/>
<_MdMergeInputs Include="@(Midl)">
<WinMDPath>%(Midl.OutputDirectory)%(Midl.MetadataFileName)</WinMDPath>
<MdMergeOutputFile>$(CppWinRTProjectWinMD)</MdMergeOutputFile>
</_MdMergeInputs>
<!-- Static libraries don't mdmerge other static libraries.
Instead they are passed as independent inputs for the component projection. -->
<_MdMergeInputs Include="@(CppWinRTStaticProjectWinMDReferences)" Condition="'$(ConfigurationType)' != 'StaticLibrary'">
<MdMergeOutputFile>$(CppWinRTProjectWinMD)</MdMergeOutputFile>
</_MdMergeInputs>
<_MdMergeReferences Remove="@(_MdMergeReferences)" />
<!-- Static libraries don't mdmerge other static libraries.
They are however used as references so idl can reference classes from other libs. -->
<_MdMergeReferences Include="@(CppWinRTStaticProjectWinMDReferences)" Condition="'$(ConfigurationType)' == 'StaticLibrary'" />
<_MdMergeReferences Include="@(CppWinRTDirectWinMDReferences)" />
<_MdMergeReferences Include="@(CppWinRTDynamicProjectWinMDReferences)" />
<_MdMergeReferences Include="@(CppWinRTPlatformWinMDReferences)" />
<CppWinRTMdMergeMetadataDirectories Remove="@(CppWinRTMdMergeMetadataDirectories)" />
<CppWinRTMdMergeMetadataDirectories Include="@(_MdMergeReferences->'%(RelativeDir)'->Distinct())" />
<CppWinRTMdMergeInputs Remove="@(CppWinRTMdMergeInputs)" />
<CppWinRTMdMergeInputs Include="@(_MdMergeInputs->'%(WinMDPath)'->Distinct())" />
</ItemGroup>
<Message Text="CppWinRTMdMergeInputs: @(CppWinRTMdMergeInputs)" Importance="$(CppWinRTVerbosity)"/>
<Message Text="CppWinRTMdMergeMetadataDirectories: @(CppWinRTMdMergeMetadataDirectories)" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!-- Adds the XamlMetadataProvider idl to the Midl itemgroup, if building any xaml content -->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTComputeXamlGeneratedMidlInputs"
DependsOnTargets="$(CppWinRTComputeXamlGeneratedMidlInputsDependsOn)"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT' and '$(CppWinRTAddXamlMetaDataProviderIdl)' == 'true'">
<PropertyGroup>
<_DisableReferences>false</_DisableReferences>
<_DisableReferences Condition="('$(CppWinRTOverrideSDKReferences)' != 'true') and ('$(TargetPlatformVersion)' &lt; '10.0.18310.0')">true</_DisableReferences>
</PropertyGroup>
<ItemGroup>
<Midl Remove="$(XamlMetaDataProviderIdl)" />
<Midl Include="$(XamlMetaDataProviderIdl)">
<DisableReferences Condition="$(_DisableReferences)">>true</DisableReferences>
</Midl>
</ItemGroup>
</Target>
<!-- Adds the XamlMetadataProvider cpp to the ClCompile itemgroup, if building any xaml content -->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTComputeXamlGeneratedCompileInputs"
DependsOnTargets="$(CppWinRTComputeXamlGeneratedCompileInputsDependsOn)"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT' and '$(CppWinRTAddXamlMetaDataProviderIdl)' == 'true'">
<ItemGroup>
<ClCompile Remove="$(XamlMetaDataProviderCpp)" />
<ClCompile Include="$(XamlMetaDataProviderCpp)" Condition="'$(CppWinRTOptimized)'=='true'">
<CompilerIteration>XamlGenerated</CompilerIteration>
</ClCompile>
</ItemGroup>
</Target>
<!--If building any Xaml content, write XamlMetaDataProvider idl file -->
<Target Name="CppWinRTAddXamlMetaDataProviderIdl"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT' and '$(CppWinRTAddXamlMetaDataProviderIdl)' == 'true'">
<PropertyGroup>
<_DisableReferences>false</_DisableReferences>
<_DisableReferences Condition="('$(CppWinRTOverrideSDKReferences)' != 'true') and ('$(TargetPlatformVersion)' &lt; '10.0.18310.0')">true</_DisableReferences>
<FullXamlMetadataProviderAttribute Condition="$(XamlCodeGenerationControlFlags.Contains('FullXamlMetadataProvider'))">[$(XamlNamespace).Markup.FullXamlMetadataProvider] </FullXamlMetadataProviderAttribute>
<XamlMarkupIdlImport Condition="$(_DisableReferences)">import "$(XamlNamespace).Markup.idl"%3b</XamlMarkupIdlImport>
<XamlMetaDataProviderIdlLines>
// This file is generated by the build to support Xaml apps
$(XamlMarkupIdlImport)
namespace $(RootNamespace)
{
$(FullXamlMetadataProviderAttribute)runtimeclass XamlMetaDataProvider : [default] $(XamlNamespace).Markup.IXamlMetadataProvider
{
XamlMetaDataProvider()%3b
}
}
</XamlMetaDataProviderIdlLines>
</PropertyGroup>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(XamlMetaDataProviderIdl)" Lines="$(XamlMetaDataProviderIdlLines)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(XamlMetaDataProviderIdl)" Lines="$(XamlMetaDataProviderIdlLines)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
</Target>
<!--If building any Xaml content, write XamlMetaDataProvider cpp file -->
<Target Name="CppWinRTAddXamlMetaDataProviderCpp"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT' and '$(CppWinRTAddXamlMetaDataProviderIdl)' == 'true'">
<PropertyGroup>
<_PCH>@(ClCompile->Metadata('PrecompiledHeaderFile')->Distinct())</_PCH>
<XamlMetaDataProviderPch Condition="'$(_PCH)'!=''">#include "$(_PCH)"</XamlMetaDataProviderPch>
<XamlMetaDataProviderCppLines>
// This file is generated by the build to support Xaml apps
$(XamlMetaDataProviderPch)
#include "XamlMetaDataProvider.h"
#include "XamlMetaDataProvider.g.cpp"
</XamlMetaDataProviderCppLines>
</PropertyGroup>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(XamlMetaDataProviderCpp)" Lines="$(XamlMetaDataProviderCppLines)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(XamlMetaDataProviderCpp)" Lines="$(XamlMetaDataProviderCppLines)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
</Target>
<!--Insert Midl /references to Platform WinMDs, library reference WinMDs, and direct reference WinMDs-->
<Target Name="CppWinRTSetMidlReferences"
Condition="'$(CppWinRTModernIDL)' != 'false'"
DependsOnTargets="GetCppWinRTPlatformWinMDReferences;GetCppWinRTDirectWinMDReferences;GetCppWinRTProjectWinMDReferences;$(CppWinRTSetMidlReferencesDependsOn)"
Inputs="$(MSBuildAllProjects);@(CppWinRTDirectWinMDReferences);@(CppWinRTStaticProjectWinMDReferences);@(CppWinRTDynamicProjectWinMDReferences);@(CppWinRTPlatformWinMDReferences)"
Outputs="$(CppWinRTMidlResponseFile)">
<ItemGroup>
<_MidlReferences Remove="@(_MidlReferences)"/>
<_MidlReferences Include="@(CppWinRTDirectWinMDReferences)"/>
<_MidlReferences Include="@(CppWinRTStaticProjectWinMDReferences)"/>
<_MidlReferences Include="@(CppWinRTDynamicProjectWinMDReferences)"/>
<_MidlReferences Include="@(CppWinRTPlatformWinMDReferences)"/>
<_MidlReferencesDistinct Remove="@(_MidlReferencesDistinct)" />
<_MidlReferencesDistinct Include="@(_MidlReferences->'%(WinMDPath)'->Distinct())" />
<Midl Condition="'%(Midl.DisableReferences)'==''">
<AdditionalOptions>%(Midl.AdditionalOptions) %40"$(CppWinRTMidlResponseFile)"</AdditionalOptions>
</Midl>
</ItemGroup>
<PropertyGroup>
<_MidlrtParameters>@(_MidlReferencesDistinct->'/reference &quot;%(WinMDPath)&quot;','&#x0d;&#x0a;')</_MidlrtParameters>
</PropertyGroup>
<!-- Always write the midlrt.rsp file when the target runs, because the file is used as the output of this target. -->
<WriteLinesToFile
File="$(CppWinRTMidlResponseFile)" Lines="$(_MidlrtParameters)"
Overwrite="true" />
<Message Text="CppWinRTMidlReferences: @(_MidlReferences->'%(WinMDPath)')" Importance="$(CppWinRTVerbosity)"/>
</Target>
<!--Ctrl+F7 (selected file) midl compilation support-->
<Target Name="CppWinRTSetSelectMidlReferences" BeforeTargets="SelectMidl" DependsOnTargets="CppWinRTSetMidlReferences" />
<!--
============================================================
Generate a file used to track MdMerge dependencies between incremental build
executions. This handles cases where items are added or removed and can't
otherwise be detected with timestamp comparisons. The file contains a hash of
MdMerge inputs that are known to contribute to incremental build inconsistencies.
NOTE: this is not used when building with older MSBuild versions.
============================================================
-->
<Target Name="_CppWinRTGenerateMergeProjectWinMDDependencyCache" Condition="'$(CppWinRTHasHashTask)' == 'true'" DependsOnTargets="Midl;GetCppWinRTMdMergeInputs">
<ItemGroup>
<CustomAdditionalMdMergeInputs Include="$(IntermediateOutputPath)$(MSBuildProjectFile).MdMergeInputs.cache" />
<MdMergeCache Include="@(CppWinRTMdMergeInputs)" />
<MdMergeCache Include="@(Page)" />
<MdMergeCache Include="@(ApplicationDefinition)" />
<!-- No need to include properties here as those should be caught by having $(MSBuildAllProjects) as input to the target-->
</ItemGroup>
<Hash
ItemsToHash="@(MdMergeCache)"
IgnoreCase="$([MSBuild]::ValueOrDefault(`$(MdMergeCacheIgnoreCase)`, `true`))">
<Output TaskParameter="HashResult" PropertyName="MdMergeDependencyHash" />
</Hash>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntermediateOutputPath)$(MSBuildProjectFile).MdMergeInputs.cache" Lines="$(MdMergeDependencyHash)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntermediateOutputPath)$(MSBuildProjectFile).MdMergeInputs.cache" Lines="$(MdMergeDependencyHash)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
<ItemGroup>
<FileWrites Include="$(IntDir)$(MSBuildProjectFile).MdMergeInputs.cache" />
</ItemGroup>
</Target>
<Target Name="_CppWinRTCleanMdMergeOutputs">
<Delete Files="$(CppWinRTMdMergeResponseFile)" />
</Target>
<!--Merge project-generated WinMDs and project-referenced static library WinMDs into project WinMD-->
<Target Name="CppWinRTMergeProjectWinMDInputs"
DependsOnTargets="Midl;GetCppWinRTMdMergeInputs;_CppWinRTGenerateMergeProjectWinMDDependencyCache;$(CppWinRTMergeProjectWinMDInputsDependsOn)"
Inputs="$(MSBuildAllProjects);@(CppWinRTMdMergeInputs);@(CustomAdditionalMdMergeInputs)"
Outputs="@(_MdMergedOutput);$(CppWinRTMdMergeResponseFile)">
<PropertyGroup>
<!--Note: CppWinRTNamespaceMergeDepth supersedes CppWinRTMergeDepth-->
<_MdMergeDepth Condition="'$(CppWinRTNamespaceMergeDepth)' != ''">-n:$(CppWinRTNamespaceMergeDepth)</_MdMergeDepth>
<_MdMergeDepth Condition="'$(_MdMergeDepth)' == ''">$(CppWinRTMergeDepth)</_MdMergeDepth>
<_MdMergeDepth Condition="'$(_MdMergeDepth)' == '' And '$(CppWinRTRootNamespaceAutoMerge)' == 'true'">-n:$(RootNamespace.Split('.').length)</_MdMergeDepth>
<_MdMergeDepth Condition="'$(_MdMergeDepth)' == '' And ('@(Page)' != '' Or '@(ApplicationDefinition)' != '')">-n:1</_MdMergeDepth>
<_MdMergeCommand>$(MdMergePath)mdmerge %40"$(CppWinRTMdMergeResponseFile)"</_MdMergeCommand>
</PropertyGroup>
<PropertyGroup>
<!-- mdmerge.exe wants the folders to not have a trailing \ -->
<_MdMergeParameters Condition="'$(CppWinRTMergeNoValidate)'!='true'">-v</_MdMergeParameters>
<_MdMergeParameters>$(_MdMergeParameters) @(CppWinRTMdMergeMetadataDirectories->'-metadata_dir &quot;%(RelativeDir).&quot;', '&#x0d;&#x0a;')</_MdMergeParameters>
<_MdMergeParameters>$(_MdMergeParameters) @(CppWinRTMdMergeInputs->'-i &quot;%(Identity)&quot;', '&#x0d;&#x0a;')</_MdMergeParameters>
<_MdMergeParameters>$(_MdMergeParameters) -o &quot;$(CppWinRTMergedDir.TrimEnd('\'))&quot; -partial $(_MdMergeDepth)</_MdMergeParameters>
</PropertyGroup>
<!-- Always write the mdmerge.rsp file when the target runs, because the file is used as the output of this target. -->
<WriteLinesToFile
File="$(CppWinRTMdMergeResponseFile)" Lines="$(_MdMergeParameters)"
Overwrite="true" />
<MakeDir Directories="$(CppWinRTUnmergedDir);$(CppWinRTMergedDir)" />
<Message Text="$(_MdMergeCommand)" Importance="$(CppWinRTVerbosity)" Condition="'@(CppWinRTMdMergeInputs)' != ''" />
<!-- Only run mdmerge.exe when we actually have inputs -->
<Exec Command="$(_MdMergeCommand)" Condition="'@(CppWinRTMdMergeInputs)' != ''" />
<ItemGroup>
<_MdMergedOutput Remove="@(_MdMergedOutput)"/>
<_MdMergedOutput Include="$(CppWinRTMergedDir)*.winmd"/>
</ItemGroup>
<Message Text="CppWinRTMdMerge output: @(MdMergeOutput)" Importance="$(CppWinRTVerbosity)"/>
<!-- Clean the output file if the target failed to indicate it needs to be rebuild -->
<OnError ExecuteTargets="_CppWinRTCleanMdMergeOutputs" />
</Target>
<!-- Only copy winmd to output folder if CppWinRTGenerateWindowsMetadata is true -->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTCopyWinMDToOutputDirectory"
Condition="'$(CppWinRTGenerateWindowsMetadata)' == 'true'"
DependsOnTargets="CppWinRTMergeProjectWinMDInputs;$(CppWinRTCopyWinMDToOutputDirectoryDependsOn)"
Inputs="@(_MdMergedOutput)"
Outputs="$(CppWinRTProjectWinMD)">
<Copy UseHardlinksIfPossible="$(CppWinRTUseHardlinksIfPossible)"
SkipUnchangedFiles="$(CppWinRTSkipUnchangedFiles)"
SourceFiles="@(_MdMergedOutput)"
DestinationFiles="@(_MdMergedOutput->'$(OutDir)%(Filename)%(Extension)')" />
<ItemGroup>
<FileWrites Include="$(CppWinRTProjectWinMD)"/>
</ItemGroup>
</Target>
<!--
============================================================
Generate a file used to track C++/WinRT platform WinMD input dependencies between incremental build
executions. This handles cases where items are added or removed and can't
otherwise be detected with timestamp comparisons. The file contains a hash of
the platform winmd inputs that are known to contribute to incremental build inconsistencies.
NOTE: this is not used when building with older MSBuild versions.
============================================================
-->
<Target Name="_CppWinRTMakePlatformProjectionDependencyCache" Condition="'$(CppWinRTHasHashTask)' == 'true'" DependsOnTargets="CppWinRTResolveReferences;GetCppWinRTPlatformWinMDInputs">
<ItemGroup>
<CustomAdditionalPlatformWinMDInputs Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_plat.cache" />
<CppWinRTPlatformProjectionCache Include="@(CppWinRTPlatformWinMDInputs)" />
<!-- No need to include properties here as those should be caught by having $(MSBuildAllProjects) as input to the target-->
</ItemGroup>
<Hash
ItemsToHash="@(CppWinRTPlatformProjectionCache)"
IgnoreCase="$([MSBuild]::ValueOrDefault(`$(CppWinRTPlatformProjectionCacheIgnoreCase)`, `true`))">
<Output TaskParameter="HashResult" PropertyName="CppWinRTPlatformProjectionDependencyHash" />
</Hash>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_plat.cache"
Lines="$(CppWinRTPlatformProjectionDependencyHash)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_plat.cache"
Lines="$(CppWinRTPlatformProjectionDependencyHash)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
<ItemGroup>
<FileWrites Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_plat.cache" />
</ItemGroup>
</Target>
<Target Name="_CppWinRTCleanMakePlatformProjectionOutputs">
<Delete Files="$(CppWinRTPlatformProjectionResponseFile)" />
</Target>
<!-- Build the platform projection from the winmds that ship with the platform in the Windows SDK -->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTMakePlatformProjection"
Condition="'$(CppWinRTEnablePlatformProjection)' == 'true' AND '$(CppWinRTOverrideSDKReferences)' != 'true'"
DependsOnTargets="CppWinRTResolveReferences;GetCppWinRTPlatformWinMDInputs;_CppWinRTMakePlatformProjectionDependencyCache;$(CppWinRTMakePlatformProjectionDependsOn)"
Inputs="$(MSBuildAllProjects);@(CppWinRTPlatformWinMDInputs);@(CustomAdditionalPlatformWinMDInputs)"
Outputs="$(CppWinRTPlatformProjectionResponseFile)">
<PropertyGroup>
<CppWinRTCommand>$(CppWinRTPath)cppwinrt %40"$(CppWinRTPlatformProjectionResponseFile)"</CppWinRTCommand>
</PropertyGroup>
<ItemGroup>
<_CppwinrtInputs Remove="@(_CppwinrtInputs)"/>
<_CppwinrtInputs Include="@(CppWinRTPlatformWinMDInputs)"/>
</ItemGroup>
<PropertyGroup>
<_CppwinrtParameters>$(CppWinRTCommandVerbosity) $(CppWinRTParameters)</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) @(_CppwinrtInputs->'-in &quot;%(WinMDPath)&quot;', '&#x0d;&#x0a;')</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) -out &quot;$(GeneratedFilesDir).&quot;</_CppwinrtParameters>
</PropertyGroup>
<!-- Always write the cppwinrt_plat.rsp file when the target runs, because the file is used as the output of this target. -->
<WriteLinesToFile
File="$(CppWinRTPlatformProjectionResponseFile)" Lines="$(_CppwinrtParameters)"
Overwrite="true" />
<Message Text="$(CppWinRTCommand)" Importance="$(CppWinRTVerbosity)" Condition="'@(_CppwinrtInputs)' != ''" />
<Exec Command="$(CppWinRTCommand)" Condition="'@(_CppwinrtInputs)' != ''" />
<!-- Clean the output file if the target failed to indicate it needs to be rebuild -->
<OnError ExecuteTargets="_CppWinRTCleanMakePlatformProjectionOutputs" />
</Target>
<!--
============================================================
Generate a file used to track C++/WinRT reference WinMD input dependencies between incremental build
executions. This handles cases where items are added or removed and can't
otherwise be detected with timestamp comparisons. The file contains a hash of
the reference winmd inputs that are known to contribute to incremental build inconsistencies.
NOTE: this is not used when building with older MSBuild versions.
============================================================
-->
<Target Name="_CppWinRTMakeReferenceProjectionDependencyCache" Condition="'$(CppWinRTHasHashTask)' == 'true'" DependsOnTargets="CppWinRTResolveReferences">
<ItemGroup>
<CustomAdditionalReferenceWinMDInputs Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_ref.cache" />
<CppWinRTReferenceProjectionCache Include="@(CppWinRTDirectWinMDReferences)" />
<CppWinRTReferenceProjectionCache Include="@(CppWinRTDynamicProjectWinMDReferences)" />
<CppWinRTReferenceProjectionCache Include="@(CppWinRTPlatformWinMDReferences)" />
<!-- No need to include properties here as those should be caught by having $(MSBuildAllProjects) as input to the target-->
</ItemGroup>
<Hash
ItemsToHash="@(CppWinRTReferenceProjectionCache)"
IgnoreCase="$([MSBuild]::ValueOrDefault(`$(CppWinRTReferenceProjectionCacheIgnoreCase)`, `true`))">
<Output TaskParameter="HashResult" PropertyName="CppWinRTReferenceProjectionDependencyHash" />
</Hash>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_ref.cache"
Lines="$(CppWinRTReferenceProjectionDependencyHash)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_ref.cache"
Lines="$(CppWinRTReferenceProjectionDependencyHash)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
<ItemGroup>
<FileWrites Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_ref.cache" />
</ItemGroup>
</Target>
<Target Name="_CppWinRTCleanMakeReferenceProjectionOutputs">
<Delete Files="$(CppWinRTReferenceProjectionResponseFile)" />
</Target>
<!--Build reference projection from WinMD project references and dynamic library project references-->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTMakeReferenceProjection"
Condition="'@(CppWinRTDirectWinMDReferences)@(CppWinRTDynamicProjectWinMDReferences)' != '' AND '$(CppWinRTEnableReferenceProjection)' == 'true'"
DependsOnTargets="CppWinRTResolveReferences;_CppWinRTMakeReferenceProjectionDependencyCache;$(CppWinRTMakeReferenceProjectionDependsOn)"
Inputs="$(MSBuildAllProjects);@(CppWinRTDirectWinMDReferences);@(CppWinRTDynamicProjectWinMDReferences);@(CppWinRTPlatformWinMDReferences);@(CustomAdditionalReferenceWinMDInputs)"
Outputs="$(CppWinRTReferenceProjectionResponseFile)">
<PropertyGroup>
<CppWinRTCommand>$(CppWinRTPath)cppwinrt %40"$(CppWinRTReferenceProjectionResponseFile)"</CppWinRTCommand>
</PropertyGroup>
<ItemGroup>
<_CppwinrtRefInputs Remove="@(_CppwinrtRefInputs)"/>
<_CppwinrtRefInputs Include="@(CppWinRTDirectWinMDReferences)"/>
<_CppwinrtRefInputs Include="@(CppWinRTDynamicProjectWinMDReferences)"/>
<_CppwinrtRefRefs Remove="@(_CppwinrtRefRefs)"/>
<_CppwinrtRefRefs Include="@(CppWinRTPlatformWinMDReferences)"/>
</ItemGroup>
<PropertyGroup>
<_CppwinrtParameters>$(CppWinRTCommandVerbosity) $(CppWinRTParameters)</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) @(_CppwinrtRefInputs->'-in &quot;%(WinMDPath)&quot;', '&#x0d;&#x0a;')</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) @(_CppwinrtRefRefs->'-ref &quot;%(WinMDPath)&quot;', '&#x0d;&#x0a;')</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) -out &quot;$(GeneratedFilesDir).&quot;</_CppwinrtParameters>
</PropertyGroup>
<!-- Always write the cppwinrt_ref.rsp file when the target runs, because the file is used as the output of this target. -->
<WriteLinesToFile
File="$(CppWinRTReferenceProjectionResponseFile)" Lines="$(_CppwinrtParameters)"
Overwrite="true" />
<Message Text="$(CppWinRTCommand)" Importance="$(CppWinRTVerbosity)" Condition="'@(_CppwinrtRefInputs)' != ''" />
<Exec Command="$(CppWinRTCommand)" Condition="'@(_CppwinrtRefInputs)' != ''" />
<!-- Clean the output file if the target failed to indicate it needs to be rebuild -->
<OnError ExecuteTargets="_CppWinRTCleanMakeReferenceProjectionOutputs" />
</Target>
<!--
============================================================
Generate a file used to track C++/WinRT reference WinMD input dependencies between incremental build
executions. This handles cases where items are added or removed and can't
otherwise be detected with timestamp comparisons. The file contains a hash of
the reference winmd inputs that are known to contribute to incremental build inconsistencies.
NOTE: this is not used when building with older MSBuild versions.
============================================================
-->
<Target Name="_CppWinRTMakeComponentProjectionDependencyCache" Condition="'$(CppWinRTHasHashTask)' == 'true'" DependsOnTargets="CppWinRTResolveReferences">
<ItemGroup>
<CustomAdditionalComponentWinMDInputs Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_comp.cache" />
<CppWinRTComponentProjectionCache Include="@(CppWinRTMdMergeInputs)" />
<CppWinRTComponentProjectionCache Include="@(CppWinRTStaticProjectWinMDReferences)" />
<CppWinRTComponentProjectionCache Include="@(CppWinRTDirectWinMDReferences)"/>
<CppWinRTComponentProjectionCache Include="@(CppWinRTDynamicProjectWinMDReferences)"/>
<CppWinRTComponentProjectionCache Include="@(CppWinRTPlatformWinMDReferences)"/>
<!-- No need to include properties here as those should be caught by having $(MSBuildAllProjects) as input to the target-->
</ItemGroup>
<Hash
ItemsToHash="@(CppWinRTComponentProjectionCache)"
IgnoreCase="$([MSBuild]::ValueOrDefault(`$(CppWinRTComponentProjectionCacheIgnoreCase)`, `true`))">
<Output TaskParameter="HashResult" PropertyName="CppWinRTComponentProjectionDependencyHash" />
</Hash>
<WriteLinesToFile Condition="!$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_comp.cache"
Lines="$(CppWinRTComponentProjectionDependencyHash)"
Overwrite="true" />
<WriteLinesToFile Condition="$(CppWinRTWriteOnlyWhenDifferent)"
File="$(IntDir)$(MSBuildProjectFile).cppwinrt_comp.cache"
Lines="$(CppWinRTComponentProjectionDependencyHash)"
Overwrite="true"
WriteOnlyWhenDifferent="true" />
<ItemGroup>
<FileWrites Include="$(IntDir)$(MSBuildProjectFile).cppwinrt_comp.cache" />
</ItemGroup>
</Target>
<Target Name="_CppWinRTCleanMakeComponentProjectionOutputs">
<Delete Files="$(CppWinRTComponentProjectionResponseFile)" />
</Target>
<!--Build component projection from project WinMD file and static library project references-->
<!-- Note that Condition is evaluated before DependsOnTargets are run -->
<Target Name="CppWinRTMakeComponentProjection"
Condition="'$(CppWinRTEnableComponentProjection)' == 'true'"
DependsOnTargets="CppWinRTResolveReferences;GetCppWinRTMdMergeInputs;_CppWinRTMakeComponentProjectionDependencyCache;$(CppWinRTMakeComponentProjectionDependsOn)"
Inputs="$(MSBuildAllProjects);@(CppWinRTMdMergeInputs);@(CppWinRTStaticProjectWinMDReferences);@(CustomAdditionalComponentWinMDInputs)"
Outputs="$(CppWinRTComponentProjectionResponseFile)">
<PropertyGroup>
<_PCH>@(ClCompile->Metadata('PrecompiledHeaderFile')->Distinct())</_PCH>
</PropertyGroup>
<Error Condition="('$(CppWinRTOverrideSDKReferences)' != 'true') and ('$(TargetPlatformVersion)' &lt; '10.0.17709.0') and ('$(_PCH)' != 'pch.h')"
Text="Please retarget to 10.0.17709.0 or later, or rename your PCH to 'pch.h'."/>
<PropertyGroup Condition="('$(CppWinRTOverrideSDKReferences)' == 'true') or ('$(TargetPlatformVersion)' &gt; '10.0.17708.0')">
<CppWinRTUsePrefixes Condition="'$(CppWinRTUsePrefixes)' == ''">true</CppWinRTUsePrefixes>
<CppWinRTPrecompiledHeader Condition="'$(CppWinRTPrecompiledHeader)' == ''">$(_PCH)</CppWinRTPrecompiledHeader>
</PropertyGroup>
<PropertyGroup>
<CppWinRTCommandUsePrefixes Condition="'$(CppWinRTUsePrefixes)' == 'true'">-prefix</CppWinRTCommandUsePrefixes>
<CppWinRTCommandPrecompiledHeader Condition="'$(CppWinRTPrecompiledHeader)' != ''">-pch $(CppWinRTPrecompiledHeader)</CppWinRTCommandPrecompiledHeader>
<CppWinRTCommand>$(CppWinRTPath)cppwinrt %40"$(CppWinRTComponentProjectionResponseFile)"</CppWinRTCommand>
</PropertyGroup>
<ItemGroup>
<!-- use the output from MdMerge directly to generate the component projection. -->
<_MdMergedOutput Remove="@(_MdMergedOutput)"/>
<_MdMergedOutput Include="$(CppWinRTMergedDir)*.winmd"/>
<_CppwinrtCompInputs Remove="@(_CppwinrtCompInputs)"/>
<_CppwinrtCompInputs Include="@(_MdMergedOutput)">
<WinMDPath>%(_MdMergedOutput.FullPath)</WinMDPath>
</_CppwinrtCompInputs>
<!-- If this is a static library with static library references,
pass the individual static library references to cppwinrt.exe
for the component projection as they are not merged.-->
<_CppwinrtCompInputs Include="@(CppWinRTStaticProjectWinMDReferences)" Condition="'$(ConfigurationType)' == 'StaticLibrary'">
<WinMDPath>%(CppWinRTStaticProjectWinMDReferences.FullPath)</WinMDPath>
</_CppwinrtCompInputs>
<_CppwinrtCompRefs Remove="@(_CppwinrtCompRefs)"/>
<_CppwinrtCompRefs Include="@(CppWinRTDirectWinMDReferences)"/>
<_CppwinrtCompRefs Include="@(CppWinRTDynamicProjectWinMDReferences)"/>
<_CppwinrtCompRefs Include="@(CppWinRTPlatformWinMDReferences)"/>
</ItemGroup>
<PropertyGroup>
<_CppwinrtParameters>$(CppWinRTCommandVerbosity) $(CppWinRTParameters) -overwrite -name $(RootNamespace) $(CppWinRTCommandPrecompiledHeader) $(CppWinRTCommandUsePrefixes) -comp &quot;$(GeneratedFilesDir)sources&quot;</_CppwinrtParameters>
<_CppwinrtParameters Condition="'$(CppWinRTOptimized)'=='true'">$(_CppwinrtParameters) -opt</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) @(_CppwinrtCompInputs->'-in &quot;%(WinMDPath)&quot;', '&#x0d;&#x0a;')</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) @(_CppwinrtCompRefs->'-ref &quot;%(WinMDPath)&quot;', '&#x0d;&#x0a;')</_CppwinrtParameters>
<_CppwinrtParameters>$(_CppwinrtParameters) -out &quot;$(GeneratedFilesDir).&quot;</_CppwinrtParameters>
</PropertyGroup>
<!-- Always write the cppwinrt_comp.rsp file when the target runs, because the file is used as the output of this target. -->
<WriteLinesToFile
File="$(CppWinRTComponentProjectionResponseFile)" Lines="$(_CppwinrtParameters)"
Overwrite="true" />
<Message Text="$(CppWinRTCommand)" Importance="$(CppWinRTVerbosity)" Condition="'@(_CppwinrtCompInputs)' != ''"/>
<Exec Command="$(CppWinRTCommand)" Condition="'@(_CppwinrtCompInputs)' != ''"/>
<!-- Clean the output file if the target failed to indicate it needs to be rebuild -->
<OnError ExecuteTargets="_CppWinRTCleanMakeComponentProjectionOutputs" />
</Target>
<Target Name="CppWinRTMakeProjections" DependsOnTargets="CppWinRTResolveReferences;CppWinRTMakePlatformProjection;CppWinRTMakeReferenceProjection;CppWinRTMakeComponentProjection;$(CppWinRTMakeProjectionsDependsOn)" />
<!--Add references to all merged project WinMD files for Xaml Compiler-->
<Target Name="CppWinRTAddXamlReferences"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT'"
DependsOnTargets="$(CppWinRTAddXamlReferencesDependsOn)">
<ItemGroup>
<XamlReferencesToCompile Include="$(OutDir)*.winmd" />
</ItemGroup>
</Target>
<!--Clear merged assembly and set local assembly for Xaml Compiler.
(Note: this can be removed when CppWinRT references are removed from the Xaml targets file.)-->
<Target Name="CppWinRTSetXamlLocalAssembly"
Condition="'@(Page)@(ApplicationDefinition)' != '' and '$(XamlLanguage)' == 'CppWinRT'"
DependsOnTargets="$(CppWinRTSetXamlLocalAssemblyDependsOn)">
<PropertyGroup>
<CppWinRTMetadataAssembly></CppWinRTMetadataAssembly>
<XamlLocalAssembly>$(CppWinRTProjectWinMD)</XamlLocalAssembly>
</PropertyGroup>
</Target>
<!--Append any additional item metadata after all default and project settings have been applied-->
<ItemDefinitionGroup>
<ClCompile>
<AdditionalOptions>%(AdditionalOptions) /bigobj</AdditionalOptions>
<AdditionalOptions Condition="'%(ClCompile.LanguageStandard)' == 'stdcpp17'">%(AdditionalOptions) /await</AdditionalOptions>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(GeneratedFilesDir)</AdditionalIncludeDirectories>
</ClCompile>
<Midl Condition="'$(CppWinRTModernIDL)' != 'false'">
<AdditionalMetadataDirectories Condition="'%(AdditionalMetadataDirectories)' == '' And '$(WindowsSDK_MetadataFoundationPath)' != ''">$(WindowsSDK_MetadataFoundationPath);%(AdditionalMetadataDirectories)</AdditionalMetadataDirectories>
<AdditionalMetadataDirectories Condition="'%(AdditionalMetadataDirectories)' == '' And '$(WindowsSDK_MetadataFoundationPath)' == ''">$(WindowsSDK_MetadataPath);%(AdditionalMetadataDirectories)</AdditionalMetadataDirectories>
<AdditionalOptions>%(AdditionalOptions) /nomidl</AdditionalOptions>
</Midl>
<Link>
<AdditionalDependencies Condition="'$(CppWinRTLibs)' != 'false'">%(AdditionalDependencies);WindowsApp.lib</AdditionalDependencies>
<AdditionalDependencies Condition="'$(CppWinRTFastAbi)'=='true'">%(AdditionalDependencies);$(CppWinRTPackageDir)build\native\lib\$(Platform)\cppwinrt_fast_forwarder.lib</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
</Project>

@ -0,0 +1,22 @@
========================================================================
The Microsoft.Windows.CppWinRT NuGet package automatically generates C++/WinRT projection headers,
enabling you to both consume and produce Windows Runtime classes.
========================================================================
C++/WinRT detects Windows metadata required by the project, from:
* Platform winmd files in the SDK (both MSI and NuGet)
* NuGet package references containing winmd files
* Other project references producing winmd files
* Raw winmd file references
* Interface definition language (IDL) files in the project
For any winmd file discovered above, C++/WinRT creates reference (consuming) projection headers.
Client code can simply #include these headers, which are created in the generated files directory (see below).
For any IDL file contained in the project, C++/WinRT creates component (producing) projection headers.
In addition, C++/WinRT generates templates and skeleton implementations for each runtime class, under the Generated Files directory.
========================================================================
For more information, visit:
https://github.com/Microsoft/cppwinrt/tree/master/nuget
========================================================================

@ -1,17 +1,94 @@
#include "../csv.h"
#include <iostream> #include <iostream>
#include <string>
//#include <thread>
#include <chrono>
#include "libaquery.h" #include "libaquery.h"
#ifdef _WIN32 #ifdef _WIN32
#include "winhelper.h" #include "winhelper.h"
#else #else
#include <dlfcn.h> #include <dlfcn.h>
#include <fcntl.h>
#include <sys/mman.h>
struct SharedMemory
{
int hFileMap;
void* pData;
SharedMemory(const char* fname) {
hFileMap = open(fname, O_RDWR, 0);
if (hFileMap != -1)
pData = mmap(NULL, 8, PROT_READ | PROT_WRITE, MAP_SHARED, hFileMap, 0);
else
pData = 0;
}
void FreeMemoryMap() {
}
};
#endif #endif
struct thread_context{
}v;
void daemon(thread_context* c) {
}
typedef int (*code_snippet)(void*); typedef int (*code_snippet)(void*);
int main() int _main();
int main(int argc, char** argv) {
printf("%d %s\n", argc, argv[1]);
const char* shmname;
if (argc <= 1)
return _main();
else
shmname = argv[1];
SharedMemory shm = SharedMemory(shmname);
if (!shm.pData)
return 1;
bool &running = static_cast<bool*>(shm.pData)[0],
&ready = static_cast<bool*>(shm.pData)[1];
Context *cxt = new Context();
using namespace std::chrono_literals;
printf("running: %s\n", running? "true":"false");
printf("ready: %s\n", ready? "true":"false");
while (running) {
std::this_thread::sleep_for(1us);
if(ready){
printf("running: %s\n", running? "true":"false");
printf("ready: %s\n", ready? "true":"false");
void* handle = dlopen("./dll.so", RTLD_LAZY);
printf("handle: %x\n", handle);
if (handle) {
printf("inner\n");
code_snippet c = reinterpret_cast<code_snippet>(dlsym(handle, "dllmain"));
printf("routine: %x\n", c);
if (c) {
printf("inner\n");
printf("return: %d\n", c(cxt));
}
dlclose(handle);
}
ready = false;
}
}
shm.FreeMemoryMap();
return 0;
}
int _main()
{ {
using string = std::string;
using std::cout;
using std::thread;
void* handle = dlopen("dll.so", RTLD_LAZY); void* handle = dlopen("dll.so", RTLD_LAZY);
code_snippet c = static_cast<code_snippet>(dlsym(handle, "dlmain")); io::CSVReader<4> in("../test.csv");
printf("%d", c(0)); in.read_header(io::ignore_extra_column, "a", "b", "c", "d");
dlclose(handle); int a, b, cc, d;
string tp, tpdf, st;
while (in.read_row(a, b, cc, d))
cout << a<< ' ' << b <<' ' << cc <<' ' << d << '\n';
//code_snippet c = reinterpret_cast<code_snippet>(dlsym(handle, "dlmain"));
//printf("%d", c(0));
//dlclose(handle);
vector_type<double> t1{ 1.2, 3.4, .2, 1e-5, 1, 3, 5, 4, 5}; vector_type<double> t1{ 1.2, 3.4, .2, 1e-5, 1, 3, 5, 4, 5};
vector_type<int> t2{ 2, 4, 3, 5, 0, 2, 6, 1, 2}; vector_type<int> t2{ 2, 4, 3, 5, 0, 2, 6, 1, 2};
printf("x: "); printf("x: ");
@ -20,6 +97,50 @@ int main()
printf("%lf ", x); printf("%lf ", x);
} }
puts(""); puts("");
Context* cxt = new Context();
auto stocks = TableInfo<int, int>("stocks", 2);
cxt->tables.insert(std::make_pair("stocks", &stocks));
auto& stocks_0 = get<0>(stocks);
auto& stocks_1 = get<1>(stocks);
stocks_0.init();
stocks_1.init();
stocks_0.emplace_back(1);
stocks_1.emplace_back(15);
stocks_0.emplace_back(2);
stocks_1.emplace_back(19);
stocks_0.emplace_back(3);
stocks_1.emplace_back(16);
stocks_0.emplace_back(4);
stocks_1.emplace_back(17);
stocks_0.emplace_back(5);
stocks_1.emplace_back(15);
stocks_0.emplace_back(6);
stocks_1.emplace_back(13);
stocks_0.emplace_back(7);
stocks_1.emplace_back(5);
stocks_0.emplace_back(8);
stocks_1.emplace_back(8);
stocks_0.emplace_back(9);
stocks_1.emplace_back(7);
stocks_0.emplace_back(10);
stocks_1.emplace_back(13);
stocks_0.emplace_back(11);
stocks_1.emplace_back(11);
stocks_0.emplace_back(12);
stocks_1.emplace_back(14);
stocks_0.emplace_back(13);
stocks_1.emplace_back(10);
stocks_0.emplace_back(14);
stocks_1.emplace_back(5);
stocks_0.emplace_back(15);
stocks_1.emplace_back(2);
stocks_0.emplace_back(16);
stocks_1.emplace_back(5);
printf("%d\n", max(stocks_0 - mins(stocks_1)));
return 0; return 0;
} }

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.props')" />
<ItemGroup Label="ProjectConfigurations"> <ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32"> <ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration> <Configuration>Debug</Configuration>
@ -86,8 +87,9 @@
<ClCompile> <ClCompile>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
@ -100,8 +102,9 @@
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions> <IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
@ -114,8 +117,9 @@
<ClCompile> <ClCompile>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
@ -128,8 +132,9 @@
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions> <IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
@ -141,20 +146,33 @@
<ItemGroup> <ItemGroup>
<ClCompile Include="table.cpp" /> <ClCompile Include="table.cpp" />
<ClCompile Include="server.cpp" /> <ClCompile Include="server.cpp" />
<ClCompile Include="types.cpp" />
<ClCompile Include="vector_type.cpp" /> <ClCompile Include="vector_type.cpp" />
<ClCompile Include="winhelper.cpp" /> <ClCompile Include="winhelper.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="csv.h" />
<ClInclude Include="gc.hpp" />
<ClInclude Include="table.h" /> <ClInclude Include="table.h" />
<ClInclude Include="libaquery.h" /> <ClInclude Include="libaquery.h" />
<ClInclude Include="types.h" /> <ClInclude Include="types.h" />
<ClInclude Include="utils.h" />
<ClInclude Include="vector_type.hpp" /> <ClInclude Include="vector_type.hpp" />
<ClInclude Include="winhelper.h" /> <ClInclude Include="winhelper.h" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="cpp.hint" /> <None Include="cpp.hint" />
<None Include="packages.config" />
</ItemGroup> </ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.targets')" />
</ImportGroup> </ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.210806.1\build\native\Microsoft.Windows.CppWinRT.targets'))" />
</Target>
</Project> </Project>

@ -4,28 +4,164 @@
#include "types.h" #include "types.h"
#include "vector_type.hpp" #include "vector_type.hpp"
template <class T> template <typename T>
class vector_type; class vector_type;
template <>
class vector_type<void>;
#ifdef _MSC_VER #ifdef _MSC_VER
namespace types { namespace types {
enum Type_t; enum Type_t;
template <typename T>
struct Types;
template <class T1, class T2>
struct Coercion;
} }
#endif #endif
template<typename Ty> template<typename _Ty>
class ColRef : public vector_type<Ty> class ColRef : public vector_type<_Ty>
{ {
public:
const char* name; const char* name;
types::Type_t ty; types::Type_t ty = types::ERROR;
ColRef(uint32_t size, const char* name = "") : vector_type<_Ty>(size), name(name) {}
ColRef(const char* name) : name(name) {} ColRef(const char* name) : name(name) {}
void init() { ty = types::Types<_Ty>::getType(); this->size = this->capacity = 0; this->container = 0; }
ColRef(const char* name, types::Type_t ty) : name(name), ty(ty) {}
template<typename T>
ColRef<T> scast();
}; };
class TableInfo { template<typename _Ty>
template<typename T>
inline ColRef<T> ColRef<_Ty>::scast()
{
this->ty = types::Types<T>::getType();
return *(ColRef<T> *)this;
}
using uColRef = ColRef<void>;
template<class ...Types>
struct TableInfo {
const char* name; const char* name;
ColRef<void>* colrefs; ColRef<void>* colrefs;
uint32_t n_cols; uint32_t n_cols, n_rows;
//void print();
TableInfo(const char* name, uint32_t n_cols);
}; };
template <class T>
constexpr static inline bool is_vector(const ColRef<T>&) {
return true;
}
template <class T>
constexpr static inline bool is_vector(const vector_type<T>&) {
return true;
}
template <class T>
constexpr static inline bool is_vector(const T&) {
return false;
}
template<class ...Types>
TableInfo<Types...>::TableInfo(const char* name, uint32_t n_cols) : name(name), n_cols(n_cols) {
this->colrefs = (ColRef<void>*)malloc(sizeof(ColRef<void>) * n_cols);
}
template <class T1, class T2>
ColRef<typename types::Coercion<T1, T2>::type> operator -(const ColRef<T1>& lhs, const ColRef<T2>& rhs) {
auto ret = ColRef<typename types::Coercion<T1, T2>::type>(lhs.size, "");
for (int i = 0; i < lhs.size; ++i)
ret.container[i] = lhs.container[i] - rhs.container[i];
return ret;
}
template <class T1, class T2>
ColRef<typename types::Coercion<T1, T2>::type> operator -(const ColRef<T1>& lhs, const T2& rhs) {
auto ret = ColRef<typename types::Coercion<T1, T2>::type>(lhs.size, "");
for (int i = 0; i < lhs.size; ++i)
ret.container[i] = lhs.container[i] - rhs;
return ret;
}
template <size_t _Index, class... _Types>
constexpr ColRef<std::tuple_element_t<_Index, std::tuple<_Types...>>>& get(TableInfo<_Types...>& table) noexcept {
return *(ColRef< std::tuple_element_t<_Index, std::tuple<_Types...>>> *) &(table.colrefs[_Index]);
}
//void TableInfo::print()
//{
// for (int i = 0; i < n_rows; ++i) {
// for (int j = 0; j < n_cols; ++j) // TODO: Deal with date/time
// printf(types::printf_str[colrefs[j].ty], colrefs[j].get(i, colrefs[j].ty));
// puts("");
// }
//}
template<class T>
ColRef<T> mins(const ColRef<T>& arr) {
const int& len = arr.size;
std::deque<std::pair<T, uint32_t>> cache;
ColRef<T> ret(len);
T min = std::numeric_limits<T>::max();
for (int i = 0; i < len; ++i) {
if (arr[i] < min)
min = arr[i];
ret[i] = min;
}
return ret;
}
template<class T>
ColRef<T> maxs(const ColRef<T>& arr) {
const int& len = arr.size;
ColRef<T> ret(len);
T max = std::numeric_limits<T>::min();
for (int i = 0; i < len; ++i) {
if (arr[i] > max)
max = arr[i];
ret[i] = max;
}
return ret;
}
template<class T>
ColRef<T> minw(const ColRef<T>& arr, uint32_t w) {
const int& len = arr.size;
ColRef<T> ret(len);
std::deque<std::pair<T, uint32_t>> cache;
for (int i = 0; i < len; ++i) {
if (!cache.empty() && cache.front().second == i - w) cache.pop_front();
while (!cache.empty() && cache.back().first > arr[i]) cache.pop_back();
cache.push_back({ arr[i], i });
ret[i] = cache.front().first;
}
return ret;
}
template<class T>
ColRef<T> maxw(const ColRef<T>& arr, uint32_t w) {
const int& len = arr.size;
ColRef<T> ret(len);
std::deque<std::pair<T, uint32_t>> cache;
for (int i = 0; i < len; ++i) {
if (!cache.empty() && cache.front().second == i - w) cache.pop_front();
while (!cache.empty() && cache.back().first > arr[i]) cache.pop_back();
cache.push_back({ arr[i], i });
arr[i] = cache.front().first;
}
return ret;
}
template <class T>
void print(const T& v) {
printf(types::printf_str[types::Types<T>::getType()], v);
}
template <class T>
void print(const ColRef<T>& v, const char* delimiter) {
for (const auto& vi : v) {
print(vi);
puts(delimiter);
}
}
#endif #endif

@ -0,0 +1,25 @@
#include "types.h"
#include <string>
#include <iostream>
//template<typename T>
//inline static constexpr void types::Types<T>::print(T& v)
//{
// std::cout << v;
//}
#include <chrono>
#include <ctime>
namespace types {
using namespace std;
using namespace chrono;
string date_t::toString() const {
uint32_t curr_v = val;
tm;
time_t;
return string() + string("/") + string() + string("/") + string();
}
string time_t::toString() const {
uint32_t curr_v = val;
return string() + string("/") + string() + string("/") + string();
}
}

@ -4,38 +4,37 @@
#include <functional> #include <functional>
#include <cstdint> #include <cstdint>
#include <type_traits> #include <type_traits>
#include "table.h" #include <string>
#ifdef _MSC_VER
#define __restrict__ __restrict
#endif
namespace types { namespace types {
enum Type_t { enum Type_t {
AINT, AFLOAT, ASTR, ADOUBLE, ALDOUBLE, ALONG, ASHORT, ADATE, ATIME, ACHAR, NONE, AINT, AFLOAT, ASTR, ADOUBLE, ALDOUBLE, ALONG, ASHORT, ADATE, ATIME, ACHAR,
AUINT, AULONG, AUSHORT, AUCHAR AUINT, AULONG, AUSHORT, AUCHAR, NONE, ERROR
}; };
static constexpr const char* printf_str[] = { "%d ", "%f ", "%s ", "%lf ", "%llf ", "%ld ", "%hi ", "%s ", "%s ", "%c ",
"%u ", "%lu ", "%hu ", "%hhu ", "NULL " };
// TODO: deal with data/time <=> str/uint conversion // TODO: deal with data/time <=> str/uint conversion
struct date_t { struct date_t {
uint32_t val; uint32_t val;
date_t(const char* d) { date_t(const char* d) {
} }
const char* toString() const{ std::string toString() const;
return "";
}
}; };
struct time_t { struct time_t {
uint32_t val; uint32_t val;
time_t(const char* d) { time_t(const char* d) {
} }
const char* toString() const { std::string toString() const;
return "";
}
}; };
template <typename T> template <typename T>
struct Types { struct Types {
typedef T type; typedef T type;
constexpr Types() noexcept = default; constexpr Types() noexcept = default;
#define ConnectTypes(f, x, y) \ #define ConnectTypes(f) \
f(int, AINT) \ f(int, AINT) \
f(float, AFLOAT) \ f(float, AFLOAT) \
f(const char*, ASTR) \ f(const char*, ASTR) \
@ -45,18 +44,21 @@ namespace types {
f(short, ASHORT) \ f(short, ASHORT) \
f(date_t, ADATE) \ f(date_t, ADATE) \
f(time_t, ATIME) \ f(time_t, ATIME) \
f(unsigned short, AUSHORT) \
f(unsigned long, AULONG) \
f(unsigned int, AUINT) \
f(unsigned char, ACHAR) \ f(unsigned char, ACHAR) \
f(void, NONE) f(unsigned int, AUINT) \
f(unsigned long, AULONG) \
f(unsigned short, AUSHORT) \
f(unsigned char, AUCHAR)
constexpr Type_t getType() const { constexpr static Type_t getType() {
#define TypeConnect(x, y) if(typeid(T) == typeid(x)) return y; else #define TypeConnect(x, y) if(typeid(T) == typeid(x)) return y; else
ConnectTypes(TypeConnect, x, y) ConnectTypes(TypeConnect)
return NONE; return NONE;
} }
//static constexpr inline void print(T& v);
}; };
#define ATypeSize(t, at) sizeof(t),
static constexpr size_t AType_sizes[] = { ConnectTypes(ATypeSize) 1 };
#define Cond(c, x, y) typename std::conditional<c, x, y>::type #define Cond(c, x, y) typename std::conditional<c, x, y>::type
#define Comp(o) (sizeof(T1) o sizeof(T2)) #define Comp(o) (sizeof(T1) o sizeof(T2))
#define Same(x, y) (std::is_same_v<x, y>) #define Same(x, y) (std::is_same_v<x, y>)
@ -64,9 +66,19 @@ namespace types {
#define Fp(x) std::is_floating_point<x>::value #define Fp(x) std::is_floating_point<x>::value
template <class T1, class T2> template <class T1, class T2>
struct Coercion { struct Coercion {
using t1 = Cond(Comp(<=), Cond(Comp(==), Cond(Fp(T1), T1, Cond(Fp(T2), T2, Cond(_U(T1), T2, T1))), T2), T1); using t1 = Cond(Comp(<= ), Cond(Comp(== ), Cond(Fp(T1), T1, Cond(Fp(T2), T2, Cond(_U(T1), T2, T1))), T2), T1);
using t2 = Cond(Same(T1, T2), T1, Cond(Same(T1, const char*) || Same(T2, const char*), const char*, void)); using t2 = Cond(Same(T1, T2), T1, Cond(Same(T1, const char*) || Same(T2, const char*), const char*, void));
using type = Cond(Same(t2, void), Cond(Same(T1, date_t) && Same(T2, time_t) || Same(T1, time_t) && Same(T2, time_t), void, t1), t2); using type = Cond(Same(t2, void), Cond(Same(T1, date_t) && Same(T2, time_t) || Same(T1, time_t) && Same(T2, time_t), void, t1), t2);
}; };
#define __Eq(x) (sizeof(T) == sizeof(x))
template<class T>
struct GetFPType {
using type = Cond(__Eq(float), float, Cond(__Eq(double), double, long double));
};
template<class T>
struct GetLongType
{
using type = Cond(_U(T), unsigned long long, Cond(Fp(T), long double, long long));
};
} }
#endif // !_TYPES_H #endif // !_TYPES_H

@ -0,0 +1,18 @@
#pragma once
#include <string>
#include <ctime>
#include <random>
using std::string;
string base62uuid(int l = 8) {
constexpr static const char* base62alp = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static mt19937_64 engine(chrono::system_clock::now().time_since_epoch().count());
static uniform_int_distribution<uint64_t> u(0x100000000, 0xfffffffff);
uint64_t uuid = (u(engine)<<16ull) + (time(0)&0xffff);
printf("%lx\n", uuid);
string ret;
while (uuid && l-- >= 0){
ret = string("") + base62alp[uuid % 62] + ret;
uuid /= 62;
}
return ret;
}

@ -1 +1 @@
#include "vector_type.hpp" #include "vector_type.hpp"

@ -14,7 +14,8 @@
#include <initializer_list> #include <initializer_list>
#include <vector> #include <vector>
#include <stdarg.h> #include <stdarg.h>
#include <limits>
#include <deque>
#include "types.h" #include "types.h"
#pragma pack(push, 1) #pragma pack(push, 1)
@ -45,12 +46,12 @@ public:
} }
constexpr vector_type(std::initializer_list<_Ty> _l) { constexpr vector_type(std::initializer_list<_Ty> _l) {
size = capacity = _l.size(); size = capacity = _l.size();
_Ty* container = this->container = (_Ty*)malloc(sizeof(_Ty) * _l.size()); _Ty* _container = this->container = (_Ty*)malloc(sizeof(_Ty) * _l.size());
for (const auto& l : _l) { for (const auto& l : _l) {
*(container++) = l; *(_container++) = l;
} }
} }
constexpr vector_type() noexcept = default; constexpr vector_type() noexcept {};
constexpr vector_type(vector_type<_Ty>& vt) noexcept { constexpr vector_type(vector_type<_Ty>& vt) noexcept {
_copy(vt); _copy(vt);
} }
@ -67,7 +68,7 @@ public:
} }
void emplace_back(_Ty _val) { void emplace_back(_Ty _val) {
if (size >= capacity) { // geometric growth if (size >= capacity) { // geometric growth
capacity += 1 + capacity >> 1; capacity += 1 + (capacity >> 1);
_Ty* n_container = (_Ty*)malloc(capacity * sizeof(_Ty)); _Ty* n_container = (_Ty*)malloc(capacity * sizeof(_Ty));
memcpy(n_container, container, sizeof(_Ty) * size); memcpy(n_container, container, sizeof(_Ty) * size);
free(container); free(container);
@ -216,5 +217,65 @@ public:
_Make_Ops(Ops) _Make_Ops(Ops)
_Make_Ops(Opseq) _Make_Ops(Opseq)
}; };
template <>
class vector_type<void> {
public:
void* container;
uint32_t size, capacity;
typedef void* iterator_t;
vector_type(uint32_t size) : size(size), capacity(size) {
container = (void*)malloc(size);
}
template<typename _Ty>
constexpr vector_type(std::initializer_list<_Ty> _l) {
size = capacity = _l.size();
this->container = malloc(sizeof(_Ty) * _l.size());
_Ty* _container = (_Ty*)this->container;
for (const auto& l : _l) {
*(_container++) = l;
}
}
constexpr vector_type() : size(0), capacity(0), container(0) {};
void *get(uint32_t i, types::Type_t atype){
return static_cast<void*>(static_cast<char*>(container) + (i * types::AType_sizes[atype]));
}
};
#pragma pack(pop) #pragma pack(pop)
// TODO: Specializations for dt/str/none
template<class T>
types::GetLongType<T> sum(const vector_type<T> &v) {
types::GetLongType<T> ret = 0;
for (const auto& _v : v)
ret += _v;
return ret;
}
template<class T>
types::GetFPType<T> avg(const vector_type<T> &v) {
return static_cast<types::GetFPType<T>>(
sum<T>(v)/static_cast<long double>(v.size));
}
template <class T>
T max(const vector_type<T>& v) {
T max_v = std::numeric_limits<T>::min();
for (const auto& _v : v)
max_v = max_v > _v ? max_v : _v;
return max_v;
}
template <class T>
T min(const vector_type<T>& v) {
T min_v = std::numeric_limits<T>::max();
for (const auto& _v : v)
min_v = min_v < _v ? min_v : _v;
return min_v;
}
#endif #endif

@ -16,3 +16,21 @@ int dlclose(void* handle)
{ {
return FreeLibrary(static_cast<HMODULE>(handle)); return FreeLibrary(static_cast<HMODULE>(handle));
} }
SharedMemory::SharedMemory(const char* fname)
{
this->hFileMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 2, fname);
if (this->hFileMap)
this->pData = MapViewOfFile(this->hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 2);
else
this->pData = NULL;
}
void SharedMemory::FreeMemoryMap()
{
if (this->hFileMap)
if (this->pData)
UnmapViewOfFile(this->pData);
if (this->hFileMap)
CloseHandle(this->hFileMap);
}

@ -1,7 +1,14 @@
#ifndef _WINHELPER_H #ifndef _WINHELPER_H
#define _WINHELPER_H #define _WINHELPER_H
#define RTLD_LAZY 1 static constexpr int RTLD_LAZY = 1;
void* dlopen(const char*, int); void* dlopen(const char*, int);
void* dlsym(void*, const char*); void* dlsym(void*, const char*);
int dlclose(void*); int dlclose(void*);
struct SharedMemory
{
void* hFileMap;
void* pData;
SharedMemory(const char*);
void FreeMemoryMap();
};
#endif #endif

@ -17,13 +17,16 @@ INSERT INTO stocks VALUES(14,5)
INSERT INTO stocks VALUES(15,2) INSERT INTO stocks VALUES(15,2)
INSERT INTO stocks VALUES(16,5) INSERT INTO stocks VALUES(16,5)
<k> "q1" </k>
SELECT max(price-min(timestamp)) FROM stocks SELECT max(price-min(timestamp)) FROM stocks
<k> "q2" </k>
/*<k> "q1" </k>
*/
SELECT max(price-mins(price)) FROM stocks
/*
<k> "q2" </k>
SELECT price, timestamp FROM stocks where price -timestamp > 1 and not (price*timestamp<100); SELECT price, timestamp FROM stocks where price -timestamp > 1 and not (price*timestamp<100);
<k> "q3"</k> <k> "q3"</k>
SELECT max(price-mins(price)) SELECT max(price-mins(price))
FROM stocks FROM stocks
ASSUMING ASC timestamp ASSUMING ASC timestamp
*/
Loading…
Cancel
Save