Struct cranelift_isle::lexer::Pos
source · Expand description
A source position.
Fields§
§file: usize
This source position’s file.
Indexes into Lexer::filenames
early in the compiler pipeline, and
later into TypeEnv::filenames
once we get into semantic analysis.
offset: usize
This source position’s byte offset in the file.
line: usize
This source position’s line number in the file.
col: usize
This source position’s column number in the file.
Implementations§
source§impl Pos
impl Pos
sourcepub fn pretty_print_line(&self, filenames: &[Arc<str>]) -> String
pub fn pretty_print_line(&self, filenames: &[Arc<str>]) -> String
Print this source position as file.isle line 12
.
Examples found in repository?
src/codegen.rs (line 227)
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 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 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
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();
}
_ => {}
}
}
}
fn type_name(&self, typeid: TypeId, by_ref: bool) -> String {
match &self.typeenv.types[typeid.index()] {
&Type::Primitive(_, sym, _) => self.typeenv.syms[sym.index()].clone(),
&Type::Enum { name, .. } => {
let r = if by_ref { "&" } else { "" };
format!("{}{}", r, self.typeenv.syms[name.index()])
}
}
}
fn value_name(&self, value: &Value) -> String {
match value {
&Value::Pattern { inst, output } => format!("pattern{}_{}", inst.index(), output),
&Value::Expr { inst, output } => format!("expr{}_{}", inst.index(), output),
}
}
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
}
fn match_variant_binders(
&self,
variant: &Variant,
arg_tys: &[TypeId],
id: InstId,
ctx: &mut BodyContext,
) -> Vec<String> {
arg_tys
.iter()
.zip(variant.fields.iter())
.enumerate()
.map(|(i, (&ty, field))| {
let value = Value::Pattern {
inst: id,
output: i,
};
let valuename = self.value_binder(&value, /* is_ref = */ true, ty);
let fieldname = &self.typeenv.syms[field.name.index()];
self.define_val(&value, ctx, /* is_ref = */ true, field.ty);
format!("{}: {}", fieldname, valuename)
})
.collect::<Vec<_>>()
}
/// Returns a `bool` indicating whether this pattern inst is
/// infallible, and the number of scopes opened.
fn generate_pattern_inst(
&self,
code: &mut String,
id: InstId,
inst: &PatternInst,
indent: &str,
ctx: &mut BodyContext,
) -> (bool, usize) {
match inst {
&PatternInst::Arg { index, ty } => {
let output = Value::Pattern {
inst: id,
output: 0,
};
let outputname = self.value_name(&output);
let is_ref = match &self.typeenv.types[ty.index()] {
&Type::Primitive(..) => false,
_ => true,
};
writeln!(code, "{}let {} = arg{};", indent, outputname, index).unwrap();
self.define_val(
&Value::Pattern {
inst: id,
output: 0,
},
ctx,
is_ref,
ty,
);
(true, 0)
}
&PatternInst::MatchEqual { ref a, ref b, .. } => {
let a = self.value_by_ref(a, ctx);
let b = self.value_by_ref(b, ctx);
writeln!(code, "{}if {} == {} {{", indent, a, b).unwrap();
(false, 1)
}
&PatternInst::MatchInt {
ref input,
int_val,
ty,
..
} => {
let int_val = self.const_int(int_val, ty);
let input = self.value_by_val(input, ctx);
writeln!(code, "{}if {} == {} {{", indent, input, int_val).unwrap();
(false, 1)
}
&PatternInst::MatchPrim { ref input, val, .. } => {
let input = self.value_by_val(input, ctx);
let sym = &self.typeenv.syms[val.index()];
writeln!(code, "{}if {} == {} {{", indent, input, sym).unwrap();
(false, 1)
}
&PatternInst::MatchVariant {
ref input,
input_ty,
variant,
ref arg_tys,
} => {
let input = self.value_by_ref(input, ctx);
let variants = match &self.typeenv.types[input_ty.index()] {
&Type::Primitive(..) => panic!("primitive type input to MatchVariant"),
&Type::Enum { ref variants, .. } => variants,
};
let ty_name = self.type_name(input_ty, /* is_ref = */ true);
let variant = &variants[variant.index()];
let variantname = &self.typeenv.syms[variant.name.index()];
let args = self.match_variant_binders(variant, &arg_tys[..], id, ctx);
let args = if args.is_empty() {
"".to_string()
} else {
format!("{{ {} }}", args.join(", "))
};
writeln!(
code,
"{}if let {}::{} {} = {} {{",
indent, ty_name, variantname, args, input
)
.unwrap();
(false, 1)
}
&PatternInst::Extract {
ref inputs,
ref output_tys,
term,
infallible,
multi,
..
} => {
let termdata = &self.termenv.terms[term.index()];
let sig = termdata.extractor_sig(self.typeenv).unwrap();
let input_values = inputs
.iter()
.map(|input| self.value_by_ref(input, ctx))
.collect::<Vec<_>>();
let output_binders = output_tys
.iter()
.enumerate()
.map(|(i, &ty)| {
let output_val = Value::Pattern {
inst: id,
output: i,
};
self.define_val(&output_val, ctx, /* is_ref = */ false, ty);
self.value_binder(&output_val, /* is_ref = */ false, ty)
})
.collect::<Vec<_>>();
let bind_pattern = format!(
"{open_paren}{vars}{close_paren}",
open_paren = if output_binders.len() == 1 { "" } else { "(" },
vars = output_binders.join(", "),
close_paren = if output_binders.len() == 1 { "" } else { ")" }
);
let etor_call = format!(
"{name}(ctx, {args})",
name = sig.full_name,
args = input_values.join(", ")
);
match (infallible, multi) {
(_, true) => {
writeln!(
code,
"{indent}if let Some(mut iter) = {etor_call} {{",
indent = indent,
etor_call = etor_call,
)
.unwrap();
writeln!(
code,
"{indent} while let Some({bind_pattern}) = iter.next(ctx) {{",
indent = indent,
bind_pattern = bind_pattern,
)
.unwrap();
(false, 2)
}
(false, false) => {
writeln!(
code,
"{indent}if let Some({bind_pattern}) = {etor_call} {{",
indent = indent,
bind_pattern = bind_pattern,
etor_call = etor_call,
)
.unwrap();
(false, 1)
}
(true, false) => {
writeln!(
code,
"{indent}let {bind_pattern} = {etor_call};",
indent = indent,
bind_pattern = bind_pattern,
etor_call = etor_call,
)
.unwrap();
(true, 0)
}
}
}
&PatternInst::Expr {
ref seq, output_ty, ..
} if seq.is_const_int().is_some() => {
let (ty, val) = seq.is_const_int().unwrap();
assert_eq!(ty, output_ty);
let output = Value::Pattern {
inst: id,
output: 0,
};
writeln!(
code,
"{}let {} = {};",
indent,
self.value_name(&output),
self.const_int(val, ty),
)
.unwrap();
self.define_val(&output, ctx, /* is_ref = */ false, ty);
(true, 0)
}
&PatternInst::Expr {
ref seq, output_ty, ..
} => {
let closure_name = format!("closure{}", id.index());
writeln!(code, "{}let mut {} = || {{", indent, closure_name).unwrap();
let subindent = format!("{} ", indent);
let mut subctx = ctx.clone();
let mut returns = vec![];
for (id, inst) in seq.insts.iter().enumerate() {
let id = InstId(id);
let new_scope = self.generate_expr_inst(
code,
id,
inst,
&subindent,
&mut subctx,
&mut returns,
);
assert!(!new_scope);
}
assert_eq!(returns.len(), 1);
writeln!(code, "{}return Some({});", subindent, returns[0].1).unwrap();
writeln!(code, "{}}};", indent).unwrap();
let output = Value::Pattern {
inst: id,
output: 0,
};
writeln!(
code,
"{}if let Some({}) = {}() {{",
indent,
self.value_binder(&output, /* is_ref = */ false, output_ty),
closure_name
)
.unwrap();
self.define_val(&output, ctx, /* is_ref = */ false, output_ty);
(false, 1)
}
}
}
fn generate_body(
&self,
code: &mut String,
depth: usize,
trie: &TrieNode,
indent: &str,
ctx: &mut BodyContext,
is_multi: bool,
) -> bool {
log!("generate_body:\n{}", trie.pretty());
let mut returned = false;
match trie {
&TrieNode::Empty => {}
&TrieNode::Leaf { ref output, .. } => {
writeln!(
code,
"{}// Rule at {}.",
indent,
output.pos.pretty_print_line(&self.typeenv.filenames[..])
)
.unwrap();
// If this is a leaf node, generate the ExprSequence and return.
let mut returns = vec![];
let mut scopes = 0;
let mut indent = indent.to_string();
let orig_indent = indent.clone();
for (id, inst) in output.insts.iter().enumerate() {
let id = InstId(id);
let new_scope =
self.generate_expr_inst(code, id, inst, &indent[..], ctx, &mut returns);
if new_scope {
scopes += 1;
indent.push_str(" ");
}
}
assert_eq!(returns.len(), 1);
if is_multi {
writeln!(code, "{}returns.push({});", indent, returns[0].1).unwrap();
} else {
writeln!(code, "{}return Some({});", indent, returns[0].1).unwrap();
}
for _ in 0..scopes {
writeln!(code, "{}}}", orig_indent).unwrap();
}
returned = !is_multi;
}
&TrieNode::Decision { ref edges } => {
// If this is a decision node, generate each match op
// in turn (in priority order). Gather together
// adjacent MatchVariant ops with the same input and
// disjoint variants in order to create a `match`
// rather than a chain of if-lets.
let mut i = 0;
while i < edges.len() {
// Gather adjacent match variants so that we can turn these
// into a `match` rather than a sequence of `if let`s.
let mut last = i;
let mut adjacent_variants = StableSet::new();
let mut adjacent_variant_input = None;
log!(
"edge: prio = {:?}, symbol = {:?}",
edges[i].prio,
edges[i].symbol
);
while last < edges.len() {
match &edges[last].symbol {
&TrieSymbol::Match {
op: PatternInst::MatchVariant { input, variant, .. },
} => {
if adjacent_variant_input.is_none() {
adjacent_variant_input = Some(input);
}
if adjacent_variant_input == Some(input)
&& !adjacent_variants.contains(&variant)
{
adjacent_variants.insert(variant);
last += 1;
} else {
break;
}
}
_ => {
break;
}
}
}
// Now `edges[i..last]` is a run of adjacent `MatchVariants`
// (possibly an empty one). Only use a `match` form if there
// are at least two adjacent options.
if last - i > 1 {
self.generate_body_matches(
code,
depth,
&edges[i..last],
indent,
ctx,
is_multi,
);
i = last;
continue;
} else {
let &TrieEdge {
ref symbol,
ref node,
..
} = &edges[i];
i += 1;
match symbol {
&TrieSymbol::EndOfMatch => {
returned = self.generate_body(
code,
depth + 1,
node,
indent,
ctx,
is_multi,
);
}
&TrieSymbol::Match { ref op } => {
let id = InstId(depth);
let (infallible, new_scopes) =
self.generate_pattern_inst(code, id, op, indent, ctx);
let mut subindent = indent.to_string();
for _ in 0..new_scopes {
subindent.push_str(" ");
}
let sub_returned = self.generate_body(
code,
depth + 1,
node,
&subindent[..],
ctx,
is_multi,
);
for _ in 0..new_scopes {
writeln!(code, "{}}}", indent).unwrap();
}
if infallible && sub_returned {
returned = true;
break;
}
}
}
}
}
}
}
returned
}
Trait Implementations§
source§impl Ord for Pos
impl Ord for Pos
source§impl PartialOrd<Pos> for Pos
impl PartialOrd<Pos> for Pos
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read more