Enum cranelift_isle::ast::Pattern
source · pub enum Pattern {
Var {
var: Ident,
pos: Pos,
},
BindPattern {
var: Ident,
subpat: Box<Pattern>,
pos: Pos,
},
ConstInt {
val: i128,
pos: Pos,
},
ConstPrim {
val: Ident,
pos: Pos,
},
Term {
sym: Ident,
args: Vec<Pattern>,
pos: Pos,
},
Wildcard {
pos: Pos,
},
And {
subpats: Vec<Pattern>,
pos: Pos,
},
MacroArg {
index: usize,
pos: Pos,
},
}
Expand description
A pattern: the left-hand side of a rule.
Variants§
Var
A mention of a variable.
Equivalent either to a binding (which can be emulated with
BindPattern
with a Pattern::Wildcard
subpattern), if this
is the first mention of the variable, in order to capture its
value; or else a match of the already-captured value. This
disambiguation happens when we lower ast
nodes to sema
nodes as we resolve bound variable names.
BindPattern
An operator that binds a variable to a subterm and matches the subpattern.
ConstInt
An operator that matches a constant integer value.
ConstPrim
An operator that matches an external constant value.
Term
An application of a type variant or term.
Wildcard
An operator that matches anything.
And
N sub-patterns that must all match.
MacroArg
Internal use only: macro argument in a template.
Implementations§
source§impl Pattern
impl Pattern
sourcepub fn root_term(&self) -> Option<&Ident>
pub fn root_term(&self) -> Option<&Ident>
Examples found in repository?
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
fn collect_constructors(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
log!("collect_constructors from def: {:?}", def);
match def {
&ast::Def::Rule(ref rule) => {
let pos = rule.pos;
let term = match rule.pattern.root_term() {
Some(t) => t,
None => {
tyenv.report_error(
pos,
"Rule does not have a term at the LHS root".to_string(),
);
continue;
}
};
let term = match self.get_term_by_name(tyenv, &term) {
Some(tid) => tid,
None => {
tyenv
.report_error(pos, "Rule LHS root term is not defined".to_string());
continue;
}
};
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::Decl {
constructor_kind, ..
} => {
match constructor_kind {
None => {
*constructor_kind = Some(ConstructorKind::InternalConstructor);
}
Some(ConstructorKind::InternalConstructor) => {
// OK, no error; multiple rules can apply to
// one internal constructor term.
}
Some(ConstructorKind::ExternalConstructor { .. }) => {
tyenv.report_error(
pos,
"Rule LHS root term is incorrect kind; cannot \
be external constructor"
.to_string(),
);
continue;
}
}
}
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
"Rule LHS root term is incorrect kind; cannot be enum variant"
.to_string(),
);
continue;
}
}
}
_ => {}
}
}
}
sourcepub fn terms(&self, f: &mut dyn FnMut(Pos, &Ident))
pub fn terms(&self, f: &mut dyn FnMut(Pos, &Ident))
Call f
for each of the terms in this pattern.
Examples found in repository?
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
pub fn terms(&self, f: &mut dyn FnMut(Pos, &Ident)) {
match self {
Pattern::Term { sym, args, pos } => {
f(*pos, sym);
for arg in args {
arg.terms(f);
}
}
Pattern::And { subpats, .. } => {
for p in subpats {
p.terms(f);
}
}
Pattern::BindPattern { subpat, .. } => {
subpat.terms(f);
}
Pattern::Var { .. }
| Pattern::ConstInt { .. }
| Pattern::ConstPrim { .. }
| Pattern::Wildcard { .. }
| Pattern::MacroArg { .. } => {}
}
}
More examples
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
fn collect_extractor_templates(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
let mut extractor_call_graph = BTreeMap::new();
for def in &defs.defs {
if let &ast::Def::Extractor(ref ext) = def {
let term = match self.get_term_by_name(tyenv, &ext.term) {
Some(x) => x,
None => {
tyenv.report_error(
ext.pos,
"Extractor macro body definition on a non-existent term".to_string(),
);
return;
}
};
let template = ext.template.make_macro_template(&ext.args[..]);
log!("extractor def: {:?} becomes template {:?}", def, template);
let mut callees = BTreeSet::new();
template.terms(&mut |pos, t| {
if let Some(term) = self.get_term_by_name(tyenv, t) {
callees.insert(term);
} else {
tyenv.report_error(
pos,
format!(
"`{}` extractor definition references unknown term `{}`",
ext.term.0, t.0
),
);
}
});
extractor_call_graph.insert(term, callees);
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::EnumVariant { .. } => {
tyenv.report_error(
ext.pos,
"Extractor macro body defined on term of incorrect kind; cannot be an \
enum variant",
);
continue;
}
TermKind::Decl {
multi,
extractor_kind,
..
} => match extractor_kind {
None => {
if *multi {
tyenv.report_error(
ext.pos,
"A term declared with `multi` cannot have an internal extractor.".to_string());
continue;
}
*extractor_kind = Some(ExtractorKind::InternalExtractor { template });
}
Some(ext_kind) => {
tyenv.report_error(
ext.pos,
"Duplicate extractor definition".to_string(),
);
let pos = match ext_kind {
ExtractorKind::InternalExtractor { template } => template.pos(),
ExtractorKind::ExternalExtractor { pos, .. } => *pos,
};
tyenv.report_error(
pos,
"Extractor was already defined here".to_string(),
);
continue;
}
},
}
}
}
// Check for cycles in the extractor call graph.
let mut stack = vec![];
'outer: for root in extractor_call_graph.keys().copied() {
stack.clear();
stack.push((root, vec![root], StableSet::new()));
while let Some((caller, path, mut seen)) = stack.pop() {
let is_new = seen.insert(caller);
if is_new {
if let Some(callees) = extractor_call_graph.get(&caller) {
stack.extend(callees.iter().map(|callee| {
let mut path = path.clone();
path.push(*callee);
(*callee, path, seen.clone())
}));
}
} else {
let pos = match &self.terms[caller.index()].kind {
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { template }),
..
} => template.pos(),
_ => {
// There must have already been errors recorded.
assert!(!tyenv.errors.is_empty());
continue 'outer;
}
};
let path: Vec<_> = path
.iter()
.map(|sym| tyenv.syms[sym.index()].as_str())
.collect();
let msg = format!(
"`{}` extractor definition is recursive: {}",
tyenv.syms[root.index()],
path.join(" -> ")
);
tyenv.report_error(pos, msg);
continue 'outer;
}
}
}
}
sourcepub fn make_macro_template(&self, macro_args: &[Ident]) -> Pattern
pub fn make_macro_template(&self, macro_args: &[Ident]) -> Pattern
Examples found in repository?
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 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
pub fn make_macro_template(&self, macro_args: &[Ident]) -> Pattern {
log!("make_macro_template: {:?} with {:?}", self, macro_args);
match self {
&Pattern::BindPattern {
ref var,
ref subpat,
pos,
..
} if matches!(&**subpat, &Pattern::Wildcard { .. }) => {
if let Some(i) = macro_args.iter().position(|arg| arg.0 == var.0) {
Pattern::MacroArg { index: i, pos }
} else {
self.clone()
}
}
&Pattern::BindPattern {
ref var,
ref subpat,
pos,
} => Pattern::BindPattern {
var: var.clone(),
subpat: Box::new(subpat.make_macro_template(macro_args)),
pos,
},
&Pattern::Var { ref var, pos } => {
if let Some(i) = macro_args.iter().position(|arg| arg.0 == var.0) {
Pattern::MacroArg { index: i, pos }
} else {
self.clone()
}
}
&Pattern::And { ref subpats, pos } => {
let subpats = subpats
.iter()
.map(|subpat| subpat.make_macro_template(macro_args))
.collect::<Vec<_>>();
Pattern::And { subpats, pos }
}
&Pattern::Term {
ref sym,
ref args,
pos,
} => {
let args = args
.iter()
.map(|arg| arg.make_macro_template(macro_args))
.collect::<Vec<_>>();
Pattern::Term {
sym: sym.clone(),
args,
pos,
}
}
&Pattern::Wildcard { .. } | &Pattern::ConstInt { .. } | &Pattern::ConstPrim { .. } => {
self.clone()
}
&Pattern::MacroArg { .. } => unreachable!(),
}
}
More examples
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
fn collect_extractor_templates(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
let mut extractor_call_graph = BTreeMap::new();
for def in &defs.defs {
if let &ast::Def::Extractor(ref ext) = def {
let term = match self.get_term_by_name(tyenv, &ext.term) {
Some(x) => x,
None => {
tyenv.report_error(
ext.pos,
"Extractor macro body definition on a non-existent term".to_string(),
);
return;
}
};
let template = ext.template.make_macro_template(&ext.args[..]);
log!("extractor def: {:?} becomes template {:?}", def, template);
let mut callees = BTreeSet::new();
template.terms(&mut |pos, t| {
if let Some(term) = self.get_term_by_name(tyenv, t) {
callees.insert(term);
} else {
tyenv.report_error(
pos,
format!(
"`{}` extractor definition references unknown term `{}`",
ext.term.0, t.0
),
);
}
});
extractor_call_graph.insert(term, callees);
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::EnumVariant { .. } => {
tyenv.report_error(
ext.pos,
"Extractor macro body defined on term of incorrect kind; cannot be an \
enum variant",
);
continue;
}
TermKind::Decl {
multi,
extractor_kind,
..
} => match extractor_kind {
None => {
if *multi {
tyenv.report_error(
ext.pos,
"A term declared with `multi` cannot have an internal extractor.".to_string());
continue;
}
*extractor_kind = Some(ExtractorKind::InternalExtractor { template });
}
Some(ext_kind) => {
tyenv.report_error(
ext.pos,
"Duplicate extractor definition".to_string(),
);
let pos = match ext_kind {
ExtractorKind::InternalExtractor { template } => template.pos(),
ExtractorKind::ExternalExtractor { pos, .. } => *pos,
};
tyenv.report_error(
pos,
"Extractor was already defined here".to_string(),
);
continue;
}
},
}
}
}
// Check for cycles in the extractor call graph.
let mut stack = vec![];
'outer: for root in extractor_call_graph.keys().copied() {
stack.clear();
stack.push((root, vec![root], StableSet::new()));
while let Some((caller, path, mut seen)) = stack.pop() {
let is_new = seen.insert(caller);
if is_new {
if let Some(callees) = extractor_call_graph.get(&caller) {
stack.extend(callees.iter().map(|callee| {
let mut path = path.clone();
path.push(*callee);
(*callee, path, seen.clone())
}));
}
} else {
let pos = match &self.terms[caller.index()].kind {
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { template }),
..
} => template.pos(),
_ => {
// There must have already been errors recorded.
assert!(!tyenv.errors.is_empty());
continue 'outer;
}
};
let path: Vec<_> = path
.iter()
.map(|sym| tyenv.syms[sym.index()].as_str())
.collect();
let msg = format!(
"`{}` extractor definition is recursive: {}",
tyenv.syms[root.index()],
path.join(" -> ")
);
tyenv.report_error(pos, msg);
continue 'outer;
}
}
}
}
sourcepub fn subst_macro_args(&self, macro_args: &[Pattern]) -> Option<Pattern>
pub fn subst_macro_args(&self, macro_args: &[Pattern]) -> Option<Pattern>
Examples found in repository?
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
pub fn subst_macro_args(&self, macro_args: &[Pattern]) -> Option<Pattern> {
log!("subst_macro_args: {:?} with {:?}", self, macro_args);
match self {
&Pattern::BindPattern {
ref var,
ref subpat,
pos,
} => Some(Pattern::BindPattern {
var: var.clone(),
subpat: Box::new(subpat.subst_macro_args(macro_args)?),
pos,
}),
&Pattern::And { ref subpats, pos } => {
let subpats = subpats
.iter()
.map(|subpat| subpat.subst_macro_args(macro_args))
.collect::<Option<Vec<_>>>()?;
Some(Pattern::And { subpats, pos })
}
&Pattern::Term {
ref sym,
ref args,
pos,
} => {
let args = args
.iter()
.map(|arg| arg.subst_macro_args(macro_args))
.collect::<Option<Vec<_>>>()?;
Some(Pattern::Term {
sym: sym.clone(),
args,
pos,
})
}
&Pattern::Var { .. }
| &Pattern::Wildcard { .. }
| &Pattern::ConstInt { .. }
| &Pattern::ConstPrim { .. } => Some(self.clone()),
&Pattern::MacroArg { index, .. } => macro_args.get(index).cloned(),
}
}
More examples
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
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!(),
}
}
sourcepub fn pos(&self) -> Pos
pub fn pos(&self) -> Pos
Examples found in repository?
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
fn collect_extractor_templates(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
let mut extractor_call_graph = BTreeMap::new();
for def in &defs.defs {
if let &ast::Def::Extractor(ref ext) = def {
let term = match self.get_term_by_name(tyenv, &ext.term) {
Some(x) => x,
None => {
tyenv.report_error(
ext.pos,
"Extractor macro body definition on a non-existent term".to_string(),
);
return;
}
};
let template = ext.template.make_macro_template(&ext.args[..]);
log!("extractor def: {:?} becomes template {:?}", def, template);
let mut callees = BTreeSet::new();
template.terms(&mut |pos, t| {
if let Some(term) = self.get_term_by_name(tyenv, t) {
callees.insert(term);
} else {
tyenv.report_error(
pos,
format!(
"`{}` extractor definition references unknown term `{}`",
ext.term.0, t.0
),
);
}
});
extractor_call_graph.insert(term, callees);
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::EnumVariant { .. } => {
tyenv.report_error(
ext.pos,
"Extractor macro body defined on term of incorrect kind; cannot be an \
enum variant",
);
continue;
}
TermKind::Decl {
multi,
extractor_kind,
..
} => match extractor_kind {
None => {
if *multi {
tyenv.report_error(
ext.pos,
"A term declared with `multi` cannot have an internal extractor.".to_string());
continue;
}
*extractor_kind = Some(ExtractorKind::InternalExtractor { template });
}
Some(ext_kind) => {
tyenv.report_error(
ext.pos,
"Duplicate extractor definition".to_string(),
);
let pos = match ext_kind {
ExtractorKind::InternalExtractor { template } => template.pos(),
ExtractorKind::ExternalExtractor { pos, .. } => *pos,
};
tyenv.report_error(
pos,
"Extractor was already defined here".to_string(),
);
continue;
}
},
}
}
}
// Check for cycles in the extractor call graph.
let mut stack = vec![];
'outer: for root in extractor_call_graph.keys().copied() {
stack.clear();
stack.push((root, vec![root], StableSet::new()));
while let Some((caller, path, mut seen)) = stack.pop() {
let is_new = seen.insert(caller);
if is_new {
if let Some(callees) = extractor_call_graph.get(&caller) {
stack.extend(callees.iter().map(|callee| {
let mut path = path.clone();
path.push(*callee);
(*callee, path, seen.clone())
}));
}
} else {
let pos = match &self.terms[caller.index()].kind {
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { template }),
..
} => template.pos(),
_ => {
// There must have already been errors recorded.
assert!(!tyenv.errors.is_empty());
continue 'outer;
}
};
let path: Vec<_> = path
.iter()
.map(|sym| tyenv.syms[sym.index()].as_str())
.collect();
let msg = format!(
"`{}` extractor definition is recursive: {}",
tyenv.syms[root.index()],
path.join(" -> ")
);
tyenv.report_error(pos, msg);
continue 'outer;
}
}
}
}
fn collect_converters(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
match def {
&ast::Def::Converter(ast::Converter {
ref term,
ref inner_ty,
ref outer_ty,
pos,
}) => {
let inner_ty_id = match tyenv.get_type_by_name(inner_ty) {
Some(ty) => ty,
None => {
tyenv.report_error(
inner_ty.1,
format!("Unknown inner type for converter: '{}'", inner_ty.0),
);
continue;
}
};
let outer_ty_id = match tyenv.get_type_by_name(outer_ty) {
Some(ty) => ty,
None => {
tyenv.report_error(
outer_ty.1,
format!("Unknown outer type for converter: '{}'", outer_ty.0),
);
continue;
}
};
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term_id) => term_id,
None => {
tyenv.report_error(
term.1,
format!("Unknown term for converter: '{}'", term.0),
);
continue;
}
};
match self.converters.entry((inner_ty_id, outer_ty_id)) {
Entry::Vacant(v) => {
v.insert(term_id);
}
Entry::Occupied(_) => {
tyenv.report_error(
pos,
format!(
"Converter already exists for this type pair: '{}', '{}'",
inner_ty.0, outer_ty.0
),
);
continue;
}
}
}
_ => {}
}
}
}
fn collect_externs(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
match def {
&ast::Def::Extern(ast::Extern::Constructor {
ref term,
ref func,
pos,
}) => {
let func_sym = tyenv.intern_mut(func);
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term) => term,
None => {
tyenv.report_error(
pos,
format!("Constructor declared on undefined term '{}'", term.0),
);
continue;
}
};
let termdata = &mut self.terms[term_id.index()];
match &mut termdata.kind {
TermKind::Decl {
constructor_kind, ..
} => match constructor_kind {
None => {
*constructor_kind =
Some(ConstructorKind::ExternalConstructor { name: func_sym });
}
Some(ConstructorKind::InternalConstructor) => {
tyenv.report_error(
pos,
format!(
"External constructor declared on term that already has rules: {}",
term.0,
),
);
}
Some(ConstructorKind::ExternalConstructor { .. }) => {
tyenv.report_error(
pos,
"Duplicate external constructor definition".to_string(),
);
}
},
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
format!(
"External constructor cannot be defined on enum variant: {}",
term.0,
),
);
}
}
}
&ast::Def::Extern(ast::Extern::Extractor {
ref term,
ref func,
pos,
infallible,
}) => {
let func_sym = tyenv.intern_mut(func);
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term) => term,
None => {
tyenv.report_error(
pos,
format!("Extractor declared on undefined term '{}'", term.0),
);
continue;
}
};
let termdata = &mut self.terms[term_id.index()];
match &mut termdata.kind {
TermKind::Decl { extractor_kind, .. } => match extractor_kind {
None => {
*extractor_kind = Some(ExtractorKind::ExternalExtractor {
name: func_sym,
infallible,
pos,
});
}
Some(ExtractorKind::ExternalExtractor { pos: pos2, .. }) => {
tyenv.report_error(
pos,
"Duplicate external extractor definition".to_string(),
);
tyenv.report_error(
*pos2,
"External extractor already defined".to_string(),
);
continue;
}
Some(ExtractorKind::InternalExtractor { template }) => {
tyenv.report_error(
pos,
"Cannot define external extractor for term that already has an \
internal extractor macro body defined"
.to_string(),
);
tyenv.report_error(
template.pos(),
"Internal extractor macro body already defined".to_string(),
);
continue;
}
},
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
format!("Cannot define extractor for enum variant '{}'", term.0),
);
continue;
}
}
}
_ => {}
}
}
}
fn collect_rules(&mut self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
match def {
&ast::Def::Rule(ref rule) => {
let pos = rule.pos;
let mut bindings = Bindings::default();
let (sym, args) = if let ast::Pattern::Term { sym, args, .. } = &rule.pattern {
(sym, args)
} else {
tyenv.report_error(
pos,
"Rule does not have a term at the root of its left-hand side"
.to_string(),
);
continue;
};
let root_term = if let Some(term) = self.get_term_by_name(tyenv, sym) {
term
} else {
tyenv.report_error(
pos,
"Cannot define a rule for an unknown term".to_string(),
);
continue;
};
let termdata = &self.terms[root_term.index()];
let pure = match &termdata.kind {
&TermKind::Decl { pure, .. } => pure,
_ => {
tyenv.report_error(
pos,
"Cannot define a rule on a left-hand-side that is an enum variant"
.to_string(),
);
continue;
}
};
termdata.check_args_count(args, tyenv, pos, sym);
let args = self.translate_args(args, termdata, tyenv, &mut bindings);
let iflets = rule
.iflets
.iter()
.filter_map(|iflet| self.translate_iflet(tyenv, iflet, &mut bindings))
.collect();
let rhs = unwrap_or_continue!(self.translate_expr(
tyenv,
&rule.expr,
Some(termdata.ret_ty),
&mut bindings,
pure,
));
let rid = RuleId(self.rules.len());
self.rules.push(Rule {
id: rid,
root_term,
args,
iflets,
rhs,
vars: bindings.seen,
prio: rule.prio.unwrap_or(0),
pos,
});
}
_ => {}
}
}
}
fn check_for_undefined_decls(&self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
if let ast::Def::Decl(decl) = def {
let term = self.get_term_by_name(tyenv, &decl.term).unwrap();
let term = &self.terms[term.index()];
if !term.has_constructor() && !term.has_extractor() {
tyenv.report_error(
decl.pos,
format!(
"no rules, extractor, or external definition for declaration '{}'",
decl.term.0
),
);
}
}
}
}
fn check_for_expr_terms_without_constructors(&self, tyenv: &mut TypeEnv, defs: &ast::Defs) {
for def in &defs.defs {
if let ast::Def::Rule(rule) = def {
rule.expr.terms(&mut |pos, ident| {
let term = match self.get_term_by_name(tyenv, ident) {
None => {
debug_assert!(!tyenv.errors.is_empty());
return;
}
Some(t) => t,
};
let term = &self.terms[term.index()];
if !term.has_constructor() {
tyenv.report_error(
pos,
format!(
"term `{}` cannot be used in an expression because \
it does not have a constructor",
ident.0
),
)
}
});
}
}
}
fn maybe_implicit_convert_pattern(
&self,
tyenv: &mut TypeEnv,
pattern: &ast::Pattern,
inner_ty: TypeId,
outer_ty: TypeId,
) -> Option<ast::Pattern> {
if let Some(converter_term) = self.converters.get(&(inner_ty, outer_ty)) {
if self.terms[converter_term.index()].has_extractor() {
// This is a little awkward: we have to
// convert back to an Ident, to be
// re-resolved. The pos doesn't matter
// as it shouldn't result in a lookup
// failure.
let converter_term_ident = ast::Ident(
tyenv.syms[self.terms[converter_term.index()].name.index()].clone(),
pattern.pos(),
);
let expanded_pattern = ast::Pattern::Term {
sym: converter_term_ident,
pos: pattern.pos(),
args: vec![pattern.clone()],
};
return Some(expanded_pattern);
}
}
None
}