Enum cranelift_isle::sema::Type
source · pub enum Type {
Primitive(TypeId, Sym, Pos),
Enum {
name: Sym,
id: TypeId,
is_extern: bool,
is_nodebug: bool,
variants: Vec<Variant>,
pos: Pos,
},
}
Expand description
A type.
Variants§
Primitive(TypeId, Sym, Pos)
A primitive, Copy
type.
These are always defined externally, and we allow literals of these types to pass through from ISLE source code to the emitted Rust code.
Enum
Fields
A sum type.
Note that enums with only one variant are equivalent to a “struct”.
Implementations§
source§impl Type
impl Type
sourcepub fn name<'a>(&self, tyenv: &'a TypeEnv) -> &'a str
pub fn name<'a>(&self, tyenv: &'a TypeEnv) -> &'a str
Get the name of this Type
.
Examples found in repository?
src/codegen.rs (line 254)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
fn generate_internal_types(&self, code: &mut String) {
for ty in &self.typeenv.types {
match ty {
&Type::Enum {
name,
is_extern,
is_nodebug,
ref variants,
pos,
..
} if !is_extern => {
let name = &self.typeenv.syms[name.index()];
writeln!(
code,
"\n/// Internal type {}: defined at {}.",
name,
pos.pretty_print_line(&self.typeenv.filenames[..])
)
.unwrap();
// Generate the `derive`s.
let debug_derive = if is_nodebug { "" } else { ", Debug" };
if variants.iter().all(|v| v.fields.is_empty()) {
writeln!(
code,
"#[derive(Copy, Clone, PartialEq, Eq{})]",
debug_derive
)
.unwrap();
} else {
writeln!(code, "#[derive(Clone{})]", debug_derive).unwrap();
}
writeln!(code, "pub enum {} {{", name).unwrap();
for variant in variants {
let name = &self.typeenv.syms[variant.name.index()];
if variant.fields.is_empty() {
writeln!(code, " {},", name).unwrap();
} else {
writeln!(code, " {} {{", name).unwrap();
for field in &variant.fields {
let name = &self.typeenv.syms[field.name.index()];
let ty_name =
self.typeenv.types[field.ty.index()].name(&self.typeenv);
writeln!(code, " {}: {},", name, ty_name).unwrap();
}
writeln!(code, " }},").unwrap();
}
}
writeln!(code, "}}").unwrap();
}
_ => {}
}
}
}
More examples
src/sema.rs (line 1805)
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
fn translate_pattern(
&self,
tyenv: &mut TypeEnv,
pat: &ast::Pattern,
expected_ty: Option<TypeId>,
bindings: &mut Bindings,
) -> Option<(Pattern, TypeId)> {
log!("translate_pattern: {:?}", pat);
log!("translate_pattern: bindings = {:?}", bindings);
match pat {
// TODO: flag on primitive type decl indicating it's an integer type?
&ast::Pattern::ConstInt { val, pos } => {
let ty = match expected_ty {
Some(t) => t,
None => {
tyenv.report_error(pos, "Need an implied type for an integer constant");
return None;
}
};
if !tyenv.types[ty.index()].is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-primitive type {}, but found integer literal '{}'",
tyenv.types[ty.index()].name(tyenv),
val,
),
);
}
Some((Pattern::ConstInt(ty, val), ty))
}
&ast::Pattern::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if expected_ty.is_some() && expected_ty != Some(const_ty) {
tyenv.report_error(pos, "Type mismatch for constant");
}
Some((Pattern::ConstPrim(const_ty, val), const_ty))
}
&ast::Pattern::Wildcard { pos } => {
let ty = match expected_ty {
Some(t) => t,
None => {
tyenv.report_error(pos, "Need an implied type for a wildcard");
return None;
}
};
Some((Pattern::Wildcard(ty), ty))
}
&ast::Pattern::And { ref subpats, pos } => {
let mut expected_ty = expected_ty;
let mut children = vec![];
for subpat in subpats {
let (subpat, ty) = unwrap_or_continue!(self.translate_pattern(
tyenv,
subpat,
expected_ty,
bindings,
));
expected_ty = expected_ty.or(Some(ty));
// Normalize nested `And` nodes to a single vector of conjuncts.
match subpat {
Pattern::And(_, subpat_children) => children.extend(subpat_children),
_ => children.push(subpat),
}
}
if expected_ty.is_none() {
tyenv.report_error(pos, "No type for (and ...) form.".to_string());
return None;
}
let ty = expected_ty.unwrap();
Some((Pattern::And(ty, children), ty))
}
&ast::Pattern::BindPattern {
ref var,
ref subpat,
pos,
} => {
// Do the subpattern first so we can resolve the type for sure.
let (subpat, ty) = self.translate_pattern(tyenv, subpat, expected_ty, bindings)?;
let name = tyenv.intern_mut(var);
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!("Re-bound variable name in LHS pattern: '{}'", var.0),
);
// Try to keep going.
}
let id = bindings.add_var(name, ty);
Some((Pattern::BindPattern(ty, id, Box::new(subpat)), ty))
}
&ast::Pattern::Var { ref var, pos } => {
// Look up the variable; if it has already been bound,
// then this becomes a `Var` node (which matches the
// existing bound value), otherwise it becomes a
// `BindPattern` with a wildcard subpattern to capture
// at this location.
let name = tyenv.intern_mut(var);
match bindings.lookup(name) {
None => {
let ty = match expected_ty {
Some(ty) => ty,
None => {
tyenv.report_error(
pos,
format!("Variable pattern '{}' not allowed in context without explicit type", var.0),
);
return None;
}
};
let id = bindings.add_var(name, ty);
Some((
Pattern::BindPattern(ty, id, Box::new(Pattern::Wildcard(ty))),
ty,
))
}
Some(bv) => {
let ty = match expected_ty {
None => bv.ty,
Some(expected_ty) if expected_ty == bv.ty => bv.ty,
Some(expected_ty) => {
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but already-bound var '{}' has type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
var.0,
tyenv.types[bv.ty.index()].name(tyenv)));
bv.ty // Try to keep going for more errors.
}
};
Some((Pattern::Var(ty, bv.id), ty))
}
}
}
&ast::Pattern::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let tid = match self.get_term_by_name(tyenv, sym) {
Some(t) => t,
None => {
tyenv.report_error(pos, format!("Unknown term in pattern: '{}'", sym.0));
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term. Insert an implicit
// converter if needed.
let ret_ty = termdata.ret_ty;
let ty = match expected_ty {
None => ret_ty,
Some(expected_ty) if expected_ty == ret_ty => ret_ty,
Some(expected_ty) => {
// Can we do an implicit type conversion? Look
// up the converter term, if any. If one has
// been registered, and the term has an
// extractor, then build an expanded AST node
// right here and recurse on it.
if let Some(expanded_pattern) =
self.maybe_implicit_convert_pattern(tyenv, pat, ret_ty, expected_ty)
{
return self.translate_pattern(
tyenv,
&expanded_pattern,
Some(expected_ty),
bindings,
);
}
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but term has return type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv)));
ret_ty // Try to keep going for more errors.
}
};
termdata.check_args_count(args, tyenv, pos, sym);
match &termdata.kind {
TermKind::EnumVariant { .. } => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }),
..
} => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { ref template }),
..
} => {
// Expand the extractor macro! We create a map
// from macro args to AST pattern trees and
// then evaluate the template with these
// substitutions.
log!("internal extractor macro args = {:?}", args);
let pat = template.subst_macro_args(&args)?;
return self.translate_pattern(tyenv, &pat, expected_ty, bindings);
}
TermKind::Decl {
extractor_kind: None,
..
} => {
tyenv.report_error(
pos,
format!(
"Cannot use term '{}' that does not have a defined extractor in a \
left-hand side pattern",
sym.0
),
);
}
}
let subpats = self.translate_args(args, termdata, tyenv, bindings);
Some((Pattern::Term(ty, tid, subpats), ty))
}
&ast::Pattern::MacroArg { .. } => unreachable!(),
}
}
fn translate_args(
&self,
args: &Vec<ast::Pattern>,
termdata: &Term,
tyenv: &mut TypeEnv,
bindings: &mut Bindings,
) -> Vec<Pattern> {
args.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| self.translate_pattern(tyenv, arg, Some(arg_ty), bindings))
.map(|(subpat, _)| subpat)
.collect()
}
fn maybe_implicit_convert_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
inner_ty: TypeId,
outer_ty: TypeId,
) -> Option<ast::Expr> {
// Is there a converter for this type mismatch?
if let Some(converter_term) = self.converters.get(&(inner_ty, outer_ty)) {
if self.terms[converter_term.index()].has_constructor() {
let converter_ident = ast::Ident(
tyenv.syms[self.terms[converter_term.index()].name.index()].clone(),
expr.pos(),
);
return Some(ast::Expr::Term {
sym: converter_ident,
pos: expr.pos(),
args: vec![expr.clone()],
});
}
}
None
}
fn translate_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
ty: Option<TypeId>,
bindings: &mut Bindings,
pure: bool,
) -> Option<Expr> {
log!("translate_expr: {:?}", expr);
match expr {
&ast::Expr::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let name = tyenv.intern_mut(&sym);
let tid = match self.term_map.get(&name) {
Some(&t) => t,
None => {
// Maybe this was actually a variable binding and the user has placed
// parens around it by mistake? (See #4775.)
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!(
"Unknown term in expression: '{}'. Variable binding under this name exists; try removing the parens?", sym.0));
} else {
tyenv.report_error(
pos,
format!("Unknown term in expression: '{}'", sym.0),
);
}
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term, and determine whether we
// are doing an implicit conversion. Report an error
// if types don't match and no conversion is possible.
let ret_ty = termdata.ret_ty;
let ty = if ty.is_some() && ret_ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, ret_ty, ty.unwrap())
{
return self.translate_expr(tyenv, &expanded_expr, ty, bindings, pure);
}
tyenv.report_error(
pos,
format!("Mismatched types: expression expects type '{}' but term has return type '{}'",
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv)));
// Keep going, to discover more errors.
ret_ty
} else {
ret_ty
};
// Check that the term's constructor is pure.
if pure {
if let TermKind::Decl { pure: false, .. } = &termdata.kind {
tyenv.report_error(
pos,
format!(
"Used non-pure constructor '{}' in pure expression context",
sym.0
),
);
}
}
termdata.check_args_count(args, tyenv, pos, sym);
// Resolve subexpressions.
let subexprs = args
.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| {
self.translate_expr(tyenv, arg, Some(arg_ty), bindings, pure)
})
.collect();
Some(Expr::Term(ty, tid, subexprs))
}
&ast::Expr::Var { ref name, pos } => {
let sym = tyenv.intern_mut(name);
// Look through bindings, innermost (most recent) first.
let bv = match bindings.lookup(sym) {
None => {
tyenv.report_error(pos, format!("Unknown variable '{}'", name.0));
return None;
}
Some(bv) => bv,
};
// Verify type. Maybe do an implicit conversion.
if ty.is_some() && bv.ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, bv.ty, ty.unwrap())
{
return self.translate_expr(tyenv, &expanded_expr, ty, bindings, pure);
}
tyenv.report_error(
pos,
format!(
"Variable '{}' has type {} but we need {} in context",
name.0,
tyenv.types[bv.ty.index()].name(tyenv),
tyenv.types[ty.unwrap().index()].name(tyenv)
),
);
}
Some(Expr::Var(bv.ty, bv.id))
}
&ast::Expr::ConstInt { val, pos } => {
if ty.is_none() {
tyenv.report_error(
pos,
"integer literal in a context that needs an explicit type".to_string(),
);
return None;
}
let ty = ty.unwrap();
if !tyenv.types[ty.index()].is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-primitive type {}, but found integer literal '{}'",
tyenv.types[ty.index()].name(tyenv),
val,
),
);
}
Some(Expr::ConstInt(ty, val))
}
&ast::Expr::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if ty.is_some() && const_ty != ty.unwrap() {
tyenv.report_error(
pos,
format!(
"Constant '{}' has wrong type: expected {}, but is actually {}",
tyenv.syms[val.index()],
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[const_ty.index()].name(tyenv)
),
);
return None;
}
Some(Expr::ConstPrim(const_ty, val))
}
&ast::Expr::Let {
ref defs,
ref body,
pos,
} => {
let orig_binding_len = bindings.seen.len();
// For each new binding...
let mut let_defs = vec![];
for def in defs {
// Check that the given variable name does not already exist.
let name = tyenv.intern_mut(&def.var);
// Look up the type.
let tid = match tyenv.get_type_by_name(&def.ty) {
Some(tid) => tid,
None => {
tyenv.report_error(
pos,
format!("Unknown type {} for variable '{}'", def.ty.0, def.var.0),
);
continue;
}
};
// Evaluate the variable's value.
let val = Box::new(unwrap_or_continue!(self.translate_expr(
tyenv,
&def.val,
Some(tid),
bindings,
pure
)));
// Bind the var with the given type.
let id = bindings.add_var(name, tid);
let_defs.push((id, tid, val));
}
// Evaluate the body, expecting the type of the overall let-expr.
let body = Box::new(self.translate_expr(tyenv, body, ty, bindings, pure)?);
let body_ty = body.ty();
// Pop the bindings.
bindings.seen.truncate(orig_binding_len);
Some(Expr::Let {
ty: body_ty,
bindings: let_defs,
body,
})
}
}
}
sourcepub fn pos(&self) -> Pos
pub fn pos(&self) -> Pos
Get the position where this type was defined.
Examples found in repository?
src/sema.rs (line 915)
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
pub fn from_ast(defs: &ast::Defs) -> Result<TypeEnv, Errors> {
let mut tyenv = TypeEnv {
filenames: defs.filenames.clone(),
file_texts: defs.file_texts.clone(),
syms: vec![],
sym_map: StableMap::new(),
types: vec![],
type_map: StableMap::new(),
const_types: StableMap::new(),
errors: vec![],
};
// Traverse defs, assigning type IDs to type names. We'll fill
// in types on a second pass.
for def in &defs.defs {
match def {
&ast::Def::Type(ref td) => {
let tid = TypeId(tyenv.type_map.len());
let name = tyenv.intern_mut(&td.name);
if let Some(existing) = tyenv.type_map.get(&name).copied() {
tyenv.report_error(
td.pos,
format!("Type with name '{}' defined more than once", td.name.0),
);
let pos = unwrap_or_continue!(tyenv.types.get(existing.index())).pos();
tyenv.report_error(
pos,
format!("Type with name '{}' already defined here", td.name.0),
);
continue;
}
tyenv.type_map.insert(name, tid);
}
_ => {}
}
}
// Now lower AST nodes to type definitions, raising errors
// where typenames of fields are undefined or field names are
// duplicated.
for def in &defs.defs {
match def {
&ast::Def::Type(ref td) => {
let tid = tyenv.types.len();
if let Some(ty) = tyenv.type_from_ast(TypeId(tid), td) {
tyenv.types.push(ty);
}
}
_ => {}
}
}
// Now collect types for extern constants.
for def in &defs.defs {
match def {
&ast::Def::Extern(ast::Extern::Const {
ref name,
ref ty,
pos,
}) => {
let ty = match tyenv.get_type_by_name(ty) {
Some(ty) => ty,
None => {
tyenv.report_error(pos, "Unknown type for constant");
continue;
}
};
let name = tyenv.intern_mut(name);
tyenv.const_types.insert(name, ty);
}
_ => {}
}
}
tyenv.return_errors()?;
Ok(tyenv)
}
sourcepub fn is_prim(&self) -> bool
pub fn is_prim(&self) -> bool
Is this a primitive type?
Examples found in repository?
src/codegen.rs (line 285)
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
fn ty_prim(&self, ty: TypeId) -> bool {
self.typeenv.types[ty.index()].is_prim()
}
fn value_binder(&self, value: &Value, is_ref: bool, ty: TypeId) -> String {
let prim = self.ty_prim(ty);
if prim || !is_ref {
format!("{}", self.value_name(value))
} else {
format!("ref {}", self.value_name(value))
}
}
fn value_by_ref(&self, value: &Value, ctx: &BodyContext) -> String {
let raw_name = self.value_name(value);
let &(is_ref, ty) = ctx.values.get(value).unwrap();
let prim = self.ty_prim(ty);
if is_ref || prim {
raw_name
} else {
format!("&{}", raw_name)
}
}
fn value_by_val(&self, value: &Value, ctx: &BodyContext) -> String {
let raw_name = self.value_name(value);
let &(is_ref, _) = ctx.values.get(value).unwrap();
if is_ref {
format!("{}.clone()", raw_name)
} else {
raw_name
}
}
fn define_val(&self, value: &Value, ctx: &mut BodyContext, is_ref: bool, ty: TypeId) {
let is_ref = !self.ty_prim(ty) && is_ref;
ctx.values.insert(value.clone(), (is_ref, ty));
}
fn const_int(&self, val: i128, ty: TypeId) -> String {
let is_bool = match &self.typeenv.types[ty.index()] {
&Type::Primitive(_, name, _) => &self.typeenv.syms[name.index()] == "bool",
_ => unreachable!(),
};
if is_bool {
format!("{}", val != 0)
} else {
let ty_name = self.type_name(ty, /* by_ref = */ false);
if ty_name == "i128" {
format!("{}i128", val)
} else {
format!("{}i128 as {}", val, ty_name)
}
}
}
fn generate_internal_term_constructors(&self, code: &mut String) {
for (&termid, trie) in self.functions_by_term {
let termdata = &self.termenv.terms[termid.index()];
// Skip terms that are enum variants or that have external
// constructors/extractors.
if !termdata.has_constructor() || termdata.has_external_constructor() {
continue;
}
let sig = termdata.constructor_sig(self.typeenv).unwrap();
let args = sig
.param_tys
.iter()
.enumerate()
.map(|(i, &ty)| format!("arg{}: {}", i, self.type_name(ty, true)))
.collect::<Vec<_>>()
.join(", ");
assert_eq!(sig.ret_tys.len(), 1);
let ret = self.type_name(sig.ret_tys[0], false);
let ret = if sig.multi {
format!("impl ContextIter<Context = C, Output = {}>", ret)
} else {
ret
};
writeln!(
code,
"\n// Generated as internal constructor for term {}.",
self.typeenv.syms[termdata.name.index()],
)
.unwrap();
writeln!(
code,
"pub fn {}<C: Context>(ctx: &mut C, {}) -> Option<{}> {{",
sig.func_name, args, ret,
)
.unwrap();
if sig.multi {
writeln!(code, "let mut returns = ConstructorVec::new();").unwrap();
}
let mut body_ctx: BodyContext = Default::default();
let returned = self.generate_body(
code,
/* depth = */ 0,
trie,
" ",
&mut body_ctx,
sig.multi,
);
if !returned {
if sig.multi {
writeln!(
code,
" return Some(ContextIterWrapper::from(returns.into_iter()));"
)
.unwrap();
} else {
writeln!(code, " return None;").unwrap();
}
}
writeln!(code, "}}").unwrap();
}
}
fn generate_expr_inst(
&self,
code: &mut String,
id: InstId,
inst: &ExprInst,
indent: &str,
ctx: &mut BodyContext,
returns: &mut Vec<(usize, String)>,
) -> bool {
log!("generate_expr_inst: {:?}", inst);
let mut new_scope = false;
match inst {
&ExprInst::ConstInt { ty, val } => {
let value = Value::Expr {
inst: id,
output: 0,
};
self.define_val(&value, ctx, /* is_ref = */ false, ty);
let name = self.value_name(&value);
let ty_name = self.type_name(ty, /* by_ref = */ false);
writeln!(
code,
"{}let {}: {} = {};",
indent,
name,
ty_name,
self.const_int(val, ty)
)
.unwrap();
}
&ExprInst::ConstPrim { ty, val } => {
let value = Value::Expr {
inst: id,
output: 0,
};
self.define_val(&value, ctx, /* is_ref = */ false, ty);
let name = self.value_name(&value);
let ty_name = self.type_name(ty, /* by_ref = */ false);
writeln!(
code,
"{}let {}: {} = {};",
indent,
name,
ty_name,
self.typeenv.syms[val.index()],
)
.unwrap();
}
&ExprInst::CreateVariant {
ref inputs,
ty,
variant,
} => {
let variantinfo = match &self.typeenv.types[ty.index()] {
&Type::Primitive(..) => panic!("CreateVariant with primitive type"),
&Type::Enum { ref variants, .. } => &variants[variant.index()],
};
let mut input_fields = vec![];
for ((input_value, _), field) in inputs.iter().zip(variantinfo.fields.iter()) {
let field_name = &self.typeenv.syms[field.name.index()];
let value_expr = self.value_by_val(input_value, ctx);
input_fields.push(format!("{}: {}", field_name, value_expr));
}
let output = Value::Expr {
inst: id,
output: 0,
};
let outputname = self.value_name(&output);
let full_variant_name = format!(
"{}::{}",
self.type_name(ty, false),
self.typeenv.syms[variantinfo.name.index()]
);
if input_fields.is_empty() {
writeln!(
code,
"{}let {} = {};",
indent, outputname, full_variant_name
)
.unwrap();
} else {
writeln!(
code,
"{}let {} = {} {{",
indent, outputname, full_variant_name
)
.unwrap();
for input_field in input_fields {
writeln!(code, "{} {},", indent, input_field).unwrap();
}
writeln!(code, "{}}};", indent).unwrap();
}
self.define_val(&output, ctx, /* is_ref = */ false, ty);
}
&ExprInst::Construct {
ref inputs,
term,
infallible,
multi,
..
} => {
let mut input_exprs = vec![];
for (input_value, input_ty) in inputs {
let value_expr = if self.typeenv.types[input_ty.index()].is_prim() {
self.value_by_val(input_value, ctx)
} else {
self.value_by_ref(input_value, ctx)
};
input_exprs.push(value_expr);
}
let output = Value::Expr {
inst: id,
output: 0,
};
let outputname = self.value_name(&output);
let termdata = &self.termenv.terms[term.index()];
let sig = termdata.constructor_sig(self.typeenv).unwrap();
assert_eq!(input_exprs.len(), sig.param_tys.len());
if !multi {
let fallible_try = if infallible { "" } else { "?" };
writeln!(
code,
"{}let {} = {}(ctx, {}){};",
indent,
outputname,
sig.full_name,
input_exprs.join(", "),
fallible_try,
)
.unwrap();
} else {
writeln!(
code,
"{}let mut it = {}(ctx, {})?;",
indent,
sig.full_name,
input_exprs.join(", "),
)
.unwrap();
writeln!(
code,
"{}while let Some({}) = it.next(ctx) {{",
indent, outputname,
)
.unwrap();
new_scope = true;
}
self.define_val(&output, ctx, /* is_ref = */ false, termdata.ret_ty);
}
&ExprInst::Return {
index, ref value, ..
} => {
let value_expr = self.value_by_val(value, ctx);
returns.push((index, value_expr));
}
}
new_scope
}
More examples
src/sema.rs (line 1800)
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
fn translate_pattern(
&self,
tyenv: &mut TypeEnv,
pat: &ast::Pattern,
expected_ty: Option<TypeId>,
bindings: &mut Bindings,
) -> Option<(Pattern, TypeId)> {
log!("translate_pattern: {:?}", pat);
log!("translate_pattern: bindings = {:?}", bindings);
match pat {
// TODO: flag on primitive type decl indicating it's an integer type?
&ast::Pattern::ConstInt { val, pos } => {
let ty = match expected_ty {
Some(t) => t,
None => {
tyenv.report_error(pos, "Need an implied type for an integer constant");
return None;
}
};
if !tyenv.types[ty.index()].is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-primitive type {}, but found integer literal '{}'",
tyenv.types[ty.index()].name(tyenv),
val,
),
);
}
Some((Pattern::ConstInt(ty, val), ty))
}
&ast::Pattern::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if expected_ty.is_some() && expected_ty != Some(const_ty) {
tyenv.report_error(pos, "Type mismatch for constant");
}
Some((Pattern::ConstPrim(const_ty, val), const_ty))
}
&ast::Pattern::Wildcard { pos } => {
let ty = match expected_ty {
Some(t) => t,
None => {
tyenv.report_error(pos, "Need an implied type for a wildcard");
return None;
}
};
Some((Pattern::Wildcard(ty), ty))
}
&ast::Pattern::And { ref subpats, pos } => {
let mut expected_ty = expected_ty;
let mut children = vec![];
for subpat in subpats {
let (subpat, ty) = unwrap_or_continue!(self.translate_pattern(
tyenv,
subpat,
expected_ty,
bindings,
));
expected_ty = expected_ty.or(Some(ty));
// Normalize nested `And` nodes to a single vector of conjuncts.
match subpat {
Pattern::And(_, subpat_children) => children.extend(subpat_children),
_ => children.push(subpat),
}
}
if expected_ty.is_none() {
tyenv.report_error(pos, "No type for (and ...) form.".to_string());
return None;
}
let ty = expected_ty.unwrap();
Some((Pattern::And(ty, children), ty))
}
&ast::Pattern::BindPattern {
ref var,
ref subpat,
pos,
} => {
// Do the subpattern first so we can resolve the type for sure.
let (subpat, ty) = self.translate_pattern(tyenv, subpat, expected_ty, bindings)?;
let name = tyenv.intern_mut(var);
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!("Re-bound variable name in LHS pattern: '{}'", var.0),
);
// Try to keep going.
}
let id = bindings.add_var(name, ty);
Some((Pattern::BindPattern(ty, id, Box::new(subpat)), ty))
}
&ast::Pattern::Var { ref var, pos } => {
// Look up the variable; if it has already been bound,
// then this becomes a `Var` node (which matches the
// existing bound value), otherwise it becomes a
// `BindPattern` with a wildcard subpattern to capture
// at this location.
let name = tyenv.intern_mut(var);
match bindings.lookup(name) {
None => {
let ty = match expected_ty {
Some(ty) => ty,
None => {
tyenv.report_error(
pos,
format!("Variable pattern '{}' not allowed in context without explicit type", var.0),
);
return None;
}
};
let id = bindings.add_var(name, ty);
Some((
Pattern::BindPattern(ty, id, Box::new(Pattern::Wildcard(ty))),
ty,
))
}
Some(bv) => {
let ty = match expected_ty {
None => bv.ty,
Some(expected_ty) if expected_ty == bv.ty => bv.ty,
Some(expected_ty) => {
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but already-bound var '{}' has type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
var.0,
tyenv.types[bv.ty.index()].name(tyenv)));
bv.ty // Try to keep going for more errors.
}
};
Some((Pattern::Var(ty, bv.id), ty))
}
}
}
&ast::Pattern::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let tid = match self.get_term_by_name(tyenv, sym) {
Some(t) => t,
None => {
tyenv.report_error(pos, format!("Unknown term in pattern: '{}'", sym.0));
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term. Insert an implicit
// converter if needed.
let ret_ty = termdata.ret_ty;
let ty = match expected_ty {
None => ret_ty,
Some(expected_ty) if expected_ty == ret_ty => ret_ty,
Some(expected_ty) => {
// Can we do an implicit type conversion? Look
// up the converter term, if any. If one has
// been registered, and the term has an
// extractor, then build an expanded AST node
// right here and recurse on it.
if let Some(expanded_pattern) =
self.maybe_implicit_convert_pattern(tyenv, pat, ret_ty, expected_ty)
{
return self.translate_pattern(
tyenv,
&expanded_pattern,
Some(expected_ty),
bindings,
);
}
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but term has return type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv)));
ret_ty // Try to keep going for more errors.
}
};
termdata.check_args_count(args, tyenv, pos, sym);
match &termdata.kind {
TermKind::EnumVariant { .. } => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }),
..
} => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { ref template }),
..
} => {
// Expand the extractor macro! We create a map
// from macro args to AST pattern trees and
// then evaluate the template with these
// substitutions.
log!("internal extractor macro args = {:?}", args);
let pat = template.subst_macro_args(&args)?;
return self.translate_pattern(tyenv, &pat, expected_ty, bindings);
}
TermKind::Decl {
extractor_kind: None,
..
} => {
tyenv.report_error(
pos,
format!(
"Cannot use term '{}' that does not have a defined extractor in a \
left-hand side pattern",
sym.0
),
);
}
}
let subpats = self.translate_args(args, termdata, tyenv, bindings);
Some((Pattern::Term(ty, tid, subpats), ty))
}
&ast::Pattern::MacroArg { .. } => unreachable!(),
}
}
fn translate_args(
&self,
args: &Vec<ast::Pattern>,
termdata: &Term,
tyenv: &mut TypeEnv,
bindings: &mut Bindings,
) -> Vec<Pattern> {
args.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| self.translate_pattern(tyenv, arg, Some(arg_ty), bindings))
.map(|(subpat, _)| subpat)
.collect()
}
fn maybe_implicit_convert_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
inner_ty: TypeId,
outer_ty: TypeId,
) -> Option<ast::Expr> {
// Is there a converter for this type mismatch?
if let Some(converter_term) = self.converters.get(&(inner_ty, outer_ty)) {
if self.terms[converter_term.index()].has_constructor() {
let converter_ident = ast::Ident(
tyenv.syms[self.terms[converter_term.index()].name.index()].clone(),
expr.pos(),
);
return Some(ast::Expr::Term {
sym: converter_ident,
pos: expr.pos(),
args: vec![expr.clone()],
});
}
}
None
}
fn translate_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
ty: Option<TypeId>,
bindings: &mut Bindings,
pure: bool,
) -> Option<Expr> {
log!("translate_expr: {:?}", expr);
match expr {
&ast::Expr::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let name = tyenv.intern_mut(&sym);
let tid = match self.term_map.get(&name) {
Some(&t) => t,
None => {
// Maybe this was actually a variable binding and the user has placed
// parens around it by mistake? (See #4775.)
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!(
"Unknown term in expression: '{}'. Variable binding under this name exists; try removing the parens?", sym.0));
} else {
tyenv.report_error(
pos,
format!("Unknown term in expression: '{}'", sym.0),
);
}
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term, and determine whether we
// are doing an implicit conversion. Report an error
// if types don't match and no conversion is possible.
let ret_ty = termdata.ret_ty;
let ty = if ty.is_some() && ret_ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, ret_ty, ty.unwrap())
{
return self.translate_expr(tyenv, &expanded_expr, ty, bindings, pure);
}
tyenv.report_error(
pos,
format!("Mismatched types: expression expects type '{}' but term has return type '{}'",
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv)));
// Keep going, to discover more errors.
ret_ty
} else {
ret_ty
};
// Check that the term's constructor is pure.
if pure {
if let TermKind::Decl { pure: false, .. } = &termdata.kind {
tyenv.report_error(
pos,
format!(
"Used non-pure constructor '{}' in pure expression context",
sym.0
),
);
}
}
termdata.check_args_count(args, tyenv, pos, sym);
// Resolve subexpressions.
let subexprs = args
.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| {
self.translate_expr(tyenv, arg, Some(arg_ty), bindings, pure)
})
.collect();
Some(Expr::Term(ty, tid, subexprs))
}
&ast::Expr::Var { ref name, pos } => {
let sym = tyenv.intern_mut(name);
// Look through bindings, innermost (most recent) first.
let bv = match bindings.lookup(sym) {
None => {
tyenv.report_error(pos, format!("Unknown variable '{}'", name.0));
return None;
}
Some(bv) => bv,
};
// Verify type. Maybe do an implicit conversion.
if ty.is_some() && bv.ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, bv.ty, ty.unwrap())
{
return self.translate_expr(tyenv, &expanded_expr, ty, bindings, pure);
}
tyenv.report_error(
pos,
format!(
"Variable '{}' has type {} but we need {} in context",
name.0,
tyenv.types[bv.ty.index()].name(tyenv),
tyenv.types[ty.unwrap().index()].name(tyenv)
),
);
}
Some(Expr::Var(bv.ty, bv.id))
}
&ast::Expr::ConstInt { val, pos } => {
if ty.is_none() {
tyenv.report_error(
pos,
"integer literal in a context that needs an explicit type".to_string(),
);
return None;
}
let ty = ty.unwrap();
if !tyenv.types[ty.index()].is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-primitive type {}, but found integer literal '{}'",
tyenv.types[ty.index()].name(tyenv),
val,
),
);
}
Some(Expr::ConstInt(ty, val))
}
&ast::Expr::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if ty.is_some() && const_ty != ty.unwrap() {
tyenv.report_error(
pos,
format!(
"Constant '{}' has wrong type: expected {}, but is actually {}",
tyenv.syms[val.index()],
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[const_ty.index()].name(tyenv)
),
);
return None;
}
Some(Expr::ConstPrim(const_ty, val))
}
&ast::Expr::Let {
ref defs,
ref body,
pos,
} => {
let orig_binding_len = bindings.seen.len();
// For each new binding...
let mut let_defs = vec![];
for def in defs {
// Check that the given variable name does not already exist.
let name = tyenv.intern_mut(&def.var);
// Look up the type.
let tid = match tyenv.get_type_by_name(&def.ty) {
Some(tid) => tid,
None => {
tyenv.report_error(
pos,
format!("Unknown type {} for variable '{}'", def.ty.0, def.var.0),
);
continue;
}
};
// Evaluate the variable's value.
let val = Box::new(unwrap_or_continue!(self.translate_expr(
tyenv,
&def.val,
Some(tid),
bindings,
pure
)));
// Bind the var with the given type.
let id = bindings.add_var(name, tid);
let_defs.push((id, tid, val));
}
// Evaluate the body, expecting the type of the overall let-expr.
let body = Box::new(self.translate_expr(tyenv, body, ty, bindings, pure)?);
let body_ty = body.ty();
// Pop the bindings.
bindings.seen.truncate(orig_binding_len);
Some(Expr::Let {
ty: body_ty,
bindings: let_defs,
body,
})
}
}
}